From 9ff5bd1061d8be3c0e14ff9eb63a6e7eaca0c49f Mon Sep 17 00:00:00 2001 From: Stefan Blaginov Date: Mon, 24 Jan 2022 22:25:01 +0000 Subject: [PATCH] feat: ensure ID is primary key after autoupdate Signed-off-by: Stefan Blaginov --- lib/migration.js | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/lib/migration.js b/lib/migration.js index 7c4bf1191..ae6468bca 100644 --- a/lib/migration.js +++ b/lib/migration.js @@ -204,7 +204,20 @@ function mixinMigration(MySQL, mysql) { const sql = []; propNames.forEach(function(propName) { - if (m.properties[propName] && self.id(model, propName)) return; + // If the field is set as an ID inside the model + if (m.properties[propName] && self.id(model, propName)) { + const existingIdField = actualFields?.find( + ({ Field }) => Field === expectedColNameForModel(propName, m) + ); + + // And the same field is already present inside the DB, but not set as a + // primary key + if (existingIdField && existingIdField.Key !== 'PRI') { + // Set the field to а primary key + sql.push(`ADD PRIMARY KEY (\`${existingIdField.Field}\`)`); + } else { return; } + }; + let found; const colName = expectedColNameForModel(propName, m); if (actualFields) {