Skip to content

Commit d2b8207

Browse files
committed
fix(core): Improve the performance of last 2 sqlite migrations (#6522)
1 parent f6a9497 commit d2b8207

3 files changed

Lines changed: 91 additions & 11 deletions

File tree

packages/cli/src/databases/migrations/sqlite/1690000000002-MigrateIntegerKeysToString.ts

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,19 @@
1+
import { statSync } from 'fs';
2+
import path from 'path';
3+
import { UserSettings } from 'n8n-core';
14
import type { MigrationContext, IrreversibleMigration } from '@db/types';
5+
import config from '@/config';
6+
import { copyTable } from '@/databases/utils/migrationHelpers';
27

38
export class MigrateIntegerKeysToString1690000000002 implements IrreversibleMigration {
49
transaction = false as const;
510

6-
async up({ queryRunner, tablePrefix }: MigrationContext) {
11+
async up(context: MigrationContext) {
12+
// eslint-disable-next-line @typescript-eslint/no-use-before-define
13+
await pruneExecutionsData(context);
14+
15+
const { queryRunner, tablePrefix } = context;
16+
717
await queryRunner.query(`
818
CREATE TABLE "${tablePrefix}TMP_workflow_entity" ("id" varchar(36) PRIMARY KEY NOT NULL, "name" varchar(128) NOT NULL, "active" boolean NOT NULL, "nodes" text, "connections" text NOT NULL, "createdAt" datetime(3) NOT NULL DEFAULT (STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')), "updatedAt" datetime(3) NOT NULL DEFAULT (STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')), "settings" text, "staticData" text, "pinData" text, "versionId" varchar(36), "triggerCount" integer NOT NULL DEFAULT 0);`);
919
await queryRunner.query(
@@ -108,9 +118,7 @@ export class MigrateIntegerKeysToString1690000000002 implements IrreversibleMigr
108118
"data" text NOT NULL, "status" varchar,
109119
FOREIGN KEY("workflowId") REFERENCES "${tablePrefix}workflow_entity" ("id") ON DELETE CASCADE
110120
);`);
111-
await queryRunner.query(
112-
`INSERT INTO "${tablePrefix}TMP_execution_entity" SELECT * FROM "${tablePrefix}execution_entity";`,
113-
);
121+
await copyTable({ tablePrefix, queryRunner }, 'execution_entity', 'TMP_execution_entity');
114122
await queryRunner.query(`DROP TABLE "${tablePrefix}execution_entity";`);
115123
await queryRunner.query(
116124
`ALTER TABLE "${tablePrefix}TMP_execution_entity" RENAME TO "${tablePrefix}execution_entity";`,
@@ -178,3 +186,44 @@ export class MigrateIntegerKeysToString1690000000002 implements IrreversibleMigr
178186
);
179187
}
180188
}
189+
190+
const DESIRED_DATABASE_FILE_SIZE = 1 * 1024 * 1024 * 1024; // 1 GB
191+
const migrationsPruningEnabled = process.env.MIGRATIONS_PRUNING_ENABLED === 'true';
192+
193+
function getSqliteDbFileSize(): number {
194+
const filename = path.resolve(
195+
UserSettings.getUserN8nFolderPath(),
196+
config.getEnv('database.sqlite.database'),
197+
);
198+
const { size } = statSync(filename);
199+
return size;
200+
}
201+
202+
const pruneExecutionsData = async ({ queryRunner, tablePrefix }: MigrationContext) => {
203+
if (migrationsPruningEnabled) {
204+
const dbFileSize = getSqliteDbFileSize();
205+
if (dbFileSize < DESIRED_DATABASE_FILE_SIZE) {
206+
console.log(`DB Size not large enough to prune: ${dbFileSize}`);
207+
return;
208+
}
209+
210+
console.time('pruningData');
211+
const counting = (await queryRunner.query(
212+
`select count(id) as rows from "${tablePrefix}execution_entity";`,
213+
)) as Array<{ rows: number }>;
214+
215+
const averageExecutionSize = dbFileSize / counting[0].rows;
216+
const numberOfExecutionsToKeep = Math.floor(DESIRED_DATABASE_FILE_SIZE / averageExecutionSize);
217+
218+
const query = `SELECT id FROM "${tablePrefix}execution_entity" ORDER BY id DESC limit ${numberOfExecutionsToKeep}, 1`;
219+
const idToKeep = await queryRunner
220+
.query(query)
221+
.then((rows: Array<{ id: number }>) => rows[0].id);
222+
223+
const removalQuery = `DELETE FROM "${tablePrefix}execution_entity" WHERE id < ${idToKeep} and status IN ('success')`;
224+
await queryRunner.query(removalQuery);
225+
console.timeEnd('pruningData');
226+
} else {
227+
console.log('Pruning was requested, but was not enabled');
228+
}
229+
};

packages/cli/src/databases/migrations/sqlite/1690000000010-SeparateExecutionData.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { MigrationContext, ReversibleMigration } from '@/databases/types';
2+
import { copyTable } from '@/databases/utils/migrationHelpers';
23

34
export class SeparateExecutionData1690000000010 implements ReversibleMigration {
45
async up({ queryRunner, tablePrefix }: MigrationContext): Promise<void> {
@@ -11,13 +12,12 @@ export class SeparateExecutionData1690000000010 implements ReversibleMigration {
1112
)`,
1213
);
1314

14-
await queryRunner.query(
15-
`INSERT INTO "${tablePrefix}execution_data" (
16-
"executionId",
17-
"workflowData",
18-
"data")
19-
SELECT "id", "workflowData", "data" FROM "${tablePrefix}execution_entity"
20-
`,
15+
await copyTable(
16+
{ tablePrefix, queryRunner },
17+
'execution_entity',
18+
'execution_data',
19+
['id', 'workflowData', 'data'],
20+
['executionId', 'workflowData', 'data'],
2121
);
2222

2323
await queryRunner.query(

packages/cli/src/databases/utils/migrationHelpers.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,37 @@ export const wrapMigration = (migration: Migration) => {
115115
});
116116
};
117117

118+
export const copyTable = async (
119+
{ tablePrefix, queryRunner }: Pick<MigrationContext, 'queryRunner' | 'tablePrefix'>,
120+
fromTable: string,
121+
toTable: string,
122+
fromFields: string[] = [],
123+
toFields: string[] = [],
124+
batchSize = 10,
125+
) => {
126+
const driver = queryRunner.connection.driver;
127+
fromTable = driver.escape(`${tablePrefix}${fromTable}`);
128+
toTable = driver.escape(`${tablePrefix}${toTable}`);
129+
const fromFieldsStr = fromFields.length
130+
? fromFields.map((f) => driver.escape(f)).join(', ')
131+
: '*';
132+
const toFieldsStr = toFields.length
133+
? `(${toFields.map((f) => driver.escape(f)).join(', ')})`
134+
: '';
135+
136+
const total = await queryRunner
137+
.query(`SELECT COUNT(*) as count from ${fromTable}`)
138+
.then((rows: Array<{ count: number }>) => rows[0].count);
139+
140+
let migrated = 0;
141+
while (migrated < total) {
142+
await queryRunner.query(
143+
`INSERT INTO ${toTable} ${toFieldsStr} SELECT ${fromFieldsStr} FROM ${fromTable} LIMIT ${migrated}, ${batchSize}`,
144+
);
145+
migrated += batchSize;
146+
}
147+
};
148+
118149
function batchQuery(query: string, limit: number, offset = 0): string {
119150
return `
120151
${query}

0 commit comments

Comments
 (0)