import { sql } from 'drizzle-orm' import type { DrizzleTransaction } from './with-user' export type { DrizzleTransaction } /** * Writes to audit_log via the write_audit_log() SECURITY DEFINER function. * Must be called inside a withUser() transaction — the function reads app_current_user_id(). * Signature mirrors the DB function exactly. */ export async function writeAuditLog( tx: DrizzleTransaction, tableName: string, recordId: string, action: string, newValue?: Record | null, oldValue?: Record | null ): Promise { await tx.execute( sql`SELECT write_audit_log( ${tableName}, ${recordId}::uuid, ${action}, ${newValue ? JSON.stringify(newValue) : null}::jsonb, ${oldValue ? JSON.stringify(oldValue) : null}::jsonb )` ) }