Created
April 11, 2015 17:38
-
-
Save eirnym/d9079e5eee380450f464 to your computer and use it in GitHub Desktop.
SQLAlchemy dump SQL and metadata create_all and drop_all usage example. This is highly usable with aiopg and similar library where synchronised version of engine is not applicable.
This file contains hidden or 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
from sqlalchemy_dump import dump_sql | |
def create_all_sql(metadata): | |
return dump_sql(metadata.create_all, bind=True)() | |
def drop_all_sql(metadata): | |
return dumpsql(metadata.drop_all, bind=True)() |
This file contains hidden or 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
def dump_sql(func, bind=False): | |
@wraps(func) | |
def func_wrapper(*args, **kwargs): | |
out = StringIO() | |
def dump(sql, *multiparams, **params): | |
out.write('{};\n'.format(str(sql.compile(dialect=dump.dialect)).strip())) | |
engine = sqlalchemy.create_engine('postgres://', strategy='mock', executor=dump) | |
dump.dialect = engine.dialect | |
if bind: | |
func(*args, bind=engine, **kwargs) | |
else: | |
func(engine, *args, **kwargs) | |
return out.getvalue() | |
return func_wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment