SQLAlchemy printing raw SQL from create()

Viewed 33094

I am giving Pylons a try with SQLAlchemy, and I love it, there is just one thing, is it possible to print out the raw SQL CREATE TABLE data generated from Table().create() before it's executed?

6 Answers

You can set up you engine to dump the metadata creation sequence, using the following:

def metadata_dump(sql, *multiparams, **params):
    # print or write to log or file etc
    print(sql.compile(dialect=engine.dialect))

engine = create_engine(myDatabaseURL, strategy='mock', executor=metadata_dump)
metadata.create_all(engine)

One advantage of this approach is that enums and indexes are included in the printout. Using CreateTable leaves this out.

Another advantage is that the order of the schema definitions is correct and (almost) usable as a script.

Related