Added encounter data for Diamond, Pearl, and Platinum.
[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 table_name
46
47 reader = csv.reader(open("%s/%s.csv" % (dir, table_name), 'rb'), lineterminator='\n')
48 column_names = [unicode(column) for column in reader.next()]
49
50 for csvs in reader:
51 row = table()
52
53 for column_name, value in zip(column_names, csvs):
54 column = table.__table__.c[column_name]
55 if column.nullable and value == '':
56 # Empty string in a nullable column really means NULL
57 value = None
58 elif isinstance(column.type, sqlalchemy.types.Boolean):
59 # Boolean values are stored as string values 0/1, but both
60 # of those evaluate as true; SQLA wants True/False
61 if value == '0':
62 value = False
63 else:
64 value = True
65 else:
66 # Otherwise, unflatten from bytes
67 value = value.decode('utf-8')
68
69 setattr(row, column_name, value)
70
71 session.add(row)
72
73 session.commit()
74
75 # Shouldn't matter since this is usually the end of the program and thus
76 # the connection too, but let's change this back just in case
77 if 'mysql' in engine_uri:
78 session.execute('SET FOREIGN_KEY_CHECKS = 1')
79
80
81 def csvexport(engine_uri, dir='.'):
82 import csv
83 session = connect(engine_uri)
84
85 for table_name in sorted(metadata.tables.keys()):
86 print table_name
87 table = metadata.tables[table_name]
88
89 writer = csv.writer(open("%s/%s.csv" % (dir, table_name), 'wb'), lineterminator='\n')
90 columns = [col.name for col in table.columns]
91 writer.writerow(columns)
92
93 for row in session.query(table).all():
94 csvs = []
95 for col in columns:
96 # Convert Pythony values to something more universal
97 val = getattr(row, col)
98 if val == None:
99 val = ''
100 elif val == True:
101 val = '1'
102 elif val == False:
103 val = '0'
104 else:
105 val = unicode(val).encode('utf-8')
106
107 csvs.append(val)
108
109 writer.writerow(csvs)
110
111
112 def help():
113 print u"""pokedex -- a command-line Pokédex interface
114
115 help Displays this message.
116
117 These commands are only useful for developers:
118 csvimport {uri} [dir] Import data from a set of CSVs to the database
119 given by the URI.
120 csvexport {uri} [dir] Export data from the database given by the URI
121 to a set of CSVs.
122 Directory defaults to cwd.
123 """
124
125 sys.exit(0)