Sample Header Ad - 728x90

Insert values to table only if first Insert was successful

2 votes
1 answer
1855 views
Is there a way I could check the status of an insert query whether it was successful or not. I want to write to another table only if the first insertion was successful. Below is the table I want to do the first insert and also it should return the conversation_id which I need for to make an insert to the second table. Conversations table - create table conversations ( id uuid not null, conversation_id text UNIQUE PRIMARY KEY not null, participants jsonb not null, created_at timestamp with time zone, updated_at timestamp with time zone, avatar_url varchar(500), last_message varchar(32000) ) After the successful insert on the first table, I should use the returned conversation_id and insert a record onto the messages table.After successful insertion it should return the value of the message field returned. Messages Table - create table messages ( id uuid not null primary key, conversation_id text references conversations.conversation_id not null, message text, sender_id text, receiver_id text, message_type text, created_at timestamp with time zone DEFAULT now() ) And after the two inserts I need to make an update to the first table again with the returned value of the message field. Here is the full function to do the above, the below function works when calling using select, but when I call it through my client I get this error -- Could not find the public.new_conversation(members, the_conversationId) function in the schema cache CREATE OR REPLACE FUNCTION public.new_conversation(the_conversationId text, members jsonb, sent_message text) RETURNS text LANGUAGE plpgsql AS $function$ declare conv_id text; the_message text; BEGIN SELECT conversation_id into conv_id FROM conversations WHERE conversation_id = the_conversationId; if not found then insert into conversations(conversation_id, participants) values(the_conversationId,members) Returning conversation_id into conv_id; if found then insert into messages(conversation_id,message) values(conv_id,sent_message) Returning message into the_message; if found THEN update conversations set last_message = the_message where conversation_id = conv_id; end if; end if; end if; return conv_id; END; $function$ Should I be doing any exceptions handling for my insert statements?
Asked by Sumchans (145 rep)
Sep 1, 2021, 07:13 PM
Last activity: Sep 2, 2021, 12:33 PM