Yimaru-BackEnd/db/query/exam_prep_catalog_courses.sql
Yared Yemane 4124f98160 Include nested content counts in exam-prep catalog list response.
Add units, modules, and lessons aggregate counts per catalog course so clients can render hierarchy depth without extra API calls.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-05 06:13:01 -07:00

69 lines
1.9 KiB
SQL

-- name: ExamPrepCreateCatalogCourse :one
INSERT INTO exam_prep.catalog_courses (name, description, thumbnail, sort_order)
SELECT
$1,
$2,
$3,
coalesce((
SELECT
max(c.sort_order)
FROM exam_prep.catalog_courses AS c), 0) + 1
RETURNING
*;
-- name: ExamPrepGetCatalogCourseByID :one
SELECT *
FROM exam_prep.catalog_courses
WHERE id = $1;
-- name: ExamPrepListCatalogCourses :many
WITH catalog_course_counts AS (
SELECT
u.catalog_course_id,
COUNT(DISTINCT u.id)::BIGINT AS units_count,
COUNT(DISTINCT m.id)::BIGINT AS modules_count,
COUNT(DISTINCT l.id)::BIGINT AS lessons_count
FROM exam_prep.units u
LEFT JOIN exam_prep.unit_modules m ON m.unit_id = u.id
LEFT JOIN exam_prep.unit_module_lessons l ON l.unit_module_id = m.id
GROUP BY u.catalog_course_id
)
SELECT
COUNT(*) OVER () AS total_count,
c.id,
c.name,
c.description,
c.thumbnail,
c.sort_order,
COALESCE(cc.units_count, 0)::BIGINT AS units_count,
COALESCE(cc.modules_count, 0)::BIGINT AS modules_count,
COALESCE(cc.lessons_count, 0)::BIGINT AS lessons_count,
c.created_at,
c.updated_at
FROM exam_prep.catalog_courses c
LEFT JOIN catalog_course_counts cc ON cc.catalog_course_id = c.id
ORDER BY c.sort_order ASC, c.id ASC
LIMIT $1 OFFSET $2;
-- name: ExamPrepListAllCatalogCourseIDs :many
SELECT
id
FROM exam_prep.catalog_courses
ORDER BY id;
-- name: ExamPrepUpdateCatalogCourse :one
UPDATE exam_prep.catalog_courses
SET
name = coalesce(sqlc.narg('name')::varchar, name),
description = coalesce(sqlc.narg('description')::text, description),
thumbnail = coalesce(sqlc.narg('thumbnail')::text, thumbnail),
sort_order = coalesce(sqlc.narg('sort_order')::int, sort_order),
updated_at = CURRENT_TIMESTAMP
WHERE id = sqlc.arg('id')
RETURNING
*;
-- name: ExamPrepDeleteCatalogCourse :exec
DELETE FROM exam_prep.catalog_courses
WHERE id = $1;