Moved CSV sources into pokedex/.
[zzz-pokedex.git] / pokedex / __init__.py
1 # encoding: utf8
2 import sys
3
4 from .db import connect, metadata
5
6 def main():
7 if len(sys.argv) <= 1:
8 help()
9
10 command = sys.argv[1]
11 args = sys.argv[2:]
12
13 # Find the command as a function in this file
14 func = globals().get(command, None)
15 if func and callable(func) and command != 'main':
16 func(*args)
17 else:
18 help()
19
20
21 def csvimport(engine_uri, dir='.'):
22 import csv
23
24 from sqlalchemy.orm.attributes import instrumentation_registry
25
26 session = connect(engine_uri)
27
28 metadata.create_all()
29
30 # This is a secret attribute on a secret singleton of a secret class that
31 # appears to hopefully contain all registered classes as keys.
32 # There is no other way to accomplish this, as far as I can tell.
33 # Fuck.
34 for table in sorted(instrumentation_registry.manager_finders.keys(),
35 key=lambda self: self.__table__.name):
36 table_name = table.__table__.name
37 print table_name
38
39 reader = csv.reader(open("%s/%s.csv" % (dir, table_name), 'rb'), lineterminator='\n')
40 columns = [unicode(column) for column in reader.next()]
41
42 for csvs in reader:
43 row = table()
44
45 for column, value in zip(columns, csvs):
46 value = value.decode('utf-8')
47 setattr(row, column, value)
48
49 session.add(row)
50
51 session.commit()
52
53
54 def csvexport(engine_uri, dir='.'):
55 import csv
56 session = connect(engine_uri)
57
58 for table_name in sorted(metadata.tables.keys()):
59 print table_name
60 table = metadata.tables[table_name]
61
62 writer = csv.writer(open("%s/%s.csv" % (dir, table_name), 'wb'), lineterminator='\n')
63 columns = [col.name for col in table.columns]
64 writer.writerow(columns)
65
66 for row in session.query(table).all():
67 csvs = []
68 for col in columns:
69 # Convert Pythony values to something more universal
70 val = getattr(row, col)
71 if val == None:
72 val = ''
73 elif val == True:
74 val = '1'
75 elif val == False:
76 val = '0'
77 else:
78 val = unicode(val).encode('utf-8')
79
80 csvs.append(val)
81
82 writer.writerow(csvs)
83
84
85 def help():
86 print u"""pokedex -- a command-line Pokédex interface
87
88 help Displays this message.
89
90 These commands are only useful for developers:
91 csvimport {uri} [dir] Import data from a set of CSVs to the database
92 given by the URI.
93 csvexport {uri} [dir] Export data from the database given by the URI
94 to a set of CSVs.
95 Directory defaults to cwd.
96 """
97
98 sys.exit(0)