e8f23e6f26e19dc7c732bf4d7f8f0b340126e4ff
[sitecorepy.git] / sitecore / prof / export_mysql.py
1 #!/usr/bin/env python
2 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
3 #
4 # This file is part of SiteCorePy.
5 #
6 # SiteCorePy is free software; you can redistribute it and/or modify it
7 # under the terms of the GNU General Public License as published by the
8 # Free Software Foundation, either version 2 of the License, or (at your
9 # option) any later version.
10 #
11 # SiteCorePy is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 # General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with SiteCorePy.  If not, see <http://www.gnu.org/licenses/>.
18
19 """Move Professors from MySQL -> YAML.
20
21 Not really SiteCore related, but it seves as an example of what to do
22 before calling prof_import.
23 """
24
25 import getpass
26 import logging
27
28 import MySQLdb
29 import yaml
30
31 from .. import get_logger
32 from . import Name, Graduation, Contact, Bio, Professor
33
34
35 class SimpleDB (object):
36     def __init__(self, verbose=0):
37         self.db = None
38         self.cursor = None
39         self.table = None
40         self.logger = get_logger(verbose)
41
42     def connect(database, host='localhost',
43                 username=None, password=None):
44         if username == None:
45             username = getpass.getpass('username: ')
46         if password == None:
47             password = getpass.getpass('password: ')
48         self.db = MySQLdb.connect(host=host, user=username,
49                                   passwd=password, db=database)
50         del(username)
51         del(password)
52         self.cursor = self.db.cursor()
53
54     def disconnect(self):
55         self.cursor = None
56         self.db.close()
57
58     def set_default_table(self, table):
59         self.table = table
60
61     def add_entry(self, dict, table=None):
62         if table == None:
63             table = self.table
64         dict = self._clean_dict(dict)
65         keys = dict.keys()
66         values = ["'%s'" % dict[key] for key in keys]
67         self.cursor.execute("INSERT INTO %s (%s) VALUES (%s)"
68                             % (table, ', '.join(keys), ', '.join(values)))
69         # error checking
70
71     def list_entries(self, dict=None, table=None):
72         if table == None:
73             table = self.table
74         where = self._where_string(dict)
75         self.cursor.execute('SELECT * FROM %s%s' % (table, where))
76         numrows = int(self.cursor.rowcount)
77         print '\t'.join([dtuple[0] for dtuple in self.cursor.description])
78         for x in range(0,numrows):
79             row = self.cursor.fetchone()
80             print '\t'.join(['%s' % x for x in row])
81
82     def delete_entries(self, dict, table=None):
83         if table == None:
84             table = self.table
85         where = self._where_string(dict)
86         self.cursor.execute('DELETE FROM %s%s' % (table, where))
87
88     def _clean_dict(self, dict=None):
89         if dict == None:
90             return None
91         for key in dict.keys():
92             value = dict.pop(key)
93             value = MySQLdb.escape_string(value)
94             key = MySQLdb.escape_string(key)
95             assert key not in dict, '%s in %s!' % (key, dict)
96             dict[key] = value
97         return dict
98
99     def _where_string(self, dict=None):
100         dict = self._clean_dict(dict)
101         if dict == None or len(dict) == 0:
102             where = ''
103         else:
104             where_args = []
105             for key,value in dict.items():
106                 where_args.append("%s='%s'" % (key,value))
107             where = 'where %s' % ' and '.join(where_args)
108         return where
109
110
111 def get_profs(db):
112     """
113 mysql> describe people;
114 +--------------+--------------+------+-----+---------+----------------+
115 | Field        | Type         | Null | Key | Default | Extra          |
116 +--------------+--------------+------+-----+---------+----------------+
117 | ID           | int(11)      | NO   | PRI | NULL    | auto_increment | 
118 | category     | varchar(255) | YES  |     | NULL    |                | 
119 | lastname     | varchar(255) | YES  |     | NULL    |                | 
120 | firstname    | varchar(255) | YES  |     | NULL    |                | 
121 | email        | varchar(255) | YES  |     | NULL    |                | 
122 | office       | varchar(255) | YES  |     | NULL    |                | 
123 | phone        | varchar(255) | YES  |     | NULL    |                | 
124 | lab          | varchar(255) | YES  |     | NULL    |                | 
125 | labphone     | varchar(255) | YES  |     | NULL    |                | 
126 | grouppage    | varchar(255) | YES  |     | NULL    |                | 
127 | personalpage | varchar(255) | YES  |     | NULL    |                | 
128 | position     | varchar(255) | YES  |     | NULL    |                | 
129 | position1    | varchar(255) | YES  |     | NULL    |                | 
130 | degrees      | varchar(255) | YES  |     | NULL    |                | 
131 | research     | mediumtext   | YES  |     | NULL    |                | 
132 | profile      | mediumtext   | YES  |     | NULL    |                | 
133 +--------------+--------------+------+-----+---------+----------------+
134 16 rows in set (0.00 sec)
135
136 Where the relevant categories are
137 | Faculty            | 
138 | Research Faculty   | 
139 | Teaching Faculty   | 
140 | Professor Emeritus | 
141 | Adjunct Professor  | 
142     """
143     db.set_default_table('people')
144     for category in ['Faculty',
145                      'Research Faculty',
146                      'Teaching Faculty',
147                      'Professor Emeritus',
148                      'Adjunct Professor']:
149         for prof in db.list_entries({'category':category}):
150             p = Professor()
151             TODO
152             yield p
153
154
155 def main(argv):
156     import optparse
157     usage = """%prog [options] PROF_FILE
158
159 Where PROF_FILE is the output YAML file receiving professor data.
160
161 Example:
162   ./sc.py prof-export_mysql profs.yaml
163 """
164     p = optparse.OptionParser(usage)
165     p.add_option('-d', '--database', metavar='NAME', dest='database',
166                  help='Name of the MySQL database (%default)',
167                  default='directory')
168     p.add_option('-v', '--verbose', dest='verbose', action='count',
169                  help='increment verbosity (%default)',
170                  default=0)
171
172     options,args = p.parse_args(argv)
173     prof_file = args[0]
174
175     db = SimpleDB(verbose=options.verbose)
176     db.connect(database=options.database)
177     try:
178         profs = list(get_profs(db))
179     finally:
180         db.disconnect()
181
182     yaml.save(db, profs)