Schema-level multi-tenancy with one common schema #1105
Answered
by
zzzeek
Gayathri-A-R
asked this question in
Usage Questions
-
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.
Answered by
zzzeek
Oct 20, 2022
Replies: 1 comment 7 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.
7 replies
Answer selected by
Gayathri-A-R
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: