Added Surfing Pikachu and Volt Tackle Pichu. #14
[zzz-pokedex.git] / pokedex / __init__.py
1 # encoding: utf8
2 import sys
3
4 from sqlalchemy.exc import IntegrityError
5 import sqlalchemy.types
6
7 from .db import connect, metadata, tables as tables_module
8 from pokedex.lookup import lookup as pokedex_lookup
9
10 def main():
11 if len(sys.argv) <= 1:
12 help()
13
14 command = sys.argv[1]
15 args = sys.argv[2:]
16
17 # Find the command as a function in this file
18 func = globals().get("command_%s" % command, None)
19 if func:
20 func(*args)
21 else:
22 command_help()
23
24
25 def command_csvimport(engine_uri, directory='.'):
26 import csv
27
28 from sqlalchemy.orm.attributes import instrumentation_registry
29
30 session = connect(engine_uri)
31
32 metadata.create_all()
33
34 # SQLAlchemy is retarded and there is no way for me to get a list of ORM
35 # classes besides to inspect the module they all happen to live in for
36 # things that look right.
37 table_base = tables_module.TableBase
38 orm_classes = {} # table object => table class
39
40 for name in dir(tables_module):
41 # dir() returns strings! How /convenient/.
42 thingy = getattr(tables_module, name)
43
44 if not isinstance(thingy, type):
45 # Not a class; bail
46 continue
47 elif not issubclass(thingy, table_base):
48 # Not a declarative table; bail
49 continue
50 elif thingy == table_base:
51 # Declarative table base, so not a real table; bail
52 continue
53
54 # thingy is definitely a table class! Hallelujah.
55 orm_classes[thingy.__table__] = thingy
56
57 # Okay, run through the tables and actually load the data now
58 for table_obj in metadata.sorted_tables:
59 table_class = orm_classes[table_obj]
60 table_name = table_obj.name
61
62 # Print the table name but leave the cursor in a fixed column
63 print table_name + '...', ' ' * (40 - len(table_name)),
64 sys.stdout.flush()
65
66 try:
67 csvfile = open("%s/%s.csv" % (directory, table_name), 'rb')
68 except IOError:
69 # File doesn't exist; don't load anything!
70 print 'no data!'
71 continue
72
73 reader = csv.reader(csvfile, lineterminator='\n')
74 column_names = [unicode(column) for column in reader.next()]
75
76 # Self-referential tables may contain rows with foreign keys of other
77 # rows in the same table that do not yet exist. Pull these out and add
78 # them to the session last
79 # ASSUMPTION: Self-referential tables have a single PK called "id"
80 deferred_rows = [] # ( row referring to id, [foreign ids we need] )
81 seen_ids = {} # primary key we've seen => 1
82
83 # Fetch foreign key columns that point at this table, if any
84 self_ref_columns = []
85 for column in table_obj.c:
86 if any(_.references(table_obj) for _ in column.foreign_keys):
87 self_ref_columns.append(column)
88
89 for csvs in reader:
90 row = table_class()
91
92 for column_name, value in zip(column_names, csvs):
93 column = table_obj.c[column_name]
94 if column.nullable and value == '':
95 # Empty string in a nullable column really means NULL
96 value = None
97 elif isinstance(column.type, sqlalchemy.types.Boolean):
98 # Boolean values are stored as string values 0/1, but both
99 # of those evaluate as true; SQLA wants True/False
100 if value == '0':
101 value = False
102 else:
103 value = True
104 else:
105 # Otherwise, unflatten from bytes
106 value = value.decode('utf-8')
107
108 setattr(row, column_name, value)
109
110 # May need to stash this row and add it later if it refers to a
111 # later row in this table
112 if self_ref_columns:
113 foreign_ids = [getattr(row, _.name) for _ in self_ref_columns]
114 foreign_ids = [_ for _ in foreign_ids if _] # remove NULL ids
115
116 if not foreign_ids:
117 # NULL key. Remember this row and add as usual.
118 seen_ids[row.id] = 1
119
120 elif all(_ in seen_ids for _ in foreign_ids):
121 # Non-NULL key we've already seen. Remember it and commit
122 # so we know the old row exists when we add the new one
123 session.commit()
124 seen_ids[row.id] = 1
125
126 else:
127 # Non-NULL future id. Save this and insert it later!
128 deferred_rows.append((row, foreign_ids))
129 continue
130
131 session.add(row)
132
133 session.commit()
134
135 # Attempt to add any spare rows we've collected
136 for row, foreign_ids in deferred_rows:
137 if not all(_ in seen_ids for _ in foreign_ids):
138 # Could happen if row A refers to B which refers to C.
139 # This is ridiculous and doesn't happen in my data so far
140 raise ValueError("Too many levels of self-reference! "
141 "Row was: " + str(row.__dict__))
142
143 session.add(row)
144 seen_ids[row.id] = 1
145 session.commit()
146
147 print 'loaded'
148
149 def command_csvexport(engine_uri, directory='.'):
150 import csv
151 session = connect(engine_uri)
152
153 for table_name in sorted(metadata.tables.keys()):
154 print table_name
155 table = metadata.tables[table_name]
156
157 writer = csv.writer(open("%s/%s.csv" % (directory, table_name), 'wb'),
158 lineterminator='\n')
159 columns = [col.name for col in table.columns]
160 writer.writerow(columns)
161
162 primary_key = table.primary_key
163 for row in session.query(table).order_by(*primary_key).all():
164 csvs = []
165 for col in columns:
166 # Convert Pythony values to something more universal
167 val = getattr(row, col)
168 if val == None:
169 val = ''
170 elif val == True:
171 val = '1'
172 elif val == False:
173 val = '0'
174 else:
175 val = unicode(val).encode('utf-8')
176
177 csvs.append(val)
178
179 writer.writerow(csvs)
180
181 def command_lookup(engine_uri, name):
182 # XXX don't require uri! somehow
183 session = connect(engine_uri)
184
185 results, exact = pokedex_lookup(session, name)
186 if exact:
187 print "Matched:"
188 else:
189 print "Fuzzy-matched:"
190
191 for object in results:
192 print object.__tablename__, object.name
193
194
195 def command_help():
196 print u"""pokedex -- a command-line Pokédex interface
197
198 help Displays this message.
199 lookup {uri} [name] Look up something in the Pokédex.
200
201 These commands are only useful for developers:
202 csvimport {uri} [dir] Import data from a set of CSVs to the database
203 given by the URI.
204 csvexport {uri} [dir] Export data from the database given by the URI
205 to a set of CSVs.
206 Directory defaults to cwd.
207 """.encode(sys.getdefaultencoding(), 'replace')
208
209 sys.exit(0)