How to upsert with serial primary key - postgresql

I have a stored procedure to perform an upsert. However the conflict condition never runs, passing an existing ID always causes it to create a new record.
create or replace function upsert_email(v_id bigint, v_subject character varying)
returns bigint
language plpgsql
as $$
declare
v_id bigint;
begin
insert into emails
(id, subject)
values (coalesce(v_id, (select nextval('serial'))), v_subject)
on conflict(id)
do update set (subject) = (v_subject) where emails.id = v_id
returning id into v_id;
return v_id;
end;
$$;
When running select upsert_email(6958500, 'subject'); which is a record that exists, it always creates a new record instead.
I have already looked at: Upsert/on conflict with serial primary key which is the most similar question and is what my SQL is modeled on, however I haven't been able to get it to work.

Wow, idiot of the year award goes to me.
I'm taking a parameter called v_id, then immediately overwrite it in the declare with a v_id; They should be named 2 different things:
create or replace function upsert_email(v_id bigint, v_subject character varying)
returns bigint
language plpgsql
as $$
declare
v_return_id bigint;
begin
insert into emails
(id, subject)
values (coalesce(v_id, (select nextval('serial'))), v_subject)
on conflict(id)
do update set (subject) = (v_subject) where emails.id = v_id
returning id into v_return_id;
return v_return_id;
end;
$$;

Related

Passing a procedure arguments to a trigger

I have a table say:
CREATE TABLE comment (
comment_id SERIAL PRIMARY KEY,
content varchar
);
and another:
CREATE TABLE comment_tree (
ancestor integer NOT NULL,
descendant integer NOT NULL,
PRIMARY KEY (ancestor, descendant),
FOREIGN KEY (ancestor) REFERENCES comment (comment_id),
FOREIGN KEY (descendant) REFERENCES comment (comment_id)
);
Now I have a procedure which insert a new comment as a child of another comment:
CREATE OR REPLACE PROCEDURE add_comment(content varchar, parent_id integer) AS $$
DECLARE
cid integer;
BEGIN
INSERT INTO comment (content) VALUES (content)
RETURNING comment_id INTO cid;
INSERT INTO comment_tree (ancestor, descendant)
VALUES (parent_id, cid);
END;
$$ LANGUAGE plpgsql;
But I want to know if it is possible to pass the parent_id to a trigger when I call the procedure instead of inserting into comment_tree inside the procedure?
You cannot pass an arbitrary variable directly to a trigger. You can use a temporary table that simulate a kind of pipe. Create a temporary table with the value you want to pass in the procedure:
CREATE OR REPLACE PROCEDURE add_comment(content varchar, parent_id integer) AS $$
DECLARE
pid integer;
BEGIN
CREATE TEMP TABLE my_temp_table AS SELECT parent_id;
INSERT INTO comment (content) VALUES (content)
RETURNING comment_id INTO pid;
DROP TABLE my_temp_table;
END;
$$ LANGUAGE plpgsql;
Then you can use it in the trigger fired after insertion:
CREATE OR REPLACE FUNCTION after_insert_on_comment()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO comment_tree (ancestor, descendant)
SELECT parent_id, new.comment_id
FROM my_temp_table;
RETURN null;
END $$;
Test it in db<>fiddle.

Insert within function fails with "query has no destination for result data"

Here is the complete example code:
CREATE TABLE testtbl (
id integer NOT NULL,
intval integer,
strval varchar(64)
);
CREATE SEQUENCE testtbl_id_seq
START WITH 1 INCREMENT BY 1
NO MINVALUE NO MAXVALUE CACHE 1;
ALTER SEQUENCE testtbl_id_seq OWNED BY testtbl.id;
ALTER TABLE ONLY testtbl ALTER COLUMN id SET DEFAULT
nextval('testtbl_id_seq'::regclass);
ALTER TABLE ONLY testtbl ADD CONSTRAINT testtbl_pkey PRIMARY KEY (id);
CREATE FUNCTION insert_testtbl (p_intval integer, p_strval varchar(64))
RETURNS integer AS $$
DECLARE
v_new_id integer;
BEGIN
INSERT INTO testtbl (intval, strval) VALUES (p_intval, p_strval)
RETURNING v_new_id;
RETURN v_new_id;
END;
$$ LANGUAGE plpgsql;
SELECT insert_testtbl(1, 'One');
When I run this (PostgreSQL version is 9.6.1), I get:
ERROR: query has no destination for result data
CONTEXT: PL/pgSQL function insert_testtbl(integer,character varying) line 5 at SQL statement
This doesn't make sense; I AM specifying a destination for the result!
What am I doing wrong here? Thanks!!!
I am specifying a destination for the result!
No you are not.
RETURNING v_new_id; simply means:
"return the current value of the variable v_new_id from this insert statement"
(which is null as the variable was never assigned a value)
You are not storing the generated value anywhere.
You either need to use an into clause:
CREATE FUNCTION insert_testtbl (p_intval integer, p_strval varchar(64))
RETURNS integer AS $$
DECLARE
v_new_id integer;
BEGIN
INSERT INTO testtbl (intval, strval) VALUES (p_intval, p_strval)
RETURNING id
INTO v_new_id; --<<< HERE
RETURN v_new_id;
END;
$$ LANGUAGE plpgsql;
Or convert everything it simple SQL function:
CREATE FUNCTION insert_testtbl (p_intval integer, p_strval varchar(64))
RETURNS integer AS
$$
INSERT INTO testtbl (intval, strval) VALUES (p_intval, p_strval)
RETURNING id;
$$ LANGUAGE sql;

