Added some Pokémon methods to hide form weirdness. #5
[zzz-pokedex.git] / pokedex / __init__.py
1 # encoding: utf8
2 import sys
3
4 import sqlalchemy.types
5
6 from .db import connect, metadata, tables as tables_module
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, directory='.'):
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 # SQLAlchemy is retarded and there is no way for me to get a list of ORM
33 # classes besides to inspect the module they all happen to live in for
34 # things that look right.
35 table_base = tables_module.TableBase
36 orm_classes = {} # table object => table class
37
38 for name in dir(tables_module):
39 # dir() returns strings! How /convenient/.
40 thingy = getattr(tables_module, name)
41
42 if not isinstance(thingy, type):
43 # Not a class; bail
44 continue
45 elif not issubclass(thingy, table_base):
46 # Not a declarative table; bail
47 continue
48 elif thingy == table_base:
49 # Declarative table base, so not a real table; bail
50 continue
51
52 # thingy is definitely a table class! Hallelujah.
53 orm_classes[thingy.__table__] = thingy
54
55 # Okay, run through the tables and actually load the data now
56 for table_obj in metadata.sorted_tables:
57 table_class = orm_classes[table_obj]
58 table_name = table_obj.name
59
60 # Print the table name but leave the cursor in a fixed column
61 print table_name + '...', ' ' * (40 - len(table_name)),
62
63 try:
64 csvfile = open("%s/%s.csv" % (directory, table_name), 'rb')
65 except IOError:
66 # File doesn't exist; don't load anything!
67 print 'no data!'
68 continue
69
70 reader = csv.reader(csvfile, lineterminator='\n')
71 column_names = [unicode(column) for column in reader.next()]
72
73 for csvs in reader:
74 row = table_class()
75
76 for column_name, value in zip(column_names, csvs):
77 column = table_obj.c[column_name]
78 if column.nullable and value == '':
79 # Empty string in a nullable column really means NULL
80 value = None
81 elif isinstance(column.type, sqlalchemy.types.Boolean):
82 # Boolean values are stored as string values 0/1, but both
83 # of those evaluate as true; SQLA wants True/False
84 if value == '0':
85 value = False
86 else:
87 value = True
88 else:
89 # Otherwise, unflatten from bytes
90 value = value.decode('utf-8')
91
92 setattr(row, column_name, value)
93
94 session.add(row)
95
96 session.commit()
97 print 'loaded'
98
99
100 def csvexport(engine_uri, directory='.'):
101 import csv
102 session = connect(engine_uri)
103
104 for table_name in sorted(metadata.tables.keys()):
105 print table_name
106 table = metadata.tables[table_name]
107
108 writer = csv.writer(open("%s/%s.csv" % (directory, table_name), 'wb'),
109 lineterminator='\n')
110 columns = [col.name for col in table.columns]
111 writer.writerow(columns)
112
113 for row in session.query(table).all():
114 csvs = []
115 for col in columns:
116 # Convert Pythony values to something more universal
117 val = getattr(row, col)
118 if val == None:
119 val = ''
120 elif val == True:
121 val = '1'
122 elif val == False:
123 val = '0'
124 else:
125 val = unicode(val).encode('utf-8')
126
127 csvs.append(val)
128
129 writer.writerow(csvs)
130
131
132 def help():
133 print u"""pokedex -- a command-line Pokédex interface
134
135 help Displays this message.
136
137 These commands are only useful for developers:
138 csvimport {uri} [dir] Import data from a set of CSVs to the database
139 given by the URI.
140 csvexport {uri} [dir] Export data from the database given by the URI
141 to a set of CSVs.
142 Directory defaults to cwd.
143 """
144
145 sys.exit(0)