I am hoping to create a RPC function to update contacts
field (jsonb[]) in my users
table and matching the user’s email
.
[screenshot of users table](https://i.stack.imgur.com/QsEK6.png)
I have the below RPC function created in Supabase. I added extra logs to make sure data is correct.
CREATE OR REPLACE FUNCTION public.add_contact(p_email text, p_verified_contact jsonb)
RETURNS jsonb[] AS $$
DECLARE
updated_contacts jsonb[];
BEGIN
RAISE LOG 'Input values: email=%, verified_contact=%', p_email, p_verified_contact;
UPDATE users
SET contacts = CASE
WHEN contacts IS NULL THEN ARRAY[p_verified_contact]
ELSE contacts || p_verified_contact
END
WHERE email = p_email
RETURNING contacts INTO updated_contacts;
RAISE LOG 'The value of updated_contacts is: %', updated_contacts;
RETURN updated_contacts;
END
$$ LANGUAGE PLPGSQL;
I ran the below SQL test cases in Supabase and both worked and returned the correct data.
SELECT * FROM add_contact('[email protected]', '{"user_id":2,"user_email":"[email protected]","display_name":"Tester1"}');
UPDATE users
SET contacts = CASE
WHEN contacts IS NULL THEN ARRAY['{"user_id":4,"user_email":"[email protected]","display_name":"Tester4"}'::jsonb]
ELSE contacts || '{"user_id":4,"user_email":"[email protected]","display_name":"Tester4"}'::jsonb
END
WHERE email = '[email protected]'
RETURNING contacts;
However, when I try to update the table while using the rpc function in my codes, it only returns NULL
and does not update.
I originally had it passed as parameters, but thought I should just write the data in to avoid typo.
It returns NULL
instead of updating contacts
.
const testAddContact = async () => {
try {
const { data: updatedData, error } = await supabase.rpc("add_contact", {
p_email: "[email protected]",
p_verified_contact:
'{"user_id":5,"user_email":"[email protected]","display_name":"Tester5"}',
});
if (error) throw error;
console.log(updatedData);
return updatedData;
} catch (error) {
return console.error(error);
}
};
testAddContact();
Could anyone shed some lights on why this is? I know the function itself works, and the logs show that the correct data is being passed as parameters in the RPC function in my codes.
Thanks a bunch!