From 6b61bcf1230470094bc25b5b4354f1e805d45daa Mon Sep 17 00:00:00 2001 From: Naz Date: Thu, 4 Feb 2021 13:17:50 +1300 Subject: [PATCH] Added unique constraint notation to schema definition refs https://github.com/TryGhost/Ghost/issues/12567 - Introduced here @@UNIQUE_CONSTRAINTS@@ notation allows to create unique contraints over multiple database fields. This will be needed to change posts' table unique constraint from `slug` to `slug+type`. - The notation is equivalent to SQL's: UNIQUE(column_name1,column_name2) - Example use in schema: posts: { slug: {type: 'string', maxlength: 191, nullable: false}, type: {type: 'string', maxlength: 50, nullable: false, defaultTo: 'post', validations: {isIn: [['post', 'page']]}}, '@@UNIQUES@@': [ ['slug', 'type'] ] } --- core/server/data/schema/commands.js | 10 ++++++++++ core/server/models/base/index.js | 3 ++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/core/server/data/schema/commands.js b/core/server/data/schema/commands.js index d5a1eb79a7..34bfacca1c 100644 --- a/core/server/data/schema/commands.js +++ b/core/server/data/schema/commands.js @@ -104,6 +104,7 @@ function createTable(table, transaction, tableSpec = schema[table]) { return (transaction || db.knex).schema.createTable(table, function (t) { let tableIndexes = []; + let tableUniqueConstraints = []; const columnKeys = _.keys(tableSpec); _.each(columnKeys, function (column) { @@ -112,12 +113,21 @@ function createTable(table, transaction, tableSpec = schema[table]) { return; } + if (column === '@@UNIQUE_CONSTRAINTS@@') { + tableUniqueConstraints = tableSpec['@@UNIQUE_CONSTRAINTS@@']; + return; + } + return addTableColumn(table, t, column, tableSpec[column]); }); _.each(tableIndexes, function (index) { t.index(index); }); + + _.each(tableUniqueConstraints, function (unique) { + t.unique(unique); + }); }); }); } diff --git a/core/server/models/base/index.js b/core/server/models/base/index.js index 7949696c52..bfdff17ab6 100644 --- a/core/server/models/base/index.js +++ b/core/server/models/base/index.js @@ -1254,7 +1254,8 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({ // exclude fields if enabled if (exclude) { - const toSelect = _.keys(schema.tables[tableNames[modelName]]); + let toSelect = _.keys(schema.tables[tableNames[modelName]]); + toSelect = toSelect.filter(key => !(key.startsWith('@@'))); _.each(exclude, (key) => { if (toSelect.indexOf(key) !== -1) {