Home > Software engineering >  How to create a table with schema in SQLModel?
How to create a table with schema in SQLModel?

Time:01-31

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.

CodePudding user response:

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.

  • Related