2020-04-29 18:44:27 +03:00
|
|
|
const _ = require('lodash');
|
|
|
|
const Promise = require('bluebird');
|
2020-05-28 21:30:23 +03:00
|
|
|
const {i18n} = require('../../lib/common');
|
|
|
|
const logging = require('../../../shared/logging');
|
2020-04-29 18:44:27 +03:00
|
|
|
const db = require('../db');
|
|
|
|
const schema = require('./schema');
|
|
|
|
const clients = require('./clients');
|
2014-07-10 19:10:00 +04:00
|
|
|
|
2019-08-02 05:59:49 +03:00
|
|
|
function addTableColumn(tableName, table, columnName, columnSpec = schema[tableName][columnName]) {
|
2020-04-29 18:44:27 +03:00
|
|
|
let column;
|
2014-07-18 21:58:29 +04:00
|
|
|
|
2014-06-12 19:25:55 +04:00
|
|
|
// creation distinguishes between text with fieldtype, string with maxlength and all others
|
2019-07-05 14:40:43 +03:00
|
|
|
if (columnSpec.type === 'text' && Object.prototype.hasOwnProperty.call(columnSpec, 'fieldtype')) {
|
2016-07-14 13:59:42 +03:00
|
|
|
column = table[columnSpec.type](columnName, columnSpec.fieldtype);
|
✨ replace auto increment id's by object id (#7495)
* 🛠 bookshelf tarball, bson-objectid
* 🎨 schema changes
- change increment type to string
- add a default fallback for string length 191 (to avoid adding this logic to every single column which uses an ID)
- remove uuid, because ID now represents a global resource identifier
- keep uuid for post, because we are using this as preview id
- keep uuid for clients for now - we are using this param for Ghost-Auth
* ✨ base model: generate ObjectId on creating event
- each new resource get's a auto generate ObjectId
- this logic won't work for attached models, this commit comes later
* 🎨 centralised attach method
When attaching models there are two things important two know
1. To be able to attach an ObjectId, we need to register the `onCreating` event the fetched model!This is caused by the Bookshelf design in general. On this target model we are attaching the new model.
2. We need to manually fetch the target model, because Bookshelf has a weird behaviour (which is known as a bug, see see https://github.com/tgriesser/bookshelf/issues/629). The most important property when attaching a model is `parentFk`, which is the foreign key. This can be null when fetching the model with the option `withRelated`. To ensure quality and consistency, the custom attach wrapper always fetches the target model manual. By fetching the target model (again) is a little performance decrease, but it also has advantages: we can register the event, and directly unregister the event again. So very clean code.
Important: please only use the custom attach wrapper in the future.
* 🎨 token model had overriden the onCreating function because of the created_at field
- we need to ensure that the base onCreating hook get's triggered for ALL models
- if not, they don't get an ObjectId assigned
- in this case: be smart and check if the target model has a created_at field
* 🎨 we don't have a uuid field anymore, remove the usages
- no default uuid creation in models
- i am pretty sure we have some more definitions in our tests (for example in the export json files), but that is too much work to delete them all
* 🎨 do not parse ID to Number
- we had various occurances of parsing all ID's to numbers
- we don't need this behaviour anymore
- ID is string
- i will adapt the ID validation in the next commit
* 🎨 change ID regex for validation
- we only allow: ID as ObjectId, ID as 1 and ID as me
- we need to keep ID 1, because our whole software relies on ID 1 (permissions etc)
* 🎨 owner fixture
- roles: [4] does not work anymore
- 4 means -> static id 4
- this worked in an auto increment system (not even in a system with distributed writes)
- with ObjectId we generate each ID automatically (for static and dynamic resources)
- it is possible to define all id's for static resources still, but that means we need to know which ID is already used and for consistency we have to define ObjectId's for these static resources
- so no static id's anymore, except of: id 1 for owner and id 0 for external usage (because this is required from our permission system)
- NOTE: please read through the comment in the user model
* 🎨 tests: DataGenerator and test utils
First of all: we need to ensure using ObjectId's in the tests. When don't, we can't ensure that ObjectId's work properly.
This commit brings lot's of dynamic into all the static defined id's.
In one of the next commits, i will adapt all the tests.
* 🚨 remove counter in Notification API
- no need to add a counter
- we simply generate ObjectId's (they are auto incremental as well)
- our id validator does only allow ObjectId as id,1 and me
* 🎨 extend contextUser in Base Model
- remove isNumber check, because id's are no longer numbers, except of id 0/1
- use existing isExternalUser
- support id 0/1 as string or number
* ✨ Ghost Owner has id 1
- ensure we define this id in the fixtures.json
- doesn't matter if number or string
* 🎨 functional tests adaptions
- use dynamic id's
* 🎨 fix unit tests
* 🎨 integration tests adaptions
* 🎨 change importer utils
- all our export examples (test/fixtures/exports) contain id's as numbers
- fact: but we ignore them anyway when inserting into the database, see https://github.com/TryGhost/Ghost/blob/master/core/server/data/import/utils.js#L249
- in https://github.com/TryGhost/Ghost/pull/7495/commits/0e6ed957cd54dc02a25cf6fb1ab7d7e723295e2c#diff-70f514a06347c048648be464819503c4L67 i removed parsing id's to integers
- i realised that this ^ check just existed, because the userIdToMap was an object key and object keys are always strings!
- i think this logic is a little bit complicated, but i don't want to refactor this now
- this commit ensures when trying to find the user, the id comparison works again
- i've added more documentation to understand this logic ;)
- plus i renamed an attribute to improve readability
* 🎨 Data-Generator: add more defaults to createUser
- if i use the function DataGenerator.forKnex.createUser i would like to get a full set of defaults
* 🎨 test utils: change/extend function set for functional tests
- functional tests work a bit different
- they boot Ghost and seed the database
- some functional tests have mis-used the test setup
- the test setup needs two sections: integration/unit and functional tests
- any functional test is allowed to either add more data or change data in the existing Ghost db
- but what it should not do is: add test fixtures like roles or users from our DataGenerator and cross fingers it will work
- this commit adds a clean method for functional tests to add extra users
* 🎨 functional tests adaptions
- use last commit to insert users for functional tests clean
- tidy up usage of testUtils.setup or testUtils.doAuth
* 🐛 test utils: reset database before init
- ensure we don't have any left data from other tests in the database when starting ghost
* 🐛 fix test (unrelated to this PR)
- fixes a random failure
- return statement was missing
* 🎨 make changes for invites
2016-11-17 12:09:11 +03:00
|
|
|
} else if (columnSpec.type === 'string') {
|
2019-07-05 14:40:43 +03:00
|
|
|
if (Object.prototype.hasOwnProperty.call(columnSpec, 'maxlength')) {
|
✨ replace auto increment id's by object id (#7495)
* 🛠 bookshelf tarball, bson-objectid
* 🎨 schema changes
- change increment type to string
- add a default fallback for string length 191 (to avoid adding this logic to every single column which uses an ID)
- remove uuid, because ID now represents a global resource identifier
- keep uuid for post, because we are using this as preview id
- keep uuid for clients for now - we are using this param for Ghost-Auth
* ✨ base model: generate ObjectId on creating event
- each new resource get's a auto generate ObjectId
- this logic won't work for attached models, this commit comes later
* 🎨 centralised attach method
When attaching models there are two things important two know
1. To be able to attach an ObjectId, we need to register the `onCreating` event the fetched model!This is caused by the Bookshelf design in general. On this target model we are attaching the new model.
2. We need to manually fetch the target model, because Bookshelf has a weird behaviour (which is known as a bug, see see https://github.com/tgriesser/bookshelf/issues/629). The most important property when attaching a model is `parentFk`, which is the foreign key. This can be null when fetching the model with the option `withRelated`. To ensure quality and consistency, the custom attach wrapper always fetches the target model manual. By fetching the target model (again) is a little performance decrease, but it also has advantages: we can register the event, and directly unregister the event again. So very clean code.
Important: please only use the custom attach wrapper in the future.
* 🎨 token model had overriden the onCreating function because of the created_at field
- we need to ensure that the base onCreating hook get's triggered for ALL models
- if not, they don't get an ObjectId assigned
- in this case: be smart and check if the target model has a created_at field
* 🎨 we don't have a uuid field anymore, remove the usages
- no default uuid creation in models
- i am pretty sure we have some more definitions in our tests (for example in the export json files), but that is too much work to delete them all
* 🎨 do not parse ID to Number
- we had various occurances of parsing all ID's to numbers
- we don't need this behaviour anymore
- ID is string
- i will adapt the ID validation in the next commit
* 🎨 change ID regex for validation
- we only allow: ID as ObjectId, ID as 1 and ID as me
- we need to keep ID 1, because our whole software relies on ID 1 (permissions etc)
* 🎨 owner fixture
- roles: [4] does not work anymore
- 4 means -> static id 4
- this worked in an auto increment system (not even in a system with distributed writes)
- with ObjectId we generate each ID automatically (for static and dynamic resources)
- it is possible to define all id's for static resources still, but that means we need to know which ID is already used and for consistency we have to define ObjectId's for these static resources
- so no static id's anymore, except of: id 1 for owner and id 0 for external usage (because this is required from our permission system)
- NOTE: please read through the comment in the user model
* 🎨 tests: DataGenerator and test utils
First of all: we need to ensure using ObjectId's in the tests. When don't, we can't ensure that ObjectId's work properly.
This commit brings lot's of dynamic into all the static defined id's.
In one of the next commits, i will adapt all the tests.
* 🚨 remove counter in Notification API
- no need to add a counter
- we simply generate ObjectId's (they are auto incremental as well)
- our id validator does only allow ObjectId as id,1 and me
* 🎨 extend contextUser in Base Model
- remove isNumber check, because id's are no longer numbers, except of id 0/1
- use existing isExternalUser
- support id 0/1 as string or number
* ✨ Ghost Owner has id 1
- ensure we define this id in the fixtures.json
- doesn't matter if number or string
* 🎨 functional tests adaptions
- use dynamic id's
* 🎨 fix unit tests
* 🎨 integration tests adaptions
* 🎨 change importer utils
- all our export examples (test/fixtures/exports) contain id's as numbers
- fact: but we ignore them anyway when inserting into the database, see https://github.com/TryGhost/Ghost/blob/master/core/server/data/import/utils.js#L249
- in https://github.com/TryGhost/Ghost/pull/7495/commits/0e6ed957cd54dc02a25cf6fb1ab7d7e723295e2c#diff-70f514a06347c048648be464819503c4L67 i removed parsing id's to integers
- i realised that this ^ check just existed, because the userIdToMap was an object key and object keys are always strings!
- i think this logic is a little bit complicated, but i don't want to refactor this now
- this commit ensures when trying to find the user, the id comparison works again
- i've added more documentation to understand this logic ;)
- plus i renamed an attribute to improve readability
* 🎨 Data-Generator: add more defaults to createUser
- if i use the function DataGenerator.forKnex.createUser i would like to get a full set of defaults
* 🎨 test utils: change/extend function set for functional tests
- functional tests work a bit different
- they boot Ghost and seed the database
- some functional tests have mis-used the test setup
- the test setup needs two sections: integration/unit and functional tests
- any functional test is allowed to either add more data or change data in the existing Ghost db
- but what it should not do is: add test fixtures like roles or users from our DataGenerator and cross fingers it will work
- this commit adds a clean method for functional tests to add extra users
* 🎨 functional tests adaptions
- use last commit to insert users for functional tests clean
- tidy up usage of testUtils.setup or testUtils.doAuth
* 🐛 test utils: reset database before init
- ensure we don't have any left data from other tests in the database when starting ghost
* 🐛 fix test (unrelated to this PR)
- fixes a random failure
- return statement was missing
* 🎨 make changes for invites
2016-11-17 12:09:11 +03:00
|
|
|
column = table[columnSpec.type](columnName, columnSpec.maxlength);
|
|
|
|
} else {
|
|
|
|
column = table[columnSpec.type](columnName, 191);
|
|
|
|
}
|
2014-06-12 19:25:55 +04:00
|
|
|
} else {
|
2016-07-14 13:59:42 +03:00
|
|
|
column = table[columnSpec.type](columnName);
|
2014-06-12 19:25:55 +04:00
|
|
|
}
|
2014-06-10 00:37:44 +04:00
|
|
|
|
2019-07-05 14:40:43 +03:00
|
|
|
if (Object.prototype.hasOwnProperty.call(columnSpec, 'nullable') && columnSpec.nullable === true) {
|
2014-06-12 19:25:55 +04:00
|
|
|
column.nullable();
|
|
|
|
} else {
|
2016-10-07 12:17:39 +03:00
|
|
|
column.nullable(false);
|
2014-06-12 19:25:55 +04:00
|
|
|
}
|
2019-07-05 14:40:43 +03:00
|
|
|
if (Object.prototype.hasOwnProperty.call(columnSpec, 'primary') && columnSpec.primary === true) {
|
2014-06-12 19:25:55 +04:00
|
|
|
column.primary();
|
|
|
|
}
|
2019-07-05 14:40:43 +03:00
|
|
|
if (Object.prototype.hasOwnProperty.call(columnSpec, 'unique') && columnSpec.unique) {
|
2014-06-12 19:25:55 +04:00
|
|
|
column.unique();
|
|
|
|
}
|
2019-07-05 14:40:43 +03:00
|
|
|
if (Object.prototype.hasOwnProperty.call(columnSpec, 'unsigned') && columnSpec.unsigned) {
|
2014-06-12 19:25:55 +04:00
|
|
|
column.unsigned();
|
|
|
|
}
|
2019-07-05 14:40:43 +03:00
|
|
|
if (Object.prototype.hasOwnProperty.call(columnSpec, 'references')) {
|
2014-09-10 08:06:24 +04:00
|
|
|
// check if table exists?
|
2014-07-18 21:58:29 +04:00
|
|
|
column.references(columnSpec.references);
|
2014-06-12 19:25:55 +04:00
|
|
|
}
|
2020-08-05 14:20:30 +03:00
|
|
|
if (Object.prototype.hasOwnProperty.call(columnSpec, 'cascadeDelete') && columnSpec.cascadeDelete === true) {
|
|
|
|
column.onDelete('CASCADE');
|
|
|
|
}
|
2019-07-05 14:40:43 +03:00
|
|
|
if (Object.prototype.hasOwnProperty.call(columnSpec, 'defaultTo')) {
|
2014-07-18 21:58:29 +04:00
|
|
|
column.defaultTo(columnSpec.defaultTo);
|
2014-06-12 19:25:55 +04:00
|
|
|
}
|
2019-07-05 14:40:43 +03:00
|
|
|
if (Object.prototype.hasOwnProperty.call(columnSpec, 'index') && columnSpec.index === true) {
|
2018-10-02 19:48:23 +03:00
|
|
|
column.index();
|
|
|
|
}
|
2014-06-10 00:37:44 +04:00
|
|
|
}
|
|
|
|
|
2019-08-02 05:59:49 +03:00
|
|
|
function addColumn(tableName, column, transaction, columnSpec) {
|
2016-07-14 13:59:42 +03:00
|
|
|
return (transaction || db.knex).schema.table(tableName, function (table) {
|
2019-08-02 05:59:49 +03:00
|
|
|
addTableColumn(tableName, table, column, columnSpec);
|
2014-06-12 19:25:55 +04:00
|
|
|
});
|
2014-06-10 00:37:44 +04:00
|
|
|
}
|
|
|
|
|
2020-06-24 13:58:15 +03:00
|
|
|
function dropColumn(tableName, column, transaction) {
|
|
|
|
return (transaction || db.knex).schema.table(tableName, function (table) {
|
2016-02-07 19:23:24 +03:00
|
|
|
table.dropColumn(column);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-02-02 06:43:31 +03:00
|
|
|
/**
|
|
|
|
* Adds an unique index to a table over the given columns.
|
|
|
|
*
|
|
|
|
* @param {string} tableName - name of the table to add unique constraint to
|
|
|
|
* @param {string|[string]} columns - column(s) to form unique constraint with
|
2021-03-09 19:12:10 +03:00
|
|
|
* @param {import('knex')} transaction - connection object containing knex reference
|
2021-02-02 06:43:31 +03:00
|
|
|
*/
|
2021-02-18 10:17:53 +03:00
|
|
|
async function addUnique(tableName, columns, transaction) {
|
2021-03-09 19:12:10 +03:00
|
|
|
try {
|
2021-02-18 10:17:53 +03:00
|
|
|
logging.info(`Adding unique constraint for: ${columns} in table ${tableName}`);
|
2021-03-09 19:12:10 +03:00
|
|
|
|
|
|
|
return await (transaction || db.knex).schema.table(tableName, function (table) {
|
2021-02-18 10:17:53 +03:00
|
|
|
table.unique(columns);
|
|
|
|
});
|
2021-03-09 19:12:10 +03:00
|
|
|
} catch (err) {
|
|
|
|
if (err.code === 'SQLITE_ERROR') {
|
|
|
|
logging.warn(`Constraint for: ${columns} already exists for table: ${tableName}`);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (err.code === 'ER_DUP_KEYNAME') {
|
|
|
|
logging.warn(`Constraint for: ${columns} already exists for table: ${tableName}`);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
throw err;
|
2021-02-18 10:17:53 +03:00
|
|
|
}
|
2014-06-10 00:37:44 +04:00
|
|
|
}
|
|
|
|
|
2021-02-02 06:43:31 +03:00
|
|
|
/**
|
|
|
|
* Drops a unique key constraint from a table.
|
|
|
|
*
|
|
|
|
* @param {string} tableName - name of the table to drop unique constraint from
|
|
|
|
* @param {string|[string]} columns - column(s) unique constraint was formed
|
2021-03-09 19:12:10 +03:00
|
|
|
* @param {import('knex')} transaction - connection object containing knex reference
|
2021-02-02 06:43:31 +03:00
|
|
|
*/
|
2021-02-18 10:17:53 +03:00
|
|
|
async function dropUnique(tableName, columns, transaction) {
|
2021-03-09 19:12:10 +03:00
|
|
|
try {
|
2021-02-18 10:17:53 +03:00
|
|
|
logging.info(`Dropping unique constraint for: ${columns} in table: ${tableName}`);
|
2021-03-09 19:12:10 +03:00
|
|
|
|
|
|
|
return await (transaction || db.knex).schema.table(tableName, function (table) {
|
2021-02-18 10:17:53 +03:00
|
|
|
table.dropUnique(columns);
|
|
|
|
});
|
2021-03-09 19:12:10 +03:00
|
|
|
} catch (err) {
|
|
|
|
if (err.code === 'SQLITE_ERROR') {
|
|
|
|
logging.warn(`Constraint for: ${columns} does not exist for table: ${tableName}`);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (err.code === 'ER_CANT_DROP_FIELD_OR_KEY') {
|
|
|
|
logging.warn(`Constraint for: ${columns} does not exist for table: ${tableName}`);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
throw err;
|
2021-02-18 10:17:53 +03:00
|
|
|
}
|
2014-06-10 00:37:44 +04:00
|
|
|
}
|
|
|
|
|
2021-02-25 00:07:16 +03:00
|
|
|
/**
|
|
|
|
* Checks if a foreign key exists in a table over the given columns.
|
|
|
|
*
|
|
|
|
* @param {Object} configuration - contains all configuration for this function
|
|
|
|
* @param {string} configuration.fromTableName - name of the table to add the foreign key to
|
|
|
|
* @param {string} configuration.fromColumn - column of the table to add the foreign key to
|
|
|
|
* @param {string} configuration.toTableName - name of the table to point the foreign key to
|
|
|
|
* @param {string} configuration.toColumn - column of the table to point the foreign key to
|
2021-03-09 19:12:10 +03:00
|
|
|
* @param {import('knex')} configuration.transaction - connection object containing knex reference
|
2021-02-25 00:07:16 +03:00
|
|
|
*/
|
2021-03-09 19:12:10 +03:00
|
|
|
async function hasForeignSQLite({fromTable, fromColumn, toTable, toColumn, transaction}) {
|
2021-02-25 00:07:16 +03:00
|
|
|
const knex = (transaction || db.knex);
|
|
|
|
const client = knex.client.config.client;
|
|
|
|
|
2021-03-09 19:12:10 +03:00
|
|
|
if (client !== 'sqlite3') {
|
|
|
|
throw new Error('Must use hasForeignSQLite3 on an SQLite3 database');
|
|
|
|
}
|
2021-02-25 00:07:16 +03:00
|
|
|
|
2021-03-09 19:12:10 +03:00
|
|
|
const foreignKeys = await knex.raw(`PRAGMA foreign_key_list('${fromTable}');`);
|
2021-02-25 00:07:16 +03:00
|
|
|
|
2021-03-09 19:12:10 +03:00
|
|
|
const hasForeignKey = foreignKeys.some(foreignKey => foreignKey.table === toTable && foreignKey.from === fromColumn && foreignKey.to === toColumn);
|
2021-02-25 00:07:16 +03:00
|
|
|
|
2021-03-09 19:12:10 +03:00
|
|
|
return hasForeignKey;
|
2021-02-25 00:07:16 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Adds a foreign key to a table.
|
|
|
|
*
|
|
|
|
* @param {Object} configuration - contains all configuration for this function
|
|
|
|
* @param {string} configuration.fromTableName - name of the table to add the foreign key to
|
|
|
|
* @param {string} configuration.fromColumn - column of the table to add the foreign key to
|
|
|
|
* @param {string} configuration.toTableName - name of the table to point the foreign key to
|
|
|
|
* @param {string} configuration.toColumn - column of the table to point the foreign key to
|
2021-03-02 17:06:24 +03:00
|
|
|
* @param {Boolean} configuration.cascadeDelete - adds the "on delete cascade" option if true
|
2021-03-09 19:12:10 +03:00
|
|
|
* @param {import('knex')} configuration.transaction - connection object containing knex reference
|
2021-02-25 00:07:16 +03:00
|
|
|
*/
|
2021-03-02 17:06:24 +03:00
|
|
|
async function addForeign({fromTable, fromColumn, toTable, toColumn, cascadeDelete = false, transaction}) {
|
2021-03-09 19:12:10 +03:00
|
|
|
const isSQLite = db.knex.client.config.client === 'sqlite3';
|
|
|
|
if (isSQLite) {
|
|
|
|
const foreignKeyExists = await hasForeignSQLite({fromTable, fromColumn, toTable, toColumn, transaction});
|
|
|
|
if (foreignKeyExists) {
|
|
|
|
logging.warn(`Skipped adding foreign key from ${fromTable}.${fromColumn} to ${toTable}.${toColumn} - foreign key already exists`);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
try {
|
2021-03-04 16:53:06 +03:00
|
|
|
logging.info(`Adding foreign key from ${fromTable}.${fromColumn} to ${toTable}.${toColumn}`);
|
2021-03-02 17:06:24 +03:00
|
|
|
|
|
|
|
//disable and re-enable foreign key checks on sqlite because of https://github.com/knex/knex/issues/4155
|
|
|
|
let foreignKeysEnabled;
|
2021-03-09 19:12:10 +03:00
|
|
|
if (isSQLite) {
|
2021-03-02 17:06:24 +03:00
|
|
|
foreignKeysEnabled = await db.knex.raw('PRAGMA foreign_keys;');
|
|
|
|
if (foreignKeysEnabled[0].foreign_keys) {
|
|
|
|
await db.knex.raw('PRAGMA foreign_keys = OFF;');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
await (transaction || db.knex).schema.table(fromTable, function (table) {
|
|
|
|
if (cascadeDelete) {
|
2021-02-25 00:07:16 +03:00
|
|
|
table.foreign(fromColumn).references(`${toTable}.${toColumn}`).onDelete('CASCADE');
|
|
|
|
} else {
|
|
|
|
table.foreign(fromColumn).references(`${toTable}.${toColumn}`);
|
|
|
|
}
|
|
|
|
});
|
2021-03-02 17:06:24 +03:00
|
|
|
|
2021-03-09 19:12:10 +03:00
|
|
|
if (isSQLite) {
|
2021-03-02 17:06:24 +03:00
|
|
|
if (foreignKeysEnabled[0].foreign_keys) {
|
|
|
|
await db.knex.raw('PRAGMA foreign_keys = ON;');
|
|
|
|
}
|
|
|
|
}
|
2021-03-09 19:12:10 +03:00
|
|
|
} catch (err) {
|
|
|
|
if (err.code === 'ER_DUP_KEY') {
|
|
|
|
logging.warn(`Skipped adding foreign key from ${fromTable}.${fromColumn} to ${toTable}.${toColumn} - foreign key already exists`);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
throw err;
|
2021-02-25 00:07:16 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Drops a foreign key from a table.
|
|
|
|
*
|
|
|
|
* @param {Object} configuration - contains all configuration for this function
|
|
|
|
* @param {string} configuration.fromTableName - name of the table to add the foreign key to
|
|
|
|
* @param {string} configuration.fromColumn - column of the table to add the foreign key to
|
|
|
|
* @param {string} configuration.toTableName - name of the table to point the foreign key to
|
|
|
|
* @param {string} configuration.toColumn - column of the table to point the foreign key to
|
2021-03-09 19:12:10 +03:00
|
|
|
* @param {import('knex')} configuration.transaction - connection object containing knex reference
|
2021-02-25 00:07:16 +03:00
|
|
|
*/
|
|
|
|
async function dropForeign({fromTable, fromColumn, toTable, toColumn, transaction}) {
|
2021-03-09 19:12:10 +03:00
|
|
|
const isSQLite = db.knex.client.config.client === 'sqlite3';
|
|
|
|
if (isSQLite) {
|
|
|
|
const foreignKeyExists = await hasForeignSQLite({fromTable, fromColumn, toTable, toColumn, transaction});
|
|
|
|
if (!foreignKeyExists) {
|
|
|
|
logging.warn(`Skipped dropping foreign key from ${fromTable}.${fromColumn} to ${toTable}.${toColumn} - foreign key does not exist`);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
try {
|
2021-03-04 16:53:06 +03:00
|
|
|
logging.info(`Dropping foreign key from ${fromTable}.${fromColumn} to ${toTable}.${toColumn}`);
|
2021-03-02 17:06:24 +03:00
|
|
|
|
|
|
|
//disable and re-enable foreign key checks on sqlite because of https://github.com/knex/knex/issues/4155
|
|
|
|
let foreignKeysEnabled;
|
2021-03-09 19:12:10 +03:00
|
|
|
if (isSQLite) {
|
2021-03-02 17:06:24 +03:00
|
|
|
foreignKeysEnabled = await db.knex.raw('PRAGMA foreign_keys;');
|
|
|
|
if (foreignKeysEnabled[0].foreign_keys) {
|
|
|
|
await db.knex.raw('PRAGMA foreign_keys = OFF;');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
await (transaction || db.knex).schema.table(fromTable, function (table) {
|
2021-02-25 00:07:16 +03:00
|
|
|
table.dropForeign(fromColumn);
|
|
|
|
});
|
2021-03-02 17:06:24 +03:00
|
|
|
|
2021-03-09 19:12:10 +03:00
|
|
|
if (isSQLite) {
|
2021-03-02 17:06:24 +03:00
|
|
|
if (foreignKeysEnabled[0].foreign_keys) {
|
|
|
|
await db.knex.raw('PRAGMA foreign_keys = ON;');
|
|
|
|
}
|
|
|
|
}
|
2021-03-09 19:12:10 +03:00
|
|
|
} catch (err) {
|
|
|
|
if (err.code === 'ER_CANT_DROP_FIELD_OR_KEY') {
|
|
|
|
logging.warn(`Skipped dropping foreign key from ${fromTable}.${fromColumn} to ${toTable}.${toColumn} - foreign key does not exist`);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
throw err;
|
2021-02-25 00:07:16 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-25 17:54:19 +03:00
|
|
|
/**
|
|
|
|
* Checks if primary key index exists in a table over the given columns.
|
|
|
|
*
|
2021-03-09 19:12:10 +03:00
|
|
|
* @param {string} tableName - name of the table to check primary key constraint on
|
|
|
|
* @param {import('knex')} transaction - connnection object containing knex reference
|
2021-02-25 17:54:19 +03:00
|
|
|
*/
|
2021-03-09 19:12:10 +03:00
|
|
|
async function hasPrimaryKeySQLite(tableName, transaction) {
|
2021-02-25 17:54:19 +03:00
|
|
|
const knex = (transaction || db.knex);
|
|
|
|
const client = knex.client.config.client;
|
|
|
|
|
2021-03-09 19:12:10 +03:00
|
|
|
if (client !== 'sqlite3') {
|
|
|
|
throw new Error('Must use hasPrimaryKeySQLite on an SQLite3 database');
|
|
|
|
}
|
2021-02-25 17:54:19 +03:00
|
|
|
|
2021-03-09 19:12:10 +03:00
|
|
|
const rawConstraints = await knex.raw(`PRAGMA index_list('${tableName}');`);
|
|
|
|
const tablePrimaryKey = rawConstraints.find(c => c.origin === 'pk');
|
2021-02-25 17:54:19 +03:00
|
|
|
|
2021-03-09 19:12:10 +03:00
|
|
|
return tablePrimaryKey;
|
2021-02-25 17:54:19 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Adds an primary key index to a table over the given columns.
|
|
|
|
*
|
|
|
|
* @param {string} tableName - name of the table to add primaykey constraint to
|
|
|
|
* @param {string|[string]} columns - column(s) to form primary key constraint with
|
2021-03-09 19:12:10 +03:00
|
|
|
* @param {import('knex')} transaction - connnection object containing knex reference
|
2021-02-25 17:54:19 +03:00
|
|
|
*/
|
|
|
|
async function addPrimaryKey(tableName, columns, transaction) {
|
2021-03-09 19:12:10 +03:00
|
|
|
const isSQLite = db.knex.client.config.client === 'sqlite3';
|
|
|
|
if (isSQLite) {
|
|
|
|
const primaryKeyExists = await hasPrimaryKeySQLite(tableName, transaction);
|
|
|
|
if (primaryKeyExists) {
|
|
|
|
logging.warn(`Primary key constraint for: ${columns} already exists for table: ${tableName}`);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
try {
|
2021-02-25 17:54:19 +03:00
|
|
|
logging.info(`Adding primary key constraint for: ${columns} in table ${tableName}`);
|
2021-03-09 19:12:10 +03:00
|
|
|
return await (transaction || db.knex).schema.table(tableName, function (table) {
|
2021-02-25 17:54:19 +03:00
|
|
|
table.primary(columns);
|
|
|
|
});
|
2021-03-09 19:12:10 +03:00
|
|
|
} catch (err) {
|
|
|
|
if (err.code === 'ER_MULTIPLE_PRI_KEY') {
|
|
|
|
logging.warn(`Primary key constraint for: ${columns} already exists for table: ${tableName}`);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
throw err;
|
2021-02-25 17:54:19 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-10-11 15:37:11 +03:00
|
|
|
/**
|
|
|
|
* https://github.com/tgriesser/knex/issues/1303
|
|
|
|
* createTableIfNotExists can throw error if indexes are already in place
|
|
|
|
*/
|
2021-01-22 15:24:38 +03:00
|
|
|
function createTable(table, transaction, tableSpec = schema[table]) {
|
2016-10-11 15:37:11 +03:00
|
|
|
return (transaction || db.knex).schema.hasTable(table)
|
|
|
|
.then(function (exists) {
|
|
|
|
if (exists) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
return (transaction || db.knex).schema.createTable(table, function (t) {
|
2021-02-04 03:37:05 +03:00
|
|
|
Object.keys(tableSpec)
|
|
|
|
.filter(column => !(column.startsWith('@@')))
|
|
|
|
.forEach(column => addTableColumn(table, t, column, tableSpec[column]));
|
|
|
|
|
|
|
|
if (tableSpec['@@INDEXES@@']) {
|
|
|
|
tableSpec['@@INDEXES@@'].forEach(index => t.index(index));
|
|
|
|
}
|
|
|
|
if (tableSpec['@@UNIQUE_CONSTRAINTS@@']) {
|
|
|
|
tableSpec['@@UNIQUE_CONSTRAINTS@@'].forEach(unique => t.unique(unique));
|
|
|
|
}
|
2016-10-11 15:37:11 +03:00
|
|
|
});
|
2014-06-12 19:25:55 +04:00
|
|
|
});
|
2014-06-10 00:37:44 +04:00
|
|
|
}
|
|
|
|
|
2016-07-14 13:59:42 +03:00
|
|
|
function deleteTable(table, transaction) {
|
|
|
|
return (transaction || db.knex).schema.dropTableIfExists(table);
|
2014-06-12 19:25:55 +04:00
|
|
|
}
|
|
|
|
|
2016-07-14 13:59:42 +03:00
|
|
|
function getTables(transaction) {
|
2020-04-29 18:44:27 +03:00
|
|
|
const client = (transaction || db.knex).client.config.client;
|
2014-05-16 06:29:42 +04:00
|
|
|
|
2016-06-11 21:23:27 +03:00
|
|
|
if (_.includes(_.keys(clients), client)) {
|
2017-08-01 16:27:13 +03:00
|
|
|
return clients[client].getTables(transaction);
|
2014-06-12 19:25:55 +04:00
|
|
|
}
|
2014-07-10 19:10:00 +04:00
|
|
|
|
2020-05-22 21:22:20 +03:00
|
|
|
return Promise.reject(i18n.t('notices.data.utils.index.noSupportForDatabase', {client: client}));
|
2014-06-12 19:25:55 +04:00
|
|
|
}
|
|
|
|
|
2016-07-14 13:59:42 +03:00
|
|
|
function getIndexes(table, transaction) {
|
2020-04-29 18:44:27 +03:00
|
|
|
const client = (transaction || db.knex).client.config.client;
|
2014-05-16 06:29:42 +04:00
|
|
|
|
2016-06-11 21:23:27 +03:00
|
|
|
if (_.includes(_.keys(clients), client)) {
|
2016-07-14 13:59:42 +03:00
|
|
|
return clients[client].getIndexes(table, transaction);
|
2014-06-12 19:25:55 +04:00
|
|
|
}
|
2014-07-10 19:10:00 +04:00
|
|
|
|
2020-05-22 21:22:20 +03:00
|
|
|
return Promise.reject(i18n.t('notices.data.utils.index.noSupportForDatabase', {client: client}));
|
2014-06-12 19:25:55 +04:00
|
|
|
}
|
|
|
|
|
2016-07-14 13:59:42 +03:00
|
|
|
function getColumns(table, transaction) {
|
2020-04-29 18:44:27 +03:00
|
|
|
const client = (transaction || db.knex).client.config.client;
|
2014-05-16 06:29:42 +04:00
|
|
|
|
2016-06-11 21:23:27 +03:00
|
|
|
if (_.includes(_.keys(clients), client)) {
|
2014-07-10 19:10:00 +04:00
|
|
|
return clients[client].getColumns(table);
|
2014-06-10 00:37:44 +04:00
|
|
|
}
|
2014-07-10 19:10:00 +04:00
|
|
|
|
2020-05-22 21:22:20 +03:00
|
|
|
return Promise.reject(i18n.t('notices.data.utils.index.noSupportForDatabase', {client: client}));
|
2014-07-10 19:10:00 +04:00
|
|
|
}
|
|
|
|
|
2016-07-14 13:59:42 +03:00
|
|
|
function checkTables(transaction) {
|
2020-04-29 18:44:27 +03:00
|
|
|
const client = (transaction || db.knex).client.config.client;
|
2014-07-10 19:10:00 +04:00
|
|
|
|
2014-06-10 00:37:44 +04:00
|
|
|
if (client === 'mysql') {
|
2014-07-10 19:10:00 +04:00
|
|
|
return clients[client].checkPostTable();
|
2014-06-10 00:37:44 +04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-04 07:11:53 +03:00
|
|
|
function createColumnMigration(...migrations) {
|
|
|
|
async function runColumnMigration(conn, migration) {
|
|
|
|
const {
|
|
|
|
table,
|
|
|
|
column,
|
|
|
|
dbIsInCorrectState,
|
|
|
|
operation,
|
|
|
|
operationVerb,
|
|
|
|
columnDefinition
|
|
|
|
} = migration;
|
|
|
|
|
|
|
|
const hasColumn = await conn.schema.hasColumn(table, column);
|
|
|
|
const isInCorrectState = dbIsInCorrectState(hasColumn);
|
|
|
|
|
2021-02-18 20:34:34 +03:00
|
|
|
if (isInCorrectState) {
|
|
|
|
logging.warn(`${operationVerb} ${table}.${column} column - skipping as table is correct`);
|
|
|
|
} else {
|
|
|
|
logging.info(`${operationVerb} ${table}.${column} column`);
|
2019-09-04 07:11:53 +03:00
|
|
|
await operation(table, column, conn, columnDefinition);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-16 14:55:51 +03:00
|
|
|
return async function columnMigration(conn) {
|
2019-09-04 07:11:53 +03:00
|
|
|
for (const migration of migrations) {
|
|
|
|
await runColumnMigration(conn, migration);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2014-06-10 00:37:44 +04:00
|
|
|
module.exports = {
|
2014-07-10 19:10:00 +04:00
|
|
|
checkTables: checkTables,
|
2014-06-10 00:37:44 +04:00
|
|
|
createTable: createTable,
|
|
|
|
deleteTable: deleteTable,
|
2014-06-12 19:25:55 +04:00
|
|
|
getTables: getTables,
|
|
|
|
getIndexes: getIndexes,
|
|
|
|
addUnique: addUnique,
|
|
|
|
dropUnique: dropUnique,
|
2021-02-25 17:54:19 +03:00
|
|
|
addPrimaryKey: addPrimaryKey,
|
2021-02-25 00:07:16 +03:00
|
|
|
addForeign: addForeign,
|
|
|
|
dropForeign: dropForeign,
|
2014-06-12 19:25:55 +04:00
|
|
|
addColumn: addColumn,
|
2016-02-07 19:23:24 +03:00
|
|
|
dropColumn: dropColumn,
|
2019-09-04 07:11:53 +03:00
|
|
|
getColumns: getColumns,
|
|
|
|
createColumnMigration
|
2014-09-10 08:06:24 +04:00
|
|
|
};
|