-
Notifications
You must be signed in to change notification settings - Fork 5.2k
/
migrationHelpers.ts
209 lines (192 loc) · 6.3 KB
/
migrationHelpers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import { Container } from 'typedi';
import { readFileSync, rmSync } from 'fs';
import { InstanceSettings } from 'n8n-core';
import type { ObjectLiteral } from '@n8n/typeorm';
import type { QueryRunner } from '@n8n/typeorm/query-runner/QueryRunner';
import { ApplicationError, jsonParse } from 'n8n-workflow';
import config from '@/config';
import { inTest } from '@/constants';
import type { BaseMigration, Migration, MigrationContext, MigrationFn } from '@db/types';
import { createSchemaBuilder } from '@db/dsl';
import { NodeTypes } from '@/NodeTypes';
import { Logger } from '@/Logger';
const PERSONALIZATION_SURVEY_FILENAME = 'personalizationSurvey.json';
function loadSurveyFromDisk(): string | null {
try {
const filename = `${
Container.get(InstanceSettings).n8nFolder
}/${PERSONALIZATION_SURVEY_FILENAME}`;
const surveyFile = readFileSync(filename, 'utf-8');
rmSync(filename);
const personalizationSurvey = JSON.parse(surveyFile) as object;
const kvPairs = Object.entries(personalizationSurvey);
if (!kvPairs.length) {
throw new ApplicationError('personalizationSurvey is empty');
} else {
const emptyKeys = kvPairs.reduce((acc, [, value]) => {
if (!value || (Array.isArray(value) && !value.length)) {
return acc + 1;
}
return acc;
}, 0);
if (emptyKeys === kvPairs.length) {
throw new ApplicationError('incomplete personalizationSurvey');
}
}
return surveyFile;
} catch (error) {
return null;
}
}
let runningMigrations = false;
function logMigrationStart(migrationName: string): void {
if (inTest) return;
const logger = Container.get(Logger);
if (!runningMigrations) {
logger.warn('Migrations in progress, please do NOT stop the process.');
runningMigrations = true;
}
logger.info(`Starting migration ${migrationName}`);
}
function logMigrationEnd(migrationName: string): void {
if (inTest) return;
const logger = Container.get(Logger);
logger.info(`Finished migration ${migrationName}`);
}
const runDisablingForeignKeys = async (
migration: BaseMigration,
context: MigrationContext,
fn: MigrationFn,
) => {
const { dbType, queryRunner } = context;
if (dbType !== 'sqlite')
throw new ApplicationError('Disabling transactions only available in sqlite');
await queryRunner.query('PRAGMA foreign_keys=OFF');
await queryRunner.startTransaction();
try {
await fn.call(migration, context);
await queryRunner.commitTransaction();
} catch (e) {
try {
await queryRunner.rollbackTransaction();
} catch {}
throw e;
} finally {
await queryRunner.query('PRAGMA foreign_keys=ON');
}
};
function parseJson<T>(data: string | T): T {
return typeof data === 'string' ? jsonParse<T>(data) : data;
}
const dbType = config.getEnv('database.type');
const isMysql = ['mariadb', 'mysqldb'].includes(dbType);
const dbName = config.getEnv(`database.${dbType === 'mariadb' ? 'mysqldb' : dbType}.database`);
const tablePrefix = config.getEnv('database.tablePrefix');
const createContext = (queryRunner: QueryRunner, migration: Migration): MigrationContext => ({
logger: Container.get(Logger),
tablePrefix,
dbType,
isMysql,
dbName,
migrationName: migration.name,
queryRunner,
schemaBuilder: createSchemaBuilder(tablePrefix, queryRunner),
nodeTypes: Container.get(NodeTypes),
loadSurveyFromDisk,
parseJson,
escape: {
columnName: (name) => queryRunner.connection.driver.escape(name),
tableName: (name) => queryRunner.connection.driver.escape(`${tablePrefix}${name}`),
indexName: (name) => queryRunner.connection.driver.escape(`IDX_${tablePrefix}${name}`),
},
runQuery: async <T>(sql: string, namedParameters?: ObjectLiteral) => {
if (namedParameters) {
const [query, parameters] = queryRunner.connection.driver.escapeQueryWithParameters(
sql,
namedParameters,
{},
);
return await (queryRunner.query(query, parameters) as Promise<T>);
} else {
return await (queryRunner.query(sql) as Promise<T>);
}
},
runInBatches: async <T>(
query: string,
operation: (results: T[]) => Promise<void>,
limit = 100,
) => {
let offset = 0;
let batchedQuery: string;
let batchedQueryResults: T[];
if (query.trim().endsWith(';')) query = query.trim().slice(0, -1);
do {
batchedQuery = `${query} LIMIT ${limit} OFFSET ${offset}`;
batchedQueryResults = (await queryRunner.query(batchedQuery)) as T[];
// pass a copy to prevent errors from mutation
await operation([...batchedQueryResults]);
offset += limit;
} while (batchedQueryResults.length === limit);
},
copyTable: async (
fromTable: string,
toTable: string,
fromFields?: string[],
toFields?: string[],
batchSize?: number,
) => {
const { driver } = queryRunner.connection;
fromTable = driver.escape(`${tablePrefix}${fromTable}`);
toTable = driver.escape(`${tablePrefix}${toTable}`);
const fromFieldsStr = fromFields?.length
? fromFields.map((f) => driver.escape(f)).join(', ')
: '*';
const toFieldsStr = toFields?.length
? `(${toFields.map((f) => driver.escape(f)).join(', ')})`
: '';
const total = await queryRunner
.query(`SELECT COUNT(*) AS count FROM ${fromTable}`)
.then((rows: Array<{ count: number }>) => rows[0].count);
batchSize = batchSize ?? 10;
let migrated = 0;
while (migrated < total) {
await queryRunner.query(
`INSERT INTO ${toTable} ${toFieldsStr} SELECT ${fromFieldsStr} FROM ${fromTable} LIMIT ${migrated}, ${batchSize}`,
);
migrated += batchSize;
}
},
});
export const wrapMigration = (migration: Migration) => {
const { up, down } = migration.prototype;
if (up) {
Object.assign(migration.prototype, {
async up(this: BaseMigration, queryRunner: QueryRunner) {
logMigrationStart(migration.name);
const context = createContext(queryRunner, migration);
if (this.transaction === false) {
await runDisablingForeignKeys(this, context, up);
} else {
await up.call(this, context);
}
logMigrationEnd(migration.name);
},
});
} else {
throw new ApplicationError(
'At least on migration is missing the method `up`. Make sure all migrations are valid.',
);
}
if (down) {
Object.assign(migration.prototype, {
async down(this: BaseMigration, queryRunner: QueryRunner) {
const context = createContext(queryRunner, migration);
if (this.transaction === false) {
await runDisablingForeignKeys(this, context, down);
} else {
await down.call(this, context);
}
},
});
}
};