This gist shows how you can update a single value inside a JSONB column using the supabase.js client
- I would consider this function unsafe and it should only be used on the server to avoid any risk of SQL injection.
- This is generated by ChatGPT and untested: I can't vouch for the relability of this function.
CREATE OR REPLACE FUNCTION update_jsonb_element(
table_name text,
id_column text,
id_value int,
jsonb_column text,
jsonb_path text[],
new_value jsonb
)
RETURNS void
SECURITY INVOKER
LANGUAGE plpgsql;
AS
$$
BEGIN
EXECUTE format(
'UPDATE %I SET %I = jsonb_set(%I, %L, %L, false) WHERE %I = %L',
table_name,
jsonb_column,
jsonb_column,
jsonb_path,
new_value::text,
id_column,
id_value
);
END;
$$
This uses jsonb_set()
to update a specific field in the JSONB column. This function accepts deep paths using additional elements in the path array, e.g., {parent, child}
for nested elements.
You can now use this function with the supabase-js client
const { data, error } = await supabase
.rpc('update_jsonb_element', {
table_name: 'your_table',
id_column: 'id',
id_value: 123, // row ID
jsonb_column: 'your_jsonb_column',
jsonb_path: ['parent', 'child', 'key'],
new_value: { value: 'new_value' } // new JSONB value
});
if (error) {
console.error('Error executing RPC:', error);
} else {
console.log('Update successful:', data);
}