Search code examples
postgresqltypeorm

how to migrate schema specific in typeorm


I have a specific connection for postgres:

const dbconfig: DataSourceOptions = {
      ...baseConnection,
      schema: tenantSchema,
      migrations: ['./**/*.migration.js'],
    };

let data = new DataSource(dbconfig);
data = await data.initialize();
data.runMigrations() 

this actually runs all migration, , the migrations table which are migrations, and typeorm_metadata are generated into the tenantSchema, but all other tables are generated into the public schema.

I need to automate this via api calls, and I can't really string replace schema prefixes for structural reasons, setting search_path on every query requires some sort of shared variable which I'd like to avoid. What options do I have or am I making some mistake or missing something for migration configuration


Solution

  • In the Up function that typeorm provides, before the first sql statement, you could put a set local search_path to <your_schema>` dynamically. i.e:

    public async up(queryRunner: QueryRunner): Promise<void> {
        const query = `SET search_path TO ${this.SCHEMA};
                 <your query>`;
        await queryRunner.query(query);
      }