React, Supabase Functions, and passing Objects

72 views Asked by At

I'm working using next js and Supabase.

I have a jobs table, a schedule table, and a work-type table. When I create a new row in jobs, I plan to add one too many rows to record that job's schedules in the 'job_schedules' table, and again to write that job's work types in a table called 'job_worktypes'.

I got it in my head that since the job table needs 13 fields, and the job_schedules needs a possible array of data to write, and so does job_work_types, I'd use a function so that the writing of the records wouldn't commit unless all these writes succeed.

My plan was to pass in an object to the function containing the 13 fields for a new job, and two arrays for the other two tables.

I am not succeeding in part 1, passing in the object with 13 fields.

First, I'm getting an error.

"null value in column "id" of relation "jobs" violates not-null constraint"

I have an auto-incrementing ID in the 8 fields in jobs. I did not add an id in 'job_data'. Earlier in development, when I only had 3 or 4 fields as a test record, I could write new records without including the ID and it'd insert fine. What am I doing wrong in using an object as an insert?

Second, if I may, how do I store the newly created jobs.id for use in writing multiple records into two additional tables further along in this function?

I have a function to insert a job record. The react object 'job_data' contains all of the fields that are in the database except id and the timestamp. The function looks like this:

CREATE OR REPLACE FUNCTION insert_job_record(job_data public.jobs)
  returns int as $$
  begin
    insert into jobs
    select job_data.* 
    returning id;
  end;
$$ language plpgsql;

With this function, I call it in react like this

let { data, error } = await supabase.rpc("insert_job_record", {
  job_data,
});
0

There are 0 answers