1

I have a flask application and trying to make it multi-tenant using multiple schemas in a single database.

When an alteration needed to the database like adding a column, adding a table, and other alterations. I need to migrate through each to schemas. I changed my migrations/env.py like below

def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
engine = engine_from_config(
            config.get_section(config.config_ini_section),
            prefix='sqlalchemy.',
            poolclass=pool.NullPool)

# schemas = set([prototype_schema,None])

connection = engine.connect()
context.configure(
    connection=connection,
    target_metadata=target_metadata,
    include_schemas=True, #schemas,
    # include_object=include_schemas([None,prototype_schema])
    include_object=include_schemas([None])

)

try:
    domains = ['public', 'test', 'some_schema_name']
    for domain in domains:
        connection.execute('set search_path to "{}", public'.format(domain))
        with context.begin_transaction():
            context.run_migrations()

finally:
    connection.close()

The migrations are only affecting the first schema in the array. Here the public only gets migrated. I need to migrate across all schemas.

Abhishek Aravindan
  • 1,432
  • 6
  • 23
  • 1
    I think this `connection.execute('set search_path to "{}", public'.format(domain))` should not have the `, public` . Like this it will always set in public – kakou Jun 24 '21 at 06:56
  • @KarolosK. If I remove the `public` i will get `ERROR [flask_migrate] Error: Target database is not up to date.` for the the second schema – Abhishek Aravindan Jun 24 '21 at 07:02
  • 1
    Refer here for this: https://stackoverflow.com/questions/17768940/target-database-is-not-up-to-date/17776558 , but the reason that they always run in public is that one. You can try in your psql console how the `set search_path to test, public` will behave. Or you can change the order in your array and check it, it will only be public that will be migrated – kakou Jun 24 '21 at 07:07
  • Thank you @KarolosK. I fixed the issue using your suggestion. I removed public and then I got the error target database not up to date. I fixed that by `flask db stamp head` so all schemas will be up to date. Now migrating will be across all schemas. – Abhishek Aravindan Jun 24 '21 at 07:22

0 Answers0