SQLAlchemy printing raw SQL from create()

后端 未结 6 2023
别跟我提以往
别跟我提以往 2020-11-30 00:05

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

6条回答
  •  孤城傲影
    2020-11-30 00:26

    May be you mean echo parameter of sqlalchemy.create_engine?

    /tmp$ cat test_s.py

    import sqlalchemy as sa
    from sqlalchemy.ext.declarative import declarative_base
    
    Base = declarative_base()
    
    class Department(Base):
        __tablename__ = "departments"
    
        department_id = sa.Column(sa.types.Integer, primary_key=True)
        name = sa.Column(sa.types.Unicode(100), unique=True)
        chief_id = sa.Column(sa.types.Integer)
        parent_department_id = sa.Column(sa.types.Integer,
                                         sa.ForeignKey("departments.department_id"))
    
        parent_department = sa.orm.relation("Department")
    
    
    engine = sa.create_engine("sqlite:///:memory:", echo=True)
    Base.metadata.create_all(bind=engine)
    

    /tmp$ python test_s.py

    2011-03-24 15:09:58,311 INFO sqlalchemy.engine.base.Engine.0x...42cc PRAGMA table_info("departments")
    2011-03-24 15:09:58,312 INFO sqlalchemy.engine.base.Engine.0x...42cc ()
    2011-03-24 15:09:58,312 INFO sqlalchemy.engine.base.Engine.0x...42cc 
    CREATE TABLE departments (
        department_id INTEGER NOT NULL, 
        name VARCHAR(100), 
        chief_id INTEGER, 
        parent_department_id INTEGER, 
        PRIMARY KEY (department_id), 
        UNIQUE (name), 
        FOREIGN KEY(parent_department_id) REFERENCES departments (department_id)
    )
    
    2011-03-24 15:09:58,312 INFO sqlalchemy.engine.base.Engine.0x...42cc ()
    2011-03-24 15:09:58,312 INFO sqlalchemy.engine.base.Engine.0x...42cc COMMIT
    

提交回复
热议问题