I need to run TypeORM migration that creates bunch of tables. MS-SQL Database is already created. Those tables are part of schema domain1
. Here's the ORM config and migration.
config
return {
type: 'mssql',
host: '..',
port: '..',
username: '..',
password: '..',
database: '..',
options: {
encrypt: true,
},
entities: [`${__dirname}/src/entities/*.entity{.ts,.js}`],
migrations: [`${__dirname}/migrations/**/*{.ts,.js}`],
migrationsRun: true,
synchronize: false,
logging: true,
schema: 'domain1',
cli: {
migrationsDir: 'apps/myapp/src/migration',
},
};
migration:
export class addBasicSchema1411753217156 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
console.log('inside up method');
await queryRunner.createSchema('domain1', true);
await queryRunner.query(
`IF NOT EXISTS (SELECT * FROM sys.tables t JOIN sys.schemas s ON (t.schema_id = s.schema_id) WHERE s.name = 'domain1' AND t.name = 'table1') CREATE TABLE "domain1".[table1] (..);`,
);
await queryRunner.query(
`IF NOT EXISTS (SELECT * FROM sys.tables t JOIN sys.schemas s ON (t.schema_id = s.schema_id) WHERE s.name = 'domain1' AND t.name = 'table2') CREATE TABLE "domain1".[table2] (..);`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP TABLE "domain1"."table1"`);
await queryRunner.query(`DROP TABLE "domain1"."table2"`);
await queryRunner.dropSchema('domain1', true);
}
}
The problem here is, it tries to create migration table with schema like domain1.migration
before the schema gets created. Flow never reaches to console.log('inside up method');
CREATE TABLE "mydb"."domain1"."migrations" ("id" int NOT NULL IDENTITY(1,1), "timestamp" bigint NOT NULL,
"name" varchar(255) NOT NULL, CONSTRAINT "PK_8b82d7f526340ab734260ea46b1" PRIMARY KEY ("id"))
and throws the error:
QueryFailedError: Error: The specified schema name "domain1" either does not exist or you do not have permission to use it.
You may not have permission to create a new schema (or Database).
I faced a similar issue, and I solved it by creating the Database manually.
The root cause of my case was that the user I configured in the typeorm
doesn't have permission to create the schema.