Hello. I would like to have a query that inserts data in mulitple tables at once. My understanding is that the best way to do that is via the "functions" tool in Supabase.
Some context: the user is creating a deck of flashcards. The deck is associated with a lesson, which is associated with a subject. The idea is that the user specifies the subject name, lesson name, and creates a list of cards (or tells OpenAI to do it for them) in the interface before clicking save.
DECLARE _subject_id UUID; _lesson_id UUID;BEGIN -- Insert subject INSERT INTO subjects (creator_id, name, current_level) VALUES (_creator_id, _subject_name, _current_level) RETURNING id INTO _subject_id; -- Insert lesson INSERT INTO lessons (creator_id, title, subject_id) VALUES (_creator_id, _lesson_title, _subject_id) RETURNING id INTO _lesson_id; -- Insert cards INSERT INTO cards (lesson_id, creator_id, side1, side2) SELECT _lesson_id, _creator_id, card->>'side1', card->>'side2' FROM jsonb_array_elements(_cards::jsonb) AS card;EXCEPTION WHEN OTHERS THEN -- If there is any error, rollback the transaction RAISE;END;
DECLARE _subject_id UUID; _lesson_id UUID;BEGIN -- Insert subject INSERT INTO subjects (creator_id, name, current_level) VALUES (_creator_id, _subject_name, _current_level) RETURNING id INTO _subject_id; -- Insert lesson INSERT INTO lessons (creator_id, title, subject_id) VALUES (_creator_id, _lesson_title, _subject_id) RETURNING id INTO _lesson_id; -- Insert cards INSERT INTO cards (lesson_id, creator_id, side1, side2) SELECT _lesson_id, _creator_id, card->>'side1', card->>'side2' FROM jsonb_array_elements(_cards::jsonb) AS card;EXCEPTION WHEN OTHERS THEN -- If there is any error, rollback the transaction RAISE;END;
I have specified each of the arguments in the Supabase function creator, with the
_cards
_cards
argument set to
jsonb
jsonb
Here is the format of the parameter being submitted
Supabase gives you the tools, documentation, and community that makes managing databases, authentication, and backend infrastructure a lot less overwhelming.