0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-01-06 22:40:14 -05:00

💡 Enabled foreign key checks on sqlite3

issue https://github.com/TryGhost/Team/issues/476
This commit is contained in:
Thibaut Patel 2021-03-01 19:19:24 +01:00 committed by Thibaut Patel
parent c8af2d4a04
commit 874ccaef53
2 changed files with 24 additions and 1 deletions

View file

@ -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';

View file

@ -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