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