I'm using node-pg and I've decided to refactor some code that would first make a select query to see if a record exists and then make a second query to either insert or update a record.
Suppose the following table structure:
CREATE TABLE IF NOT EXISTS my_schema.user_profile (
id SERIAL PRIMARY KEY,
user_id BIGINT REFERENCES %%.user (id) UNIQUE NOT NULL,
media_url VARCHAR(50) NOT NULL,
created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT (NOW() AT TIME ZONE 'utc'),
updated_at TIMESTAMP WITHOUT TIME ZONE DEFAULT (NOW() AT TIME ZONE 'utc')
);
I've landed on something like the below,
const request = {
userId: 123,
mediaUrl: 'https://...'
};
const query = `
INSERT INTO my_schema.user_profile
(user_id, media_url)
VALUES
($1, $2)
ON CONFLICT (user_id)
DO UPDATE SET (
updated_at,
media_url
) = (
CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC',
$1
)
`;
const values = [
request.userId,
request.mediaUrl
];
const result = await client.query(query, values);
However the problem here is that values is valid only for the insert part of the query. If a record exists that needs to be updated, then this array of values is not correct, it would have to be:
const values = [
request.mediaUrl,
];
But then node-pg will start complaining about the update portion of the query having more columns being updated than paramterized provided.
How would I be able to get something like this to work?
user_idandmedia_url. If a record already happens to exists with the provideduser_id(as I've specified in theon conflictclause), then I'd like to update that record byuser_idand set a new value forupdated_atandmedia_urlWHEREclause).whereclause, but the problem is still in the fact that$1is going to get mapped tovalues[0](which isrequest.userId). I need it to map torequest.mediaUrl. And now that I've removed thewhere user_id = $2part,node-pgwill start complaining about theupdateportion of the query and the fact that there are more values provided than columns being updatedDO UPDATE SET (updated_at, media_url) = (CURRENT_TIMESTAMP, $2)? Nothing says the the parameters have to occur in the query only once or in order.