简体   繁体   中英

How to create a table with schema in SQLModel?

I want to create a table with schema "fooschema" and name "footable" . Based on this GitHub issue and to some extent the docs, I tried

fooMetadata = MetaData(schema="fooschema")

class Foo(SQLModel, table=True):
    __tablename__ = "footable"
    metadata = fooMetadata

    id_: int = Field(primary_key=True)

engine = create_engine("<url>")

Foo.metadata.create_all(engine)
with Session(engine) as session:
    row = Foo(id_=0)
    session.add(row)
    session.commit()
    session.refresh(row)

and tried replacing metadata = fooMetadata with __table_args__ = {"schema": "fooSchema"} , and replacing Foo.metadata.create_all with SQLModel.metadata.create_all but I'm always getting an error like

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "fooschema.footable" does not exist

or

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.InvalidSchemaName) schema "fooschema" does not exist

Oddly __table_args__ works for reading an existing table, just not creating it.

I solved this by explicitly creating the schema with

    with engine.connect() as connection:
        connection.execute(CreateSchema("fooschema"))
        connection.commit()

Note this is sort of answered in this answer but it's not particularly clear and this question is about SQLModel specifically.

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