4 from .db
import connect
, metadata
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':
21 def csvimport(engine_uri
, dir='.'):
24 from sqlalchemy
.orm
.attributes
import instrumentation_registry
26 session
= connect(engine_uri
)
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')
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.
40 for table
in sorted(instrumentation_registry
.manager_finders
.keys(),
41 key
=lambda self
: self
.__table__
.name
):
42 table_name
= table
.__table__
.name
45 reader
= csv
.reader(open("%s/%s.csv" %
(dir, table_name
), 'rb'), lineterminator
='\n')
46 column_names
= [unicode(column
) for column
in reader
.next()]
51 for column_name
, value
in zip(column_names
, csvs
):
52 if table
.__table__
.c
[column_name
].nullable
and value
== '':
53 # Empty string in a nullable column really means NULL
56 # Otherwise, unflatten from bytes
57 value
= value
.decode('utf-8')
59 setattr(row
, column_name
, value
)
65 # Shouldn't matter since this is usually the end of the program and thus
66 # the connection too, but let's change this back just in case
67 if 'mysql' in engine_uri
:
68 session
.execute('SET FOREIGN_KEY_CHECKS = 1')
71 def csvexport(engine_uri
, dir='.'):
73 session
= connect(engine_uri
)
75 for table_name
in sorted(metadata
.tables
.keys()):
77 table
= metadata
.tables
[table_name
]
79 writer
= csv
.writer(open("%s/%s.csv" %
(dir, table_name
), 'wb'), lineterminator
='\n')
80 columns
= [col
.name
for col
in table
.columns
]
81 writer
.writerow(columns
)
83 for row
in session
.query(table
).all():
86 # Convert Pythony values to something more universal
87 val
= getattr(row
, col
)
95 val
= unicode(val
).encode('utf-8')
103 print u
"""pokedex -- a command-line Pokédex interface
105 help Displays this message.
107 These commands are only useful for developers:
108 csvimport {uri} [dir] Import data from a set of CSVs to the database
110 csvexport {uri} [dir] Export data from the database given by the URI
112 Directory defaults to cwd.