17e982d0ba191972dc073d717998e81082523e95
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 columns
= [unicode(column
) for column
in reader
.next()]
51 for column
, value
in zip(columns
, csvs
):
52 value
= value
.decode('utf-8')
53 setattr(row
, column
, value
)
59 # Shouldn't matter since this is usually the end of the program and thus
60 # the connection too, but let's change this back just in case
61 if 'mysql' in engine_uri
:
62 session
.execute('SET FOREIGN_KEY_CHECKS = 1')
65 def csvexport(engine_uri
, dir='.'):
67 session
= connect(engine_uri
)
69 for table_name
in sorted(metadata
.tables
.keys()):
71 table
= metadata
.tables
[table_name
]
73 writer
= csv
.writer(open("%s/%s.csv" %
(dir, table_name
), 'wb'), lineterminator
='\n')
74 columns
= [col
.name
for col
in table
.columns
]
75 writer
.writerow(columns
)
77 for row
in session
.query(table
).all():
80 # Convert Pythony values to something more universal
81 val
= getattr(row
, col
)
89 val
= unicode(val
).encode('utf-8')
97 print u
"""pokedex -- a command-line Pokédex interface
99 help Displays this message.
101 These commands are only useful for developers:
102 csvimport {uri} [dir] Import data from a set of CSVs to the database
104 csvexport {uri} [dir] Export data from the database given by the URI
106 Directory defaults to cwd.