Here, im trying to do a ‘custom SQL query for write operation’, to write into my attendance table.
I’m trying to get the custom query to throw an error if the teacher_id and enrollment_id doesn’t have a matching row in the enrollments table.
this is the Query that doesn’t work:
DO $$
BEGIN
IF NOT EXISTS ( SELECT 1 FROM enrollments WHERE enrollment_id = **currentItem ▸ enrollment_id** AND teacher_id = **currentUser ▸ customProperties ▸ teacher_id** ) THEN RAISE EXCEPTION 'No matching enrollment found for the given enrollment ID and teacher ID'; END IF; INSERT INTO attendance (enrollment_id, attended) SELECT **currentItem ▸ enrollment_id**, true;
END $$;
However if i replace the dynamic values with the actual value, it works.
e.g.:
DO $$
BEGIN
IF NOT EXISTS ( SELECT 1 FROM enrollments WHERE enrollment_id = **'EnrollmentAbc123'** AND teacher_id = **'teacherAbc123'** ) THEN RAISE EXCEPTION 'No matching enrollment found for the given enrollment ID and teacher ID'; END IF; INSERT INTO attendance (enrollment_id, attended) SELECT **'EnrollmentAbc123'**, true;
END $$;
Here’s another version of the custom query, but it doesn’t throw an error, it just matches. This query works fine, but it just doesn’t throw an error when there isn’t a match:
INSERT INTO attendance (enrollment_id,attended)
SELECT currentItem ▸ enrollment_id,true
WHERE EXISTS (
SELECT 1
FROM enrollments
WHERE enrollment_id = currentItem ▸ enrollment_id
AND teacher_id = currentUser ▸ customProperties ▸ teacher_id
);
hope i am describing this situation well.