@directus/api
Version:
Directus is a real-time API and App dashboard for managing SQL database content
49 lines (47 loc) • 1.91 kB
JavaScript
import { useLogger } from "../../logger/index.js";
import { getDatabaseClient } from "../index.js";
import { createInspector } from "@directus/schema";
//#region src/database/migrations/20230721A-require-shares-fields.ts
async function up(knex) {
const isMysql = getDatabaseClient(knex) === "mysql";
if (isMysql) await dropConstraint(knex);
await knex.schema.alterTable("directus_shares", (table) => {
table.dropNullable("collection");
table.dropNullable("item");
});
if (isMysql) await recreateConstraint(knex);
}
async function down(knex) {
const isMysql = getDatabaseClient(knex) === "mysql";
if (isMysql) await dropConstraint(knex);
await knex.schema.alterTable("directus_shares", (table) => {
table.setNullable("collection");
table.setNullable("item");
});
if (isMysql) await recreateConstraint(knex);
}
/**
* Temporarily drop foreign key constraint for MySQL instances, see https://github.com/directus/directus/issues/19399
*/
async function dropConstraint(knex) {
const logger = useLogger();
const collectionForeignKeys = (await createInspector(knex).foreignKeys("directus_shares")).filter((fk) => fk.column === "collection");
const constraintName = collectionForeignKeys[0]?.constraint_name;
if (constraintName && collectionForeignKeys.length === 1) await knex.schema.alterTable("directus_shares", (table) => {
table.dropForeign("collection", constraintName);
});
else {
logger.warn(`Unexpected number of foreign key constraints on 'directus_shares.collection':`);
logger.warn(JSON.stringify(collectionForeignKeys, null, 4));
}
}
/**
* Recreate foreign key constraint for MySQL instances, from 20211211A-add-shares.ts
*/
async function recreateConstraint(knex) {
return knex.schema.alterTable("directus_shares", async (table) => {
table.foreign("collection").references("directus_collections.collection").onDelete("CASCADE");
});
}
//#endregion
export { down, up };