Reordered some rows in mapping tables.
[zzz-pokedex.git] / pokedex / __init__.py
1 # encoding: utf8
2 import sys
3
4 import sqlalchemy.types
5
6 from .db import connect, metadata
7
8 def main():
9 if len(sys.argv) <= 1:
10 help()
11
12 command = sys.argv[1]
13 args = sys.argv[2:]
14
15 # Find the command as a function in this file
16 func = globals().get(command, None)
17 if func and callable(func) and command != 'main':
18 func(*args)
19 else:
20 help()
21
22
23 def csvimport(engine_uri, dir='.'):
24 import csv
25
26 from sqlalchemy.orm.attributes import instrumentation_registry
27
28 session = connect(engine_uri)
29
30 metadata.create_all()
31
32 # Oh, mysql-chan.
33 # TODO try to insert data in preorder so we don't need this hack and won't
34 # break similarly on other engines
35 if 'mysql' in engine_uri:
36 session.execute('SET FOREIGN_KEY_CHECKS = 0')
37
38 # This is a secret attribute on a secret singleton of a secret class that
39 # appears to hopefully contain all registered classes as keys.
40 # There is no other way to accomplish this, as far as I can tell.
41 # Fuck.
42 for table in sorted(instrumentation_registry.manager_finders.keys(),
43 key=lambda self: self.__table__.name):
44 table_name = table.__table__.name
45 # Print the table name but leave the cursor in a fixed column
46 print table_name + '...', ' ' * (40 - len(table_name)),
47
48 try:
49 csvfile = open("%s/%s.csv" % (dir, table_name), 'rb')
50 except IOError:
51 # File doesn't exist; don't load anything!
52 print 'no data!'
53 continue
54
55 reader = csv.reader(csvfile, lineterminator='\n')
56 column_names = [unicode(column) for column in reader.next()]
57
58 for csvs in reader:
59 row = table()
60
61 for column_name, value in zip(column_names, csvs):
62 column = table.__table__.c[column_name]
63 if column.nullable and value == '':
64 # Empty string in a nullable column really means NULL
65 value = None
66 elif isinstance(column.type, sqlalchemy.types.Boolean):
67 # Boolean values are stored as string values 0/1, but both
68 # of those evaluate as true; SQLA wants True/False
69 if value == '0':
70 value = False
71 else:
72 value = True
73 else:
74 # Otherwise, unflatten from bytes
75 value = value.decode('utf-8')
76
77 setattr(row, column_name, value)
78
79 session.add(row)
80
81 session.commit()
82 print 'loaded'
83
84 # Shouldn't matter since this is usually the end of the program and thus
85 # the connection too, but let's change this back just in case
86 if 'mysql' in engine_uri:
87 session.execute('SET FOREIGN_KEY_CHECKS = 1')
88
89
90 def csvexport(engine_uri, dir='.'):
91 import csv
92 session = connect(engine_uri)
93
94 for table_name in sorted(metadata.tables.keys()):
95 print table_name
96 table = metadata.tables[table_name]
97
98 writer = csv.writer(open("%s/%s.csv" % (dir, table_name), 'wb'), lineterminator='\n')
99 columns = [col.name for col in table.columns]
100 writer.writerow(columns)
101
102 for row in session.query(table).all():
103 csvs = []
104 for col in columns:
105 # Convert Pythony values to something more universal
106 val = getattr(row, col)
107 if val == None:
108 val = ''
109 elif val == True:
110 val = '1'
111 elif val == False:
112 val = '0'
113 else:
114 val = unicode(val).encode('utf-8')
115
116 csvs.append(val)
117
118 writer.writerow(csvs)
119
120
121 def help():
122 print u"""pokedex -- a command-line Pokédex interface
123
124 help Displays this message.
125
126 These commands are only useful for developers:
127 csvimport {uri} [dir] Import data from a set of CSVs to the database
128 given by the URI.
129 csvexport {uri} [dir] Export data from the database given by the URI
130 to a set of CSVs.
131 Directory defaults to cwd.
132 """
133
134 sys.exit(0)