2024-01-22 09:25:36 -08:00
|
|
|
import { Command, Flags } from '@oclif/core';
|
2024-02-08 06:13:29 -08:00
|
|
|
import type { DataSourceOptions as ConnectionOptions } from '@n8n/typeorm';
|
|
|
|
import { DataSource as Connection } from '@n8n/typeorm';
|
2023-10-25 07:35:22 -07:00
|
|
|
import { Container } from 'typedi';
|
|
|
|
import { Logger } from '@/Logger';
|
2024-02-20 05:28:53 -08:00
|
|
|
import { setSchema } from '@/Db';
|
|
|
|
import { getConnectionOptions } from '@db/config';
|
2023-06-22 00:06:31 -07:00
|
|
|
import type { Migration } from '@db/types';
|
|
|
|
import { wrapMigration } from '@db/utils/migrationHelpers';
|
2023-01-11 09:29:31 -08:00
|
|
|
import config from '@/config';
|
2021-10-13 15:21:00 -07:00
|
|
|
|
|
|
|
export class DbRevertMigrationCommand extends Command {
|
|
|
|
static description = 'Revert last database migration';
|
|
|
|
|
|
|
|
static examples = ['$ n8n db:revert'];
|
|
|
|
|
|
|
|
static flags = {
|
2024-01-22 09:25:36 -08:00
|
|
|
help: Flags.help({ char: 'h' }),
|
2021-10-13 15:21:00 -07:00
|
|
|
};
|
|
|
|
|
2023-10-25 07:35:22 -07:00
|
|
|
protected logger = Container.get(Logger);
|
2023-02-10 05:59:20 -08:00
|
|
|
|
|
|
|
private connection: Connection;
|
2021-10-13 15:21:00 -07:00
|
|
|
|
2023-02-10 05:59:20 -08:00
|
|
|
async init() {
|
2024-01-22 09:25:36 -08:00
|
|
|
await this.parse(DbRevertMigrationCommand);
|
2023-02-10 05:59:20 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
async run() {
|
|
|
|
const dbType = config.getEnv('database.type');
|
|
|
|
const connectionOptions: ConnectionOptions = {
|
2024-02-20 05:28:53 -08:00
|
|
|
...getConnectionOptions(),
|
2023-02-10 05:59:20 -08:00
|
|
|
subscribers: [],
|
|
|
|
synchronize: false,
|
|
|
|
migrationsRun: false,
|
|
|
|
dropSchema: false,
|
|
|
|
logging: ['query', 'error', 'schema'],
|
|
|
|
};
|
|
|
|
|
2023-06-22 00:06:31 -07:00
|
|
|
(connectionOptions.migrations as Migration[]).forEach(wrapMigration);
|
|
|
|
|
2023-02-10 05:59:20 -08:00
|
|
|
this.connection = new Connection(connectionOptions);
|
|
|
|
await this.connection.initialize();
|
2024-01-24 04:38:57 -08:00
|
|
|
if (dbType === 'postgresdb') await setSchema(this.connection);
|
2023-02-10 05:59:20 -08:00
|
|
|
await this.connection.undoLastMigration();
|
|
|
|
await this.connection.destroy();
|
|
|
|
}
|
|
|
|
|
|
|
|
async catch(error: Error) {
|
|
|
|
this.logger.error('Error reverting last migration. See log messages for details.');
|
|
|
|
this.logger.error(error.message);
|
|
|
|
}
|
|
|
|
|
|
|
|
protected async finally(error: Error | undefined) {
|
|
|
|
if (this.connection?.isInitialized) await this.connection.destroy();
|
2021-10-13 15:21:00 -07:00
|
|
|
|
2023-02-10 05:59:20 -08:00
|
|
|
this.exit(error ? 1 : 0);
|
2021-10-13 15:21:00 -07:00
|
|
|
}
|
|
|
|
}
|