From d934ae1e6c0747698b4973d9cad217379076a6cf Mon Sep 17 00:00:00 2001 From: Fabio Di Stasio Date: Sat, 4 Feb 2023 13:51:02 +0100 Subject: [PATCH] fix(SQLite): triggers disappear after editing related table, fixes #523 --- src/main/libs/clients/SQLiteClient.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/main/libs/clients/SQLiteClient.ts b/src/main/libs/clients/SQLiteClient.ts index d6eb94da..b4562558 100644 --- a/src/main/libs/clients/SQLiteClient.ts +++ b/src/main/libs/clients/SQLiteClient.ts @@ -344,6 +344,20 @@ export class SQLiteClient extends AntaresCore { const tmpName = `Antares_${table}_tmp`; await this.raw(`CREATE TABLE "${tmpName}" AS SELECT * FROM "${table}"`); + + // Get table triggers before drop + const { rows: triggers } = await this.raw(`SELECT * FROM "${schema}".sqlite_master WHERE type='trigger' AND tbl_name = '${table}'`); + const remappedTriggers = triggers.map((row) => { + return { + schema, + sql: row.sql.match(/(BEGIN|begin)(.*)(END|end)/gs)[0], + name: row.name, + table: row.sql.match(/(?<=ON `).*?(?=`)/gs)[0], + activation: row.sql.match(/(BEFORE|AFTER)/gs)[0], + event: row.sql.match(/(INSERT|UPDATE|DELETE)/gs)[0] + }; + }); + await this.dropTable(params); const createTableParams = { @@ -376,6 +390,11 @@ export class SQLiteClient extends AntaresCore { await this.raw(`INSERT INTO "${createTableParams.options.name}" (${insertFields.join(',')}) SELECT ${selectFields.join(',')} FROM "${tmpName}"`); await this.dropTable({ schema: schema, table: tmpName }); + + // Recreates triggers + for (const trigger of remappedTriggers) + await this.createTrigger(trigger); + await this.raw('PRAGMA foreign_keys = 1'); await this.raw('COMMIT'); }