juztcode
juztcode

Reputation: 1345

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

Upvotes: 1

Views: 1933

Answers (3)

pdesuza
pdesuza

Reputation: 1

I spent a few hours debugging this and figured it out based on something @Enak said. None of the answers directly spoke to it so I figured I'd highlight just in case someone else makes the same mistake.

I've been using TypeORM for a while but I've been doing migrations manually. I typical define my entities to be created within schemas and would set name using the pattern schema.entity:

@Entity('audit.activity')

This generally works if doing migrations manually (not using the typeorm cli). However, if using the cli, it won't recognize that the table already exists and thus will produce the create statement every time.

Needless to say, I'm now declaring my entities using the correct form:

@Entity('activity', {
  schema: 'audit'
})

Upvotes: 0

mleko
mleko

Reputation: 124

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);
  }

Upvotes: 1

Enak
Enak

Reputation: 596

Maybe I'm missing something but if you create your migrations with the above config and not with baseConnection, your migration should already contain the correct schema. Maybe something is misconfigured, can't tell with all files.

As workaround: Write the schema directly to the entities annotation like e.g.

...
@Entity("myEntity", { schema: "my_schema" })
...

Upvotes: 3

Related Questions