Trigger insert into another table only if unique value

I have a trigger function that copy row of unique values to another table on update or insert that ALMOST work.
The trigger should only insert a new row to the sample table if the number don't exist in it before. Atm. it insert a new row to the sample table with the value NULL if the number already exist in the table. I dont want it to do anything if maintbl.number = sample.nb_main
EDIT: sample table and sample data
CREATE TABLE schema.main(
sid SERIAL NOT NULL,
number INTEGER,
CONSTRAINT sid_pk PRIMARY KEY (sid)
)
CREATE TABLE schema.sample(
gid SERIAL NOT NULL,
nb_main INTEGER,
CONSTRAINT gid_pk PRIMARY KEY (gid)
Example and desired result
schema.main schema.sample
number nb_main
234233 234233
234234 555555
234234
555555
555555
CREATE OR REPLACE FUNCTION schema.update_number()
RETURNS trigger AS
$BODY$
BEGIN
INSERT INTO schema.sample(
nb_main)
SELECT DISTINCT(maintbl.number)
FROM schema.maintbl
WHERE NOT EXISTS (
SELECT nb_main FROM schema.sample WHERE maintbl.number = sample.nb_main);
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION schema.update_number()
OWNER TO postgres;
CREATE TRIGGER update_number
AFTER INSERT OR UPDATE
ON schema.maintbl
FOR EACH ROW
EXECUTE PROCEDURE schema.update_number();
I just found out that my select query is probably wrong, if I run SELECT query by itself it return one row 'NULL' but i should not?
SELECT DISTINCT(maintbl.number)
FROM schema.maintbl
WHERE NOT EXISTS (
SELECT nb_main FROM schema.sample WHERE maintbl.number = sample.nb_main);
Any good advice?
Best
If I understood correctly, you wish to append to schema.sample a number that has been inserted or updated in schema.maintbl, right?
CREATE OR REPLACE FUNCTION schema.update_number()
RETURNS trigger AS
$BODY$
BEGIN
IF (SELECT COUNT(*) FROM schema.sample WHERE number = NEW.number) = 0 THEN
INSERT INTO schema.sample(nb_main) VALUES (NEW.number);
END IF;
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql VOLATILE;

PL/Proxy returning Unsupported Type on Stored Procedure Call

I've setup a Stored Procedure in PL/Proxy to make a query, and receive some RECORDs back.
In PL/Proxy:
CREATE OR REPLACE FUNCTION query_autocomplete(q text, i_id bigint)
RETURNS SETOF RECORD AS $$
CLUSTER 'autocompletecluster';
RUN ON i_id;
$$ LANGUAGE plproxy;
In each Partition:
CREATE OR REPLACE FUNCTION query_autocomplete(q text, i_id bigint)
RETURNS SETOF RECORD AS $$
DECLARE
rec RECORD;
BEGIN
FOR rec IN EXECUTE q
LOOP
RETURN NEXT rec;
END LOOP;
RETURN;
END;
$$ LANGUAGE plpgsql;
As you've likely guessed, this is hitting a defined SERVER in PGSQL called 'autocompletecluster'. The query string that I'm sending through is as follows:
$sql = "SELECT * FROM autocomplete WHERE member_id = :memberId";
$query = $this->db->prepare("SELECT query_autocomplete('{$sql}',1234");
It's returning the following:
SQLSTATE[XX000]: Internal error: 7 ERROR: PL/Proxy function public.query_autocomplete(0): unsupported type
The table that query is hitting is defined as such:
CREATE TABLE autocomplete (
id character varying(100) NOT NULL,
extra_data hstore,
username character varying(254),
member_id bigint
);
What am I doing wrong?
The error strongly suggests that PL/Proxy doesn't support SETOF RECORD. Try instead defining your functions to return autocomplete%rowtype or, failing that, RETURNS TABLE (...) with a matching columns-set.

Autoincrement field with trigger and sequence - Check if ID is in the statement [Postgres]

I´ve got this sample from another thread and it fits perfectly on what I need to know.
CREATE SEQUENCE AlimentosSequencia;
CREATE TABLE alimento (
id integer NOT NULL PRIMARY KEY
,name VARCHAR(255));
CREATE OR REPLACE FUNCTION AlimentoFuncion()
RETURNS "trigger" AS
$BODY$
BEGIN
New.id:=nextval('AlimentosSequencia');
Return NEW;
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE;
CREATE TRIGGER AlimentosTrigger
BEFORE INSERT
ON alimento
FOR EACH ROW
EXECUTE PROCEDURE AlimentoFuncion();
INSERT INTO alimento (name) VALUES ('lemon');
This is working fine! But I have to complement the function AlimentoFunction.
Is there any way to check IN THE FUNCTION if my insert statement is placing an ID?
Example:
INSERT INTO alimento (name) VALUES ('lemon');
Ok this, works... and If I do that:
INSERT INTO alimento (id, name) VALUES (299, 'lemon');
My function must check if the sequence has to be used.
I know I can set the default value of ID to be the sequence on the table creation, but I can't modify that.. I just can change the trigger function.
Something like:
if new.id is NULL then
New.id:=nextval('AlimentosSequencia');
end if;