Skip to content

Instantly share code, notes, and snippets.

@AndreaCrotti
Created August 10, 2015 12:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndreaCrotti/69d5e1005b844782c6fc to your computer and use it in GitHub Desktop.
Save AndreaCrotti/69d5e1005b844782c6fc to your computer and use it in GitHub Desktop.
print out schema from sqlalchemy
import argparse
import inspect
from importlib import import_module
from sqlalchemy import create_engine
from sqlalchemy.schema import CreateTable
from skim.slxmodels.meta import BaseModel
def _pred(m):
"""Extract the models
"""
try:
return issubclass(m, BaseModel) and m != BaseModel
except TypeError:
return False
def _table_for_model(model, engine):
table_sql = CreateTable(getattr(model, '__table__'))
return str(table_sql), str(table_sql.compile(engine))
def parse_arguments():
parser = argparse.ArgumentParser(description='model')
parser.add_argument('-f', '--file',
help='Full path to the the models file, for example skim.slxmodels.currencies.models',
required=True)
parser.add_argument('-m', '--model',
help='model to produce the SQL for')
parser.add_argument('--db_url', required=True)
return parser.parse_args()
def main():
ns = parse_arguments()
models = import_module(ns.file)
engine = create_engine(ns.db_url)
res = {}
if ns.model:
mod = getattr(models, ns.model)
res[mod.__name__] = _table_for_model(mod, engine)
else:
for m in inspect.getmembers(models, predicate=_pred):
mod = getattr(models, m[0])
res[mod.__name__] = _table_for_model(mod, engine)
for table_name, (agnostic, specific) in res.items():
print("-- Creating table name {}".format(table_name))
print(specific)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment