improvement: optimize database filtering to only use GIN index when necessary

This commit is contained in:
Daniel Hougaard
2025-04-01 04:14:21 +04:00
parent a07f168c36
commit fd20cb1e38
@@ -96,19 +96,25 @@ export const auditLogDALFactory = (db: TDbClient) => {
const eventIsSecretType = !eventType?.length || eventType.some((event) => filterableSecretEvents.includes(event)); const eventIsSecretType = !eventType?.length || eventType.some((event) => filterableSecretEvents.includes(event));
// We only want to filter for environment/secretPath/secretKey if the user is either checking for all event types // We only want to filter for environment/secretPath/secretKey if the user is either checking for all event types
// ? Note(daniel): use the `eventMetadata" @> ?::jsonb` approach to properly use our GIN index
if (projectId && eventIsSecretType) { if (projectId && eventIsSecretType) {
if (environment) { if (environment || secretPath) {
void sqlQuery.whereRaw(`"eventMetadata"->>'environment' = ?`, [environment]); // Handle both environment and secret path together to only use the GIN index once
void sqlQuery.whereRaw(`"eventMetadata" @> ?::jsonb`, [
JSON.stringify({
...(environment && { environment }),
...(secretPath && { secretPath })
})
]);
} }
if (secretPath) { // Handle secret key separately to include the OR condition
void sqlQuery.whereRaw(`"eventMetadata"->>'secretPath' = ?`, [secretPath]);
}
if (secretKey) { if (secretKey) {
void sqlQuery.whereRaw( void sqlQuery.whereRaw(
`("eventMetadata"->>'secretKey' = ? `("eventMetadata" @> ?::jsonb
OR "eventMetadata"->'secrets' @> ?::jsonb)`, OR "eventMetadata"->'secrets' @> ?::jsonb)`,
[secretKey, JSON.stringify([{ secretKey }])] [JSON.stringify({ secretKey }), JSON.stringify([{ secretKey }])]
); );
} }
} }