Updates
This commit is contained in:
Vendored
+52
@@ -0,0 +1,52 @@
|
||||
import MariaDBQuoteGen from "./mariadb-quote-gen";
|
||||
import runSchemaQuery, { querySchemaRows } from "./run-schema-query";
|
||||
import schemaCondition from "./schema-condition";
|
||||
function columnsEqual(a, b) {
|
||||
return a.length === b.length && a.every((col, i) => col === b[i]);
|
||||
}
|
||||
export function grabDesiredPrimaryKeyColumns(table) {
|
||||
return (table.fields || [])
|
||||
.filter((field) => field.primaryKey && field.fieldName)
|
||||
.map((field) => field.fieldName);
|
||||
}
|
||||
async function grabLivePrimaryKeyColumns({ tableName, config, }) {
|
||||
const schemaCond = schemaCondition(config);
|
||||
const rows = await querySchemaRows({
|
||||
query: `
|
||||
SELECT COLUMN_NAME, ORDINAL_POSITION
|
||||
FROM information_schema.KEY_COLUMN_USAGE
|
||||
WHERE ${schemaCond.where}
|
||||
AND TABLE_NAME = ?
|
||||
AND CONSTRAINT_NAME = 'PRIMARY'
|
||||
ORDER BY ORDINAL_POSITION
|
||||
`,
|
||||
values: [...schemaCond.values, tableName],
|
||||
config,
|
||||
});
|
||||
return rows.map((row) => row.COLUMN_NAME);
|
||||
}
|
||||
export default async function syncPrimaryKey({ table, config, }) {
|
||||
const desired = grabDesiredPrimaryKeyColumns(table);
|
||||
const live = await grabLivePrimaryKeyColumns({
|
||||
tableName: table.tableName,
|
||||
config,
|
||||
});
|
||||
if (columnsEqual(desired, live)) {
|
||||
return;
|
||||
}
|
||||
if (live.length > 0) {
|
||||
console.log(`Dropping primary key on ${table.tableName}`);
|
||||
await runSchemaQuery({
|
||||
query: `ALTER TABLE ${MariaDBQuoteGen(table.tableName)} DROP PRIMARY KEY`,
|
||||
config,
|
||||
});
|
||||
}
|
||||
if (desired.length > 0) {
|
||||
const cols = desired.map((col) => MariaDBQuoteGen(col)).join(", ");
|
||||
console.log(`Creating primary key (${desired.join(", ")}) on ${table.tableName}`);
|
||||
await runSchemaQuery({
|
||||
query: `ALTER TABLE ${MariaDBQuoteGen(table.tableName)} ADD PRIMARY KEY (${cols})`,
|
||||
config,
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user