2014-05-14 22:21:18 -07:00
import config
import MySQLdb
PHONE_NUM_COL = 2
class LibAddrBook :
def __init__ ( self ) :
self . db = MySQLdb . connect ( user = config . MYSQL_USER , passwd = config . MYSQL_PASSWD , db = config . MYSQL_DB )
def get_everyone ( self ) :
c = self . db . cursor ( )
2014-05-17 19:58:34 -07:00
c . execute ( """ SELECT * from people ORDER BY people.name ASC """ )
self . db . commit ( )
2014-05-15 01:44:45 -07:00
ppl = [ ]
2014-05-14 22:21:18 -07:00
nums = [ ]
for row in c . fetchall ( ) :
print ( row )
2014-05-15 01:44:45 -07:00
print ( row [ 0 ] )
2014-05-14 22:21:18 -07:00
nums . append ( row [ PHONE_NUM_COL ] )
2014-05-15 01:44:45 -07:00
ppl . append ( { ' id ' : row [ 0 ] , ' name ' : row [ 1 ] } )
2014-05-14 22:21:18 -07:00
2014-05-15 01:44:45 -07:00
return ppl
def get_groups ( self ) :
c = self . db . cursor ( )
c . execute ( """ SELECT * from groups """ )
2014-05-17 19:58:34 -07:00
self . db . commit ( )
2014-05-15 01:44:45 -07:00
groups = [ ]
for row in c . fetchall ( ) :
groups . append ( { ' gid ' : row [ 0 ] , ' name ' : row [ 1 ] } )
return groups
# todo: make sure ids is actually a list of numbers?
def get_nums_with_ids ( self , ids ) :
2014-05-17 19:58:34 -07:00
if len ( ids ) == 0 : return [ ]
2014-05-15 01:44:45 -07:00
c = self . db . cursor ( )
idlist = ' , ' . join ( ' {} ' . format ( x ) for x in ids )
print idlist
c . execute ( """ SELECT * from people WHERE id IN ( {} ) """ . format ( idlist ) )
2014-05-17 19:58:34 -07:00
self . db . commit ( )
2014-05-15 01:44:45 -07:00
nums = [ ]
for row in c . fetchall ( ) :
nums . append ( row [ PHONE_NUM_COL ] )
2014-05-14 22:21:18 -07:00
return nums
2014-05-15 01:44:45 -07:00
def get_people_in_groups ( self , groups ) :
if ( len ( groups ) == 0 ) :
return [ ]
# /!\ SPECIAL CASE ALERT: A group ID of -1 signifies that 'everyone' is selected, so use that function instead.
if ( - 1 in groups ) :
return [ p [ ' id ' ] for p in self . get_everyone ( ) ]
c = self . db . cursor ( )
grouplist = ' , ' . join ( ' {} ' . format ( x ) for x in groups )
print grouplist
c . execute ( """ SELECT people.id from people INNER JOIN memberships ON people.id = memberships.person_id WHERE memberships.group_id IN ( {} ) """ . format ( grouplist ) )
2014-05-17 19:58:34 -07:00
self . db . commit ( )
2014-05-15 01:44:45 -07:00
ids = [ r [ 0 ] for r in c . fetchall ( ) ]
return ids
2014-05-18 14:26:37 -07:00
def add_person ( self , name , num ) :
c = self . db . cursor ( )
try :
c . execute ( """ INSERT INTO people (name, phonenum) VALUES ( %s , %s ) """ , ( name , num ) )
self . db . commit ( )
return True
except :
print " error adding user "
self . db . rollback ( )
return False