From 8e7cf5f9aca7d79da21b360433ce0a1c84bb1d66 Mon Sep 17 00:00:00 2001 From: Akhil Mohan Date: Mon, 29 Apr 2024 22:25:31 +0530 Subject: [PATCH] fix(server): added index for audit log to resolve high latency or timeout caused --- .../20240429154610_audit-log-index.ts | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 backend/src/db/migrations/20240429154610_audit-log-index.ts diff --git a/backend/src/db/migrations/20240429154610_audit-log-index.ts b/backend/src/db/migrations/20240429154610_audit-log-index.ts new file mode 100644 index 000000000..40a1cb24d --- /dev/null +++ b/backend/src/db/migrations/20240429154610_audit-log-index.ts @@ -0,0 +1,28 @@ +import { Knex } from "knex"; + +import { TableName } from "../schemas"; + +export async function up(knex: Knex): Promise { + const doesOrgIdExist = await knex.schema.hasColumn(TableName.AuditLog, "orgId"); + const doesProjectIdExist = await knex.schema.hasColumn(TableName.AuditLog, "projectId"); + const doesCreatedAtExist = await knex.schema.hasColumn(TableName.AuditLog, "createdAt"); + if (await knex.schema.hasTable(TableName.AuditLog)) { + await knex.schema.alterTable(TableName.AuditLog, (t) => { + if (doesProjectIdExist && doesCreatedAtExist) t.index(["projectId", "createdAt"]); + if (doesOrgIdExist && doesCreatedAtExist) t.index(["orgId", "createdAt"]); + }); + } +} + +export async function down(knex: Knex): Promise { + const doesOrgIdExist = await knex.schema.hasColumn(TableName.AuditLog, "orgId"); + const doesProjectIdExist = await knex.schema.hasColumn(TableName.AuditLog, "projectId"); + const doesCreatedAtExist = await knex.schema.hasColumn(TableName.AuditLog, "createdAt"); + + if (await knex.schema.hasTable(TableName.AuditLog)) { + await knex.schema.alterTable(TableName.AuditLog, (t) => { + if (doesProjectIdExist && doesCreatedAtExist) t.dropIndex(["projectId", "createdAt"]); + if (doesOrgIdExist && doesCreatedAtExist) t.dropIndex(["orgId", "createdAt"]); + }); + } +}