4 import sqlalchemy
.types
6 from .db
import connect
, metadata
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':
23 def csvimport(engine_uri
, dir='.'):
26 from sqlalchemy
.orm
.attributes
import instrumentation_registry
28 session
= connect(engine_uri
)
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')
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.
42 for table
in sorted(instrumentation_registry
.manager_finders
.keys(),
43 key
=lambda self
: self
.__table__
.name
):
44 table_name
= table
.__table__
.name
47 reader
= csv
.reader(open("%s/%s.csv" %
(dir, table_name
), 'rb'), lineterminator
='\n')
48 column_names
= [unicode(column
) for column
in reader
.next()]
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
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
66 # Otherwise, unflatten from bytes
67 value
= value
.decode('utf-8')
69 setattr(row
, column_name
, value
)
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')
81 def csvexport(engine_uri
, dir='.'):
83 session
= connect(engine_uri
)
85 for table_name
in sorted(metadata
.tables
.keys()):
87 table
= metadata
.tables
[table_name
]
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
)
93 for row
in session
.query(table
).all():
96 # Convert Pythony values to something more universal
97 val
= getattr(row
, col
)
105 val
= unicode(val
).encode('utf-8')
109 writer
.writerow(csvs
)
113 print u
"""pokedex -- a command-line Pokédex interface
115 help Displays this message.
117 These commands are only useful for developers:
118 csvimport {uri} [dir] Import data from a set of CSVs to the database
120 csvexport {uri} [dir] Export data from the database given by the URI
122 Directory defaults to cwd.