Skip to content

Instantly share code, notes, and snippets.

@kiwicopple
Last active October 2, 2024 18:50
Show Gist options
  • Save kiwicopple/94b2ec9ae2e1fda69d14ce01fb841169 to your computer and use it in GitHub Desktop.
Save kiwicopple/94b2ec9ae2e1fda69d14ce01fb841169 to your computer and use it in GitHub Desktop.
Use supabase.js to update a JSONB value

This gist shows how you can update a single value inside a JSONB column using the supabase.js client

Notes

  • 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.

Step 1: create a generic RPC

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.

Step 2: Using the RPC

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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment