From 874ccaef5345ec786bef312fd92dd0f181580d2b Mon Sep 17 00:00:00 2001 From: Thibaut Patel Date: Mon, 1 Mar 2021 19:19:24 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=92=A1=20Enabled=20foreign=20key=20checks?= =?UTF-8?q?=20on=20sqlite3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit issue https://github.com/TryGhost/Team/issues/476 --- core/server/data/db/connection.js | 7 +++++++ test/utils/db-utils.js | 18 +++++++++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/core/server/data/db/connection.js b/core/server/data/db/connection.js index 58e3ef37a9..eb5a798632 100644 --- a/core/server/data/db/connection.js +++ b/core/server/data/db/connection.js @@ -13,6 +13,13 @@ function configure(dbConfig) { // Backwards compatibility with old knex behaviour dbConfig.useNullAsDefault = Object.prototype.hasOwnProperty.call(dbConfig, 'useNullAsDefault') ? dbConfig.useNullAsDefault : true; + // Enables foreign key checks and delete on cascade + dbConfig.pool = { + afterCreate(conn, cb) { + conn.run('PRAGMA foreign_keys = ON', cb); + } + }; + // Force bthreads to use child_process backend until a worker_thread-compatible version of sqlite3 is published // https://github.com/mapbox/node-sqlite3/issues/1386 process.env.BTHREADS_BACKEND = 'child_process'; diff --git a/test/utils/db-utils.js b/test/utils/db-utils.js index afa642cb24..b966a18c96 100644 --- a/test/utils/db-utils.js +++ b/test/utils/db-utils.js @@ -24,7 +24,14 @@ module.exports.initData = async () => { module.exports.truncate = async (tableName) => { if (config.get('database:client') === 'sqlite3') { + const [foreignKeysEnabled] = await db.knex.raw('PRAGMA foreign_keys;'); + if (foreignKeysEnabled.foreign_keys) { + await db.knex.raw('PRAGMA foreign_keys = OFF;'); + } await db.knex(tableName).truncate(); + if (foreignKeysEnabled.foreign_keys) { + await db.knex.raw('PRAGMA foreign_keys = ON;'); + } return; } @@ -53,7 +60,16 @@ module.exports.teardown = () => { if (config.get('database:client') === 'sqlite3') { return Promise .mapSeries(tables, function createTable(table) { - return db.knex.raw('DELETE FROM ' + table + ';'); + return (async function () { + const [foreignKeysEnabled] = await db.knex.raw('PRAGMA foreign_keys;'); + if (foreignKeysEnabled.foreign_keys) { + await db.knex.raw('PRAGMA foreign_keys = OFF;'); + } + await db.knex.raw('DELETE FROM ' + table + ';'); + if (foreignKeysEnabled.foreign_keys) { + await db.knex.raw('PRAGMA foreign_keys = ON;'); + } + })(); }) .catch(function (err) { // CASE: table does not exist