RezinaLMS-BackEnd/db/query/activity_logs.sql
Yared Yemane 977e4e73e2 Speed up activity log listing with batch actor lookups and search filter.
Batch-load users and team members per page instead of N+1 lookups, and add server-side search on message, action, and resource fields.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-19 13:13:28 +03:00

48 lines
1.9 KiB
SQL

-- name: CreateActivityLog :one
INSERT INTO activity_logs (
actor_id, actor_role, action, resource_type, resource_id,
message, metadata, ip_address, user_agent
) VALUES (
sqlc.narg('actor_id'), sqlc.narg('actor_role'),
@action, @resource_type, sqlc.narg('resource_id'),
sqlc.narg('message'), COALESCE(sqlc.narg('metadata'), '{}'::jsonb),
sqlc.narg('ip_address'), sqlc.narg('user_agent')
)
RETURNING *;
-- name: ListActivityLogs :many
SELECT
COUNT(*) OVER() AS total_count,
al.id,
al.actor_id,
al.actor_role,
al.action,
al.resource_type,
al.resource_id,
al.message,
al.metadata,
al.ip_address,
al.user_agent,
al.created_at
FROM activity_logs al
WHERE
(sqlc.narg('filter_actor_id')::bigint IS NULL OR al.actor_id = sqlc.narg('filter_actor_id'))
AND (sqlc.narg('filter_action')::text IS NULL OR al.action = sqlc.narg('filter_action'))
AND (sqlc.narg('filter_resource_type')::text IS NULL OR al.resource_type = sqlc.narg('filter_resource_type'))
AND (sqlc.narg('filter_resource_id')::bigint IS NULL OR al.resource_id = sqlc.narg('filter_resource_id'))
AND (sqlc.narg('filter_after')::timestamptz IS NULL OR al.created_at >= sqlc.narg('filter_after'))
AND (sqlc.narg('filter_before')::timestamptz IS NULL OR al.created_at <= sqlc.narg('filter_before'))
AND (
sqlc.narg('filter_search')::text IS NULL
OR btrim(sqlc.narg('filter_search')::text) = ''
OR al.message ILIKE '%' || btrim(sqlc.narg('filter_search')::text) || '%'
OR al.action ILIKE '%' || btrim(sqlc.narg('filter_search')::text) || '%'
OR al.resource_type ILIKE '%' || btrim(sqlc.narg('filter_search')::text) || '%'
OR al.resource_id::text LIKE '%' || btrim(sqlc.narg('filter_search')::text) || '%'
)
ORDER BY al.created_at DESC
LIMIT @log_limit OFFSET @log_offset;
-- name: GetActivityLogByID :one
SELECT * FROM activity_logs WHERE id = $1;