Search code examples
pythonsqlalchemypylons

SQLAlchemy printing raw SQL from create()


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?


Solution

  • from sqlalchemy.schema import CreateTable
        
    print(CreateTable(table))
    

    If you are using declarative syntax:

    print(CreateTable(Model.__table__))
    

    Update:

    Since I have the accepted answer and there is important information in klenwell answer, I'll also add it here.

    You can get the SQL for your specific database (MySQL, Postgresql, etc.) by compiling with your engine.

    print(CreateTable(Model.__table__).compile(engine))
    

    Update 2:

    @jackotonye Added in the comments a way to do it without an engine.

    from sqlalchemy.schema import CreateTable
    from sqlalchemy.dialects import postgresql
    
    print(CreateTable(Model.__table__).compile(dialect=postgresql.dialect()))