Schema-level multi-tenancy with one common schema #1105
-
Schema-level multi-tenancy with one common schemaI am referring https://alembic.sqlalchemy.org/en/latest/cookbook.html#rudimental-schema-level-multi-tenancy-for-postgresql-databases to implement schema level multi-tenancy. But what if I have an additional schema which is common for the whole database? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 8 replies
-
you would add another option handled by env.py that would also handle this special schema. if you had it explicitly in your models, then you'd bypass the logic that sets the schema, like: from sqlalchemy import text
def run_migrations_online():
connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
special_schema = context.get_x_argument(as_dictionary=True).get("special_schema")
current_tenant = context.get_x_argument(as_dictionary=True).get("tenant")
if current_tenant is None and special_schema is None:
raise Exception("tenant or special_schema expected")
elif current_tenant is not None and special_schema is not None:
raise Exception("tenant and special_schema are mutually exclusive")
with connectable.connect() as connection:
# set search path on the connection, which ensures that
# PostgreSQL will emit all CREATE / ALTER / DROP statements
# in terms of this schema by default
if current_tenant:
connection.execute(text('set search_path to "%s"' % current_tenant))
# make use of non-supported SQLAlchemy attribute to ensure
# the dialect reflects tables in terms of the current tenant name
connection.dialect.default_schema_name = current_tenant
# otherwise it is assumed models have "schema='special_schema'" where they use this
# fixed schema
context.configure(
connection=connection,
target_metadata=target_metadata,
)
with context.begin_transaction():
context.run_migrations() |
Beta Was this translation helpful? Give feedback.
-
In the scope of my project, all tenants will have the same version of tables, so the idea was to have 2 version tables.
I run these commands: alembic -x special_schema=shared revision -m "Initial Migration Shared" --autogenerate With these commands I have the expected result:
The problem is when I try to create a new tenant with the command:
|
Beta Was this translation helpful? Give feedback.
you would add another option handled by env.py that would also handle this special schema. if you had it explicitly in your models, then you'd bypass the logic that sets the schema, like: