improvements: address requested changes

This commit is contained in:
Scott Wilson
2024-10-03 12:55:53 -07:00
parent 7cd85cf84a
commit c66a711890
15 changed files with 111 additions and 119 deletions
@@ -1,5 +1,6 @@
import { Knex } from "knex";
import { dropConstraintIfExists } from "@app/db/migrations/utils/dropConstraintIfExists";
import { TableName } from "@app/db/schemas";
export async function up(knex: Knex): Promise<void> {
@@ -7,12 +8,14 @@ export async function up(knex: Knex): Promise<void> {
const hasOrgId = await knex.schema.hasColumn(TableName.KmsKey, "orgId");
const hasSlug = await knex.schema.hasColumn(TableName.KmsKey, "slug");
// drop constraint if exists (won't exist if rolled back, see below)
await dropConstraintIfExists(TableName.KmsKey, "kms_keys_orgid_slug_unique", knex);
// projectId for CMEK functionality
await knex.schema.alterTable(TableName.KmsKey, (table) => {
table.string("projectId").nullable().references("id").inTable(TableName.Project).onDelete("CASCADE");
if (hasOrgId) {
table.dropUnique(["orgId", "slug"]); // prevents using the same key name in different projects so swapping constraint
table.unique(["orgId", "projectId", "slug"]);
}
@@ -36,7 +39,6 @@ export async function down(knex: Knex): Promise<void> {
if (hasOrgId) {
table.dropUnique(["orgId", "projectId", "slug"]);
table.unique(["orgId", "slug"]);
}
table.dropColumn("projectId");
});
@@ -0,0 +1,6 @@
import { Knex } from "knex";
import { TableName } from "@app/db/schemas";
export const dropConstraintIfExists = (tableName: TableName, constraintName: string, knex: Knex) =>
knex.raw(`ALTER TABLE ${tableName} DROP CONSTRAINT IF EXISTS ${constraintName};`);