-- Fix Lesson id sequence when it gets out of sync (e.g. after seed_schedule inserts with explicit ids). -- Call this before bulk-inserting lessons so new rows get unique ids. CREATE OR REPLACE FUNCTION sync_lesson_id_sequence() RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path = public AS $$ BEGIN PERFORM setval( pg_get_serial_sequence('"Lesson"', 'id'), COALESCE((SELECT MAX(id) FROM "Lesson"), 1) ); END; $$; COMMENT ON FUNCTION sync_lesson_id_sequence() IS 'Sets Lesson id sequence to max(id)+1 so next inserts do not violate Lesson_pkey.'; -- Allow authenticated users to call (needed for generate-lessons actions) GRANT EXECUTE ON FUNCTION sync_lesson_id_sequence() TO authenticated; GRANT EXECUTE ON FUNCTION sync_lesson_id_sequence() TO service_role;