简体   繁体   中英

SQLAlchemy + Postgres (print created types, e.g. enum types)

I would like to be able to get info about what types will be created during SQLAlchemy's create_all(). Yes, they can be printed if I set up echo-ing of generated SQL, but how can i print it without actually hitting database? For example, I have a model:

class MyModel(Base):
    id = Column(Integer, primary_key=True)
    indexed_field = Column(String(50))
    enum_field = Column(Enum(MyEnum))

    __table_args__ = (
        Index("my_ix", indexed_field),
    )

where MyEnum is:

class MyEnum(enum.Enum):
    A = 0
    B = 1

I can get CREATE TABLE statement and all CREATE INDEX statements like this:

from sqlalchemy.schema import CreateTable, CreateIndex

print(str(CreateTable(MyModel.__table__).compile(postgres_engine)))
for idx in MyModel.__table__.indexes:
    print(str(CreateIndex(idx)).compile(postgres_engine))

Result will be something like that:

CREATE TABLE my_model (
    id SERIAL NOT NULL, 
    indexed_field VARCHAR(50), 
    enum_field myenum, 
    PRIMARY KEY (id)
)
CREATE INDEX my_ix ON my_model (indexed_field)

Notice the line enum_field myenum . How can I get generated SQL for CREATE TYPE myenum... statement?

I've found the answer!

from sqlalchemy.dialects.postgresql.base import PGInspector
PGInspector(postgres_engine).get_enums()

It returns a list of all created enums, which IMO is even better than raw sql, documentation is here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM