0

So I'm trying to just do it the crappy way which is multiple insert statements. Problem is I don't know how to persist the profile_id created after the companyProfile insert so that I can use it in the last insert.

Note: the ${company.id} syntax are JS variables.

Note: I'm not able to use pg_get_serial_sequence or CTEs for this in-memory DB. So trying to find another way to do this.

const query = `
insert into company (
    company_id,
    company_name
)
values (
    ${company.id},
    '${company.name}'
);

insert into companyProfile (
    company_id,
    profile_header_image_url
)
values (
    ${company.id},
    '${company.profile.header.imageUrl}'
) returning profile_id into profileId;  <<<<- this is not valid syntax

insert into company_profile (
    company_id,
    profile_id
)
values (
    ${company.id},
    profileId   <<<<<---- how can I get this from the previous insert?
);
`

companyProfile table:

CREATE TABLE companyProfile (
    profile_id integer NOT NULL,
    company_id integer NOT NULL,
    profile_header_image_url character varying NOT NULL
);

ALTER TABLE companyProfile ALTER COLUMN profile_id ADD GENERATED ALWAYS AS IDENTITY (
    SEQUENCE NAME companyProfile_profile_id_seq
    START WITH 0
    INCREMENT BY 1
    MINVALUE 0
    NO MAXVALUE
    CACHE 1
);

PositiveGuy
  • 14,005
  • 18
  • 67
  • 121
  • Does this answer your question? [PostgreSQL function for last inserted ID](https://stackoverflow.com/questions/2944297/postgresql-function-for-last-inserted-id) – Serg Jun 13 '21 at 06:44

0 Answers0