diff --git a/backend/src/db/migrations/20241002110531_add-audit-log-metadata-index.ts b/backend/src/db/migrations/20241002110531_add-audit-log-metadata-index.ts index d07211a90f..96854693a6 100644 --- a/backend/src/db/migrations/20241002110531_add-audit-log-metadata-index.ts +++ b/backend/src/db/migrations/20241002110531_add-audit-log-metadata-index.ts @@ -8,8 +8,14 @@ export async function up(knex: Knex): Promise { `CREATE INDEX "audit_logs_actorMetadata_idx" ON ${TableName.AuditLog} USING gin("actorMetadata" jsonb_path_ops)` ); } + if (await knex.schema.hasColumn(TableName.AuditLog, "eventMetadata")) { + await knex.raw( + `CREATE INDEX "audit_logs_eventMetadata_idx" ON ${TableName.AuditLog} USING gin("eventMetadata" jsonb_path_ops)` + ); + } } export async function down(knex: Knex): Promise { await knex.raw(`DROP INDEX IF EXISTS "audit_logs_actorMetadata_idx"`); + await knex.raw(`DROP INDEX IF EXISTS "audit_logs_eventMetadata_idx"`); } diff --git a/backend/src/ee/services/audit-log/audit-log-dal.ts b/backend/src/ee/services/audit-log/audit-log-dal.ts index 4398486e1d..e528bfa44d 100644 --- a/backend/src/ee/services/audit-log/audit-log-dal.ts +++ b/backend/src/ee/services/audit-log/audit-log-dal.ts @@ -77,13 +77,13 @@ export const auditLogDALFactory = (db: TDbClient) => { // Special case: Filter by actor ID if (actorId) { - void sqlQuery.whereRaw(`"actorMetadata"->>'userId' = ?`, [actorId]); + void sqlQuery.whereRaw(`"actorMetadata" @> jsonb_build_object('userId', ?::text)`, [actorId]); } // Special case: Filter by key/value pairs in eventMetadata field if (eventMetadata && Object.keys(eventMetadata).length) { Object.entries(eventMetadata).forEach(([key, value]) => { - void sqlQuery.whereRaw(`"eventMetadata"->>'${key}' = ?`, [value]); + void sqlQuery.whereRaw(`"eventMetadata" @> jsonb_build_object(?::text, ?::text)`, [key, value]); }); } @@ -104,6 +104,7 @@ export const auditLogDALFactory = (db: TDbClient) => { if (endDate) { void sqlQuery.where(`${TableName.AuditLog}.createdAt`, "<=", endDate); } + const docs = await sqlQuery; return docs;