RezinaLMS-BackEnd/internal/repository/chapter_lessons.go

45 lines
1.5 KiB
Go

package repository
import (
"context"
"github.com/jackc/pgx/v5"
)
// GetChapterLessonContainer hides legacy module storage behind a chapter. The
// chapter row lock prevents two first lessons from creating separate containers.
func (s *Store) GetChapterLessonContainer(ctx context.Context, chapterID int64) (int64, error) {
tx, err := s.conn.Begin(ctx)
if err != nil {
return 0, err
}
defer tx.Rollback(ctx)
var id int64
if err = tx.QueryRow(ctx, `SELECT id FROM exam_prep.units WHERE id=$1 FOR UPDATE`, chapterID).Scan(&id); err != nil {
return 0, err
}
err = tx.QueryRow(ctx, `SELECT module_id FROM exam_prep.chapter_lesson_containers WHERE chapter_id=$1`, chapterID).Scan(&id)
if err == pgx.ErrNoRows {
err = tx.QueryRow(ctx, `INSERT INTO exam_prep.unit_modules (unit_id,name,sort_order,publish_status,access_tier)
SELECT $1,'__chapter_lessons__',COALESCE(MAX(sort_order),0)+1,'PUBLISHED','FREE'
FROM exam_prep.unit_modules WHERE unit_id=$1 RETURNING id`, chapterID).Scan(&id)
if err != nil {
return 0, err
}
_, err = tx.Exec(ctx, `INSERT INTO exam_prep.chapter_lesson_containers(chapter_id,module_id) VALUES($1,$2)`, chapterID, id)
}
if err != nil {
return 0, err
}
if err = tx.Commit(ctx); err != nil {
return 0, err
}
return id, nil
}
func (s *Store) lessonChapterID(ctx context.Context, moduleID int64) (int64, error) {
var id int64
err := s.conn.QueryRow(ctx, `SELECT unit_id FROM exam_prep.unit_modules WHERE id=$1`, moduleID).Scan(&id)
return id, err
}