A first attempt at MySQL -> Professor() conversion
[sitecorepy.git] / sitecore / prof / export_mysql.py
index 88871deb6f24a3e7b886d510263ba5ca8f54ef7d..15af27ca73b4c9ff57d78476bd9f68ab32520604 100644 (file)
@@ -39,12 +39,14 @@ class SimpleDB (object):
         self.table = None
         self.logger = get_logger(verbose)
 
-    def connect(database, host='localhost',
+    def connect(self, database, host='localhost',
                 username=None, password=None):
         if username == None:
             username = getpass.getpass('username: ')
         if password == None:
             password = getpass.getpass('password: ')
+        self.logger.info('logging in to %s:%s as %s'
+                         % (host, database, username))
         self.db = MySQLdb.connect(host=host, user=username,
                                   passwd=password, db=database)
         del(username)
@@ -52,59 +54,66 @@ class SimpleDB (object):
         self.cursor = self.db.cursor()
 
     def disconnect(self):
+        self.logger.info('disconnecting')
         self.cursor = None
         self.db.close()
 
+    def execute(self, command):
+        self.logger.info(command)
+        self.cursor.execute(command)
+
     def set_default_table(self, table):
         self.table = table
 
-    def add_entry(self, dict, table=None):
-        if table = None:
+    def add_entry(self, dict_, table=None):
+        if table == None:
             table = self.table
-        dict = self._clean_dict(dict)
-        keys = dict.keys()
-        values = ["'%s'" % dict[key] for key in keys]
-        self.cursor.execute("INSERT INTO %s (%s) VALUES (%s)"
-                            % (table, ', '.join(keys), ', '.join(values)))
+        dict_ = self._clean_dict(dict_)
+        keys = dict_.keys()
+        values = ["'%s'" % dict_[key] for key in keys]
+        self.execute("INSERT INTO %s (%s) VALUES (%s)"
+                     % (table, ', '.join(keys), ', '.join(values)))
         # error checking
 
-    def list_entries(self, dict=None, table=None):
-        if table = None:
+    def list_entries(self, dict_=None, table=None):
+        if table == None:
             table = self.table
-        where = self._where_string(dict)
-        self.cursor.execute('SELECT * FROM %s%s' % (table, where))
+        where = self._where_string(dict_)
+        self.execute('SELECT * FROM %s%s' % (table, where))
         numrows = int(self.cursor.rowcount)
-        print '\t'.join([dtuple[0] for dtuple in self.cursor.description])
+        fields = [dtuple[0] for dtuple in self.cursor.description]
+        ret = []
         for x in range(0,numrows):
             row = self.cursor.fetchone()
-            print '\t'.join(['%s' % x for x in row])
+            ret.append(dict(zip(fields, row)))
+        return ret
 
-    def delete_entries(self, dict, table=None):
-        if table = None:
+    def delete_entries(self, dict_, table=None):
+        if table == None:
             table = self.table
-        where = self._where_string(dict)
-        self.cursor.execute('DELETE FROM %s%s' % (table, where))
+        where = self._where_string(dict_)
+        self.execute('DELETE FROM %s%s' % (table, where))
 
-    def _clean_dict(self, dict=None):
-        if dict == None:
+    def _clean_dict(self, dict_=None):
+        if dict_ == None:
             return None
-        for key in dict.keys():
-            value = dict.pop(key)
+        for key in dict_.keys():
+            value = dict_.pop(key)
             value = MySQLdb.escape_string(value)
             key = MySQLdb.escape_string(key)
-            assert key not in dict, '%s in %s!' % (key, dict)
-            dict[key] = value
-        return dict
+            assert key not in dict_, '%s in %s!' % (key, dict_)
+            dict_[key] = value
+        return dict_
 
-    def _where_string(self, dict=None):
-        dict = self._clean_dict(dict)
-        if dict == None or len(dict) == 0:
+    def _where_string(self, dict_=None):
+        dict_ = self._clean_dict(dict_)
+        if dict_ == None or len(dict_) == 0:
             where = ''
         else:
             where_args = []
-            for key,value in dict.items():
+            for key,value in dict_.items():
                 where_args.append("%s='%s'" % (key,value))
-            where = 'where %s' % ' and '.join(where_args)
+            where = ' where %s' % ' and '.join(where_args)
         return where
 
 
@@ -148,30 +157,59 @@ Where the relevant categories are
                      'Adjunct Professor']:
         for prof in db.list_entries({'category':category}):
             p = Professor()
-            TODO
+            p.name = Name(
+                first_middle=prof['firstname'],
+                last=prof['lastname'],
+                )
+            p.title = prof['position1']
+            if len(prof['position2']) > 0:
+                p.title += ', %s' % prof['position2']
+            p.graduations = []
+            print prof['degrees']
+            for degree in prof['degrees']:
+                g.greaduations.append(
+                    Graduation(
+                        college=None,
+                        title=None,
+                        year=None,
+                        )
+                    )
+            p.contact = Contact(
+                office=prof['office'],
+                email=prof['email'],
+                website=prof['personalpage'],
+                phone=prof['phone'],
+                lab=prof['lab'],
+                lab_phone=prof['labphone'],
+                )
+            p.bio = Bio(
+                specialization=prof['research'], # prof['grouppage']
+                publications=None,
+                profile=prof['profile'],
+                cv=None,
+                )
+            self.logger.debug(unicode(p))
             yield p
 
 
-if __name__ == '__main__':
+def main(argv):
     import optparse
     usage = """%prog [options] PROF_FILE
 
 Where PROF_FILE is the output YAML file receiving professor data.
 
 Example:
-  ./sitecore/prof/export_mysql.py profs.yaml
+  ./sc.py prof-export_mysql profs.yaml
 """
     p = optparse.OptionParser(usage)
     p.add_option('-d', '--database', metavar='NAME', dest='database',
                  help='Name of the MySQL database (%default)',
                  default='directory')
-    p.add_option(
     p.add_option('-v', '--verbose', dest='verbose', action='count',
                  help='increment verbosity (%default)',
                  default=0)
 
-    options,args = p.parse_args()
-                   ]
+    options,args = p.parse_args(argv)
     prof_file = args[0]
 
     db = SimpleDB(verbose=options.verbose)