full-stack-fastapi-template icon indicating copy to clipboard operation
full-stack-fastapi-template copied to clipboard

How to add a db schema to this

Open lesourcil opened this issue 4 years ago • 3 comments

Hi normally to add a schema in sqlalchemy i do Base = declarative_base() Base.metadata.schema = 'schema_name

How can i add this to this stack please ?

lesourcil avatar Sep 30 '20 15:09 lesourcil

This template has most of the groundwork laid for you and already and includes a User model (along with an authentication flow) and an Item example model. Take a look into the backend/model and backend/schema directories to get started. Plus the docs have got you covered: https://fastapi.tiangolo.com/tutorial/sql-databases/

teschmitt avatar Oct 02 '20 06:10 teschmitt

@teschmitt I'm not sure your answer here address the question raised by @lesourcil

If I spin up a stack from this template then during migrations tables get created in the public schema in the DB.

Altering the db.base_class to have some metadata

from sqlalchemy import MetaData

@as_declarative(metadata=MetaData(schema='some_schema_name'))
...

should setup the models to be under some_schema_name

  • Though getting alembic to create this schema is another story.

Andrew-Sheridan avatar Apr 22 '21 18:04 Andrew-Sheridan

In the alembic.env file if you update run_migrations() to

def run_migrations(connection):
    context.configure(connection=connection, target_metadata=target_metadata, compare_type=True,        include_schemas=True,
        version_table_schema="some_schema_name")

    connection.execute(text("CREATE SCHEMA IF NOT EXISTS some_schema_name"))
    with context.begin_transaction():
        context.run_migrations()
  • then the schema will be created

Andrew-Sheridan avatar Apr 22 '21 18:04 Andrew-Sheridan