I'm using NestJS 10 and TypeORM 0.3.17 (PostGres 14 db). I want to create a migration that will drop a table. I have defined this in src/config/data-source.ts
import * as dotenv from 'dotenv';
import * as dotenvExpand from 'dotenv-expand';
import { DataSource } from 'typeorm';
import {
initializeTransactionalContext,
addTransactionalDataSource,
} from 'typeorm-transactional';
const SnakeNamingStrategy =
require('typeorm-naming-strategies').SnakeNamingStrategy;
dotenvExpand.expand(dotenv.config());
const dataSource = new DataSource({
type: 'postgres',
host: process.env.DATABASE_HOST,
port: Number(process.env.DATABASE_PORT) || 5432,
database: process.env.DATABASE_NAME,
username: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
entities: ['dist/**/*.entity.js'],
migrations: ['dist/migrations/*.js'],
extra: {
charset: 'utf8mb4_unicode_ci',
},
namingStrategy: new SnakeNamingStrategy(),
});
initializeTransactionalContext();
addTransactionalDataSource(dataSource);
export default dataSource;
and defined this in my package.json ...
"typeorm": "npm run build && npx typeorm -d dist/config/data-source.js",
"migration:run": "npm run typeorm -- migration:run",
"migration:generate": "npm run typeorm -- migration:generate ./src/migrations/$npm_config_name",
"migration:create": "npm run typeorm -- migration:create ./src/migrations/$npm_config_name",
"migration:revert": "npm run typeorm -- -d ./src/config/typeorm.ts migration:revert"
However, when I run my migration:create command, I get this baffling error ...
$ npm run migration:create --name=dropCategoriesTable
> custom-greetings-api@0.0.1 migration:create
> npm run typeorm -- migration:create ./src/migrations/$npm_config_name
> custom-greetings-api@0.0.1 typeorm
> npm run build && npx typeorm -d dist/config/data-source.js migration:create ./src/migrations/dropCategoriesTable
> custom-greetings-api@0.0.1 build
> nest build
typeorm migration:create <path>
Creates a new migration file.
Options:
-h, --help Show help [boolean]
-o, --outputJs Generate a migration file on Javascript instead of Typescript
[boolean] [default: false]
-t, --timestamp Custom timestamp for the migration name
[number] [default: false]
-v, --version Show version number [boolean]
Unknown argument: d
How do I create my migration to drop a table?
TypeORM's documentation goes over this. In v0.3.0 you no longer need to pass the datasource object to the migration to create the migration file. You just pass the path to where the migration should be created and that's it. When you run the migration(s) is when you want to have the -d
option to tell TypeORM what datasource it is running against. For a simple table drop, something like
import { MigrationInterface, QueryRunner } from "typeorm"
export class DropTableMigration implements MigrationInterface {
async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query('DROP TABLE "table";')
}
async down(queryRunner: QueryRunner): Promise<void> {}
}
would probably do