Created
June 23, 2012 15:04
-
-
Save happy15/2978596 to your computer and use it in GitHub Desktop.
model definition generator for Storm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
#coding=utf8 | |
# generate models definition automatically from database schema | |
# TODO add relationship between classes | |
from storm.locals import * | |
def class_name(table_name): | |
return '%s%s' % (table_name[0].upper(), table_name[1:]) | |
def property_type(field_type): | |
if field_type == 'tinyint(1)': | |
return 'Bool()' | |
elif field_type.startswith( | |
('tinyint', 'smallint', 'mediumint', 'int', 'bigint')): | |
return 'Int()' | |
elif field_type.startswith(('float', 'real', 'double precision')): | |
return 'Float()' | |
elif field_type.startswith(('decimal', 'numeric')): | |
return 'Decimal()' | |
elif field_type.startswith(('varchar', 'char', 'text', 'longtext', 'tinytext', 'mediumtext')): | |
return 'Unicode()' | |
elif field_type.startswith(('datetime', 'timestamp')): | |
return 'DateTime()' | |
elif field_type.startswith('time'): | |
return 'Time()' | |
elif field_type.startswith(('blob', 'binary', 'varbinary')): | |
return 'Pickle()' | |
db = create_database("...") | |
store = Store(db) | |
res = store.execute('show tables') | |
for tname, in res: | |
print 'class %s(Storm):' % class_name(tname) | |
print ' __storm_table__ = "%s"' % tname | |
for f in store.execute('desc %s' % tname): | |
print ' %s = %s' % (f[0], property_type(f[1])) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment