Overhauled CLI. #180
[zzz-pokedex.git] / pokedex / db / load.py
1 """CSV to database or vice versa."""
2 import csv
3 import os.path
4 import pkg_resources
5 import re
6 import sys
7
8 from sqlalchemy.orm.attributes import instrumentation_registry
9 import sqlalchemy.sql.util
10 import sqlalchemy.types
11
12 from pokedex.db import metadata
13 import pokedex.db.tables as tables
14
15
16 def _wildcard_char_to_regex(char):
17 """Converts a single wildcard character to the regex equivalent."""
18
19 if char == '?':
20 return '.?'
21 elif char == '*':
22 return '.*'
23 else:
24 return re.escape(char)
25
26 def _wildcard_glob_to_regex(glob):
27 """Converts a single wildcard glob to a regex STRING."""
28
29 # If it looks like a filename, make it not one
30 if '.' in glob or '/' in glob:
31 _, filename = os.path.split(glob)
32 table_name, _ = os.path.splitext(filename)
33 glob = table_name
34
35 return u''.join(map(_wildcard_char_to_regex, glob))
36
37 def _wildcards_to_regex(strings):
38 """Converts a list of wildcard globs to a single regex object."""
39
40 regex_parts = map(_wildcard_glob_to_regex, strings)
41
42 regex = '^(?:' + '|'.join(regex_parts) + ')$'
43
44 return re.compile(regex)
45
46
47 def _get_verbose_prints(verbose):
48 """If `verbose` is true, returns two functions: one for printing a starting
49 message, and the other for printing a success or failure message when
50 finished.
51
52 If `verbose` is false, returns two no-op functions.
53 """
54
55 if verbose:
56 import sys
57 def print_start(thing):
58 # Truncate to 66 characters, leaving 10 characters for a success
59 # or failure message
60 truncated_thing = thing[0:66]
61
62 # Also, space-pad to keep the cursor in a known column
63 num_spaces = 66 - len(truncated_thing)
64
65 print "%s...%s" % (truncated_thing, ' ' * num_spaces),
66 sys.stdout.flush()
67
68 def print_done(msg='ok'):
69 print msg
70 sys.stdout.flush()
71
72 return print_start, print_done
73
74 # Not verbose; return dummies
75 def dummy(*args, **kwargs):
76 pass
77
78 return dummy, dummy
79
80
81 def load(session, tables=[], directory=None, drop_tables=False, verbose=False):
82 """Load data from CSV files into the given database session.
83
84 Tables are created automatically.
85
86 `session`
87 SQLAlchemy session to use.
88
89 `tables`
90 List of tables to load. If omitted, all tables are loaded.
91
92 `directory`
93 Directory the CSV files reside in. Defaults to the `pokedex` data
94 directory.
95
96 `drop_tables`
97 If set to True, existing `pokedex`-related tables will be dropped.
98
99 `verbose`
100 If set to True, status messages will be printed to stdout.
101 """
102
103 # First take care of verbosity
104 print_start, print_done = _get_verbose_prints(verbose)
105
106
107 if not directory:
108 directory = pkg_resources.resource_filename('pokedex', 'data/csv')
109
110 if tables:
111 regex = _wildcards_to_regex(tables)
112 table_names = filter(regex.match, metadata.tables.keys())
113 else:
114 table_names = metadata.tables.keys()
115
116 table_objs = [metadata.tables[name] for name in table_names]
117 table_objs = sqlalchemy.sql.util.sort_tables(table_objs)
118
119
120 # Drop all tables if requested
121 if drop_tables:
122 print_start('Dropping tables')
123 for table in reversed(table_objs):
124 table.drop(checkfirst=True)
125 print_done()
126
127 for table in table_objs:
128 table.create()
129 connection = session.connection()
130
131 # Okay, run through the tables and actually load the data now
132 for table_obj in table_objs:
133 table_name = table_obj.name
134 insert_stmt = table_obj.insert()
135
136 print_start(table_name)
137
138 try:
139 csvfile = open("%s/%s.csv" % (directory, table_name), 'rb')
140 except IOError:
141 # File doesn't exist; don't load anything!
142 print_done('missing?')
143 continue
144
145 reader = csv.reader(csvfile, lineterminator='\n')
146 column_names = [unicode(column) for column in reader.next()]
147
148 # Self-referential tables may contain rows with foreign keys of other
149 # rows in the same table that do not yet exist. Pull these out and add
150 # them to the session last
151 # ASSUMPTION: Self-referential tables have a single PK called "id"
152 deferred_rows = [] # ( row referring to id, [foreign ids we need] )
153 seen_ids = {} # primary key we've seen => 1
154
155 # Fetch foreign key columns that point at this table, if any
156 self_ref_columns = []
157 for column in table_obj.c:
158 if any(_.references(table_obj) for _ in column.foreign_keys):
159 self_ref_columns.append(column)
160
161 new_rows = []
162 def insert_and_commit():
163 session.connection().execute(insert_stmt, new_rows)
164 session.commit()
165 new_rows[:] = []
166
167 for csvs in reader:
168 row_data = {}
169
170 for column_name, value in zip(column_names, csvs):
171 column = table_obj.c[column_name]
172 if column.nullable and value == '':
173 # Empty string in a nullable column really means NULL
174 value = None
175 elif isinstance(column.type, sqlalchemy.types.Boolean):
176 # Boolean values are stored as string values 0/1, but both
177 # of those evaluate as true; SQLA wants True/False
178 if value == '0':
179 value = False
180 else:
181 value = True
182 else:
183 # Otherwise, unflatten from bytes
184 value = value.decode('utf-8')
185
186 # nb: Dictionaries flattened with ** have to have string keys
187 row_data[ str(column_name) ] = value
188
189 # May need to stash this row and add it later if it refers to a
190 # later row in this table
191 if self_ref_columns:
192 foreign_ids = [row_data[_.name] for _ in self_ref_columns]
193 foreign_ids = [_ for _ in foreign_ids if _] # remove NULL ids
194
195 if not foreign_ids:
196 # NULL key. Remember this row and add as usual.
197 seen_ids[row_data['id']] = 1
198
199 elif all(_ in seen_ids for _ in foreign_ids):
200 # Non-NULL key we've already seen. Remember it and commit
201 # so we know the old row exists when we add the new one
202 insert_and_commit()
203 seen_ids[row_data['id']] = 1
204
205 else:
206 # Non-NULL future id. Save this and insert it later!
207 deferred_rows.append((row_data, foreign_ids))
208 continue
209
210 # Insert row!
211 new_rows.append(row_data)
212
213 # Remembering some zillion rows in the session consumes a lot of
214 # RAM. Let's not do that. Commit every 1000 rows
215 if len(new_rows) >= 1000:
216 insert_and_commit()
217
218 insert_and_commit()
219
220 # Attempt to add any spare rows we've collected
221 for row_data, foreign_ids in deferred_rows:
222 if not all(_ in seen_ids for _ in foreign_ids):
223 # Could happen if row A refers to B which refers to C.
224 # This is ridiculous and doesn't happen in my data so far
225 raise ValueError("Too many levels of self-reference! "
226 "Row was: " + str(row))
227
228 session.connection().execute(
229 insert_stmt.values(**row_data)
230 )
231 seen_ids[row_data['id']] = 1
232 session.commit()
233
234 print_done()
235
236
237
238 def dump(session, tables=[], directory=None, verbose=False):
239 """Dumps the contents of a database to a set of CSV files. Probably not
240 useful to anyone besides a developer.
241
242 `session`
243 SQLAlchemy session to use.
244
245 `tables`
246 List of tables to dump. If omitted, all tables are dumped.
247
248 `directory`
249 Directory the CSV files should be put in. Defaults to the `pokedex`
250 data directory.
251
252 `verbose`
253 If set to True, status messages will be printed to stdout.
254 """
255
256 # First take care of verbosity
257 print_start, print_done = _get_verbose_prints(verbose)
258
259
260 if not directory:
261 directory = pkg_resources.resource_filename('pokedex', 'data/csv')
262
263 if tables:
264 regex = _wildcards_to_regex(tables)
265 table_names = filter(regex.match, metadata.tables.keys())
266 else:
267 table_names = metadata.tables.keys()
268
269 table_names.sort()
270
271
272 for table_name in table_names:
273 print_start(table_name)
274 table = metadata.tables[table_name]
275
276 writer = csv.writer(open("%s/%s.csv" % (directory, table_name), 'wb'),
277 lineterminator='\n')
278 columns = [col.name for col in table.columns]
279 writer.writerow(columns)
280
281 primary_key = table.primary_key
282 for row in session.query(table).order_by(*primary_key).all():
283 csvs = []
284 for col in columns:
285 # Convert Pythony values to something more universal
286 val = getattr(row, col)
287 if val == None:
288 val = ''
289 elif val == True:
290 val = '1'
291 elif val == False:
292 val = '0'
293 else:
294 val = unicode(val).encode('utf-8')
295
296 csvs.append(val)
297
298 writer.writerow(csvs)
299
300 print_done()