17e982d0ba191972dc073d717998e81082523e95
[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 # Oh, mysql-chan.
31 # TODO try to insert data in preorder so we don't need this hack and won't
32 # break similarly on other engines
33 if 'mysql' in engine_uri:
34 session.execute('SET FOREIGN_KEY_CHECKS = 0')
35
36 # This is a secret attribute on a secret singleton of a secret class that
37 # appears to hopefully contain all registered classes as keys.
38 # There is no other way to accomplish this, as far as I can tell.
39 # Fuck.
40 for table in sorted(instrumentation_registry.manager_finders.keys(),
41 key=lambda self: self.__table__.name):
42 table_name = table.__table__.name
43 print table_name
44
45 reader = csv.reader(open("%s/%s.csv" % (dir, table_name), 'rb'), lineterminator='\n')
46 columns = [unicode(column) for column in reader.next()]
47
48 for csvs in reader:
49 row = table()
50
51 for column, value in zip(columns, csvs):
52 value = value.decode('utf-8')
53 setattr(row, column, value)
54
55 session.add(row)
56
57 session.commit()
58
59 # Shouldn't matter since this is usually the end of the program and thus
60 # the connection too, but let's change this back just in case
61 if 'mysql' in engine_uri:
62 session.execute('SET FOREIGN_KEY_CHECKS = 1')
63
64
65 def csvexport(engine_uri, dir='.'):
66 import csv
67 session = connect(engine_uri)
68
69 for table_name in sorted(metadata.tables.keys()):
70 print table_name
71 table = metadata.tables[table_name]
72
73 writer = csv.writer(open("%s/%s.csv" % (dir, table_name), 'wb'), lineterminator='\n')
74 columns = [col.name for col in table.columns]
75 writer.writerow(columns)
76
77 for row in session.query(table).all():
78 csvs = []
79 for col in columns:
80 # Convert Pythony values to something more universal
81 val = getattr(row, col)
82 if val == None:
83 val = ''
84 elif val == True:
85 val = '1'
86 elif val == False:
87 val = '0'
88 else:
89 val = unicode(val).encode('utf-8')
90
91 csvs.append(val)
92
93 writer.writerow(csvs)
94
95
96 def help():
97 print u"""pokedex -- a command-line Pokédex interface
98
99 help Displays this message.
100
101 These commands are only useful for developers:
102 csvimport {uri} [dir] Import data from a set of CSVs to the database
103 given by the URI.
104 csvexport {uri} [dir] Export data from the database given by the URI
105 to a set of CSVs.
106 Directory defaults to cwd.
107 """
108
109 sys.exit(0)