Postgres trigger creation - ERROR: no language specified SQL state: 42P13 - sql

I am new to triggers. I am trying to create a trigger by following this link - http://www.postgresqltutorial.com/creating-first-trigger-postgresql/. But it gives some error. The code block and the error is given below.
Code block:
CREATE OR REPLACE FUNCTION log_last_name_changes()
RETURNS trigger AS
$BODY$
BEGIN
IF NEW.last_name <> OLD.last_name THEN
INSERT INTO employee_audits(employee_id,last_name,changed_on)
VALUES(OLD.id,OLD.last_name,now());
END IF;
RETURN NEW;
END;
$BODY$
And the error:
ERROR: no language specified
SQL state: 42P13
What can I try next?

Try this way:
CREATE OR REPLACE FUNCTION log_last_name_changes()
RETURNS trigger AS
$BODY$
BEGIN
IF NEW.last_name <> OLD.last_name THEN
INSERT INTO employee_audits(employee_id,last_name,changed_on)
VALUES(OLD.id,OLD.last_name,now());
END IF;
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql VOLATILE -- Says the function is implemented in the plpgsql language; VOLATILE says the function has side effects.
COST 100; -- Estimated execution cost of the function.

If arriving here because your function gave you the same error (like mine did).. here's an over-baked example of using a function to update the tweet on the bottom right "blurb" with "hello world".
Important note: language goes BEFORE the last semicolon (see below). This is easy to miss in the accepted solution.
id (serial)
pub_id (text)
tweet (text)
1
abc
hello world
2
def
blurb
-- Optional drop if replace fails below.
drop function if exists sync_tweets(text, text);
create or replace function sync_tweets(
src_pub_id text, -- function arguments
dst_pub_id text
) returns setof tweets as -- i.e. rows. int, text work too
$$
declare
src_id int; -- temp function variables (not args)
dest_id int;
src_tweet text;
begin
-- query result into a temp variable
src_id := (select id from tweets where pub_id = src_pub_id);
-- query result into a temp variable (another way)
select tweet into src_tweet from tweets where id = src_id;
dest_id := (select id from tweets where pub_id = dst_pub_id);
update tweets set tweet=src_tweet where id = dest_id;
return query -- i.e. rows, return 0 with return int above works too
select * from tweets where pub_id in (src_pub_id, dst_pub_id);
end
$$ language plpgsql; -- need the language to avoid ERROR 42P13
-- Run it!
select * from sync_tweets('abc', 'def');
/*
Outputs
__________________________________________________
| id (serial) | pub_id (text) | tweet (text) |
|---------------|-----------------|----------------|
| 1 | abc | hello world |
| 2 | def | blurb |
--------------------------------------------------
*/

Related

Postgres function to return Table into variables

How can I capture different columns into different variables like so (note this is only pseudocode so I am assuming it will cause errors. Example taken from here)
create or replace function get_film (
p_pattern varchar
)
returns table (
film_title varchar,
film_release_year int
)
language plpgsql
as $$
begin
return query
select
title,
release_year::integer
from
film
where
title ilike p_pattern;
end;$$
create or replace function get_film_into_variables (
p_pattern varchar
)
returns null
language plpgsql
as $$
declare
v_title varchar,
v_release_year integer
begin
SELECT
get_film (p_pattern)
INTO
v_title,
v_release_year;
end;$$
Assuming you have some purpose for the variables after retrieving them not just ending the function your "get_film_into_variables" is almost there. But first let's backup just a bit. A function that returns a table does just that, you can use the results just like a table stored on disk (it just goes away after query or calling function ends). To that end only a slight change to the "get_film_into_variables" function is required. The "get_film" becomes the object of the FROM clause. Also change the returns null, to returns void. So
create or replace function get_film_into_variables (
p_pattern varchar
)
returns void
language plpgsql
as $$
declare
v_title varchar;
v_release_year integer;
begin
select *
from get_film (p_pattern)
INTO
v_title,
v_release_year;
end;
$$;
The above works for a single row returned by a function returning table. However for a return of multiple rows you process the results of the table returning function just lake you would an actual table - with a cursor.
create or replace
function get_film_into_variables2(p_pattern varchar)
returns void
language plpgsql
as $$
declare
k_message_template constant text = 'The film "%s" was released in %s.';
v_title varchar;
v_release_year integer;
v_film_message varchar;
c_film cursor (c_pattern varchar) for
select * from get_film (c_pattern);
begin
open c_film (p_pattern);
loop
fetch c_film
into v_title
, v_release_year;
exit when not found;
v_film_message = format( k_message_template,v_title,v_release_year::text);
raise notice using
message = v_film_message;
end loop;
end;
$$;
BTW: the get_film function can be turned into a SQL function. See fiddle here. For demo purposes get_film_into_variable routines return a message.

Postgresql functions

These are the type definitions provided to me
create type IR as (pattern_number integer, uoc_number integer);
My current progress is:
create or replace function q1(pattern text, uoc_threshold integer)
returns setof IR
as $$
BEGIN
RETURN QUERY
select count(code) from temp where code like $1;
RETURN QUERY
select count(code) from temp where code like $1 and uoc > $2;
END;
$$ language plpgsql;
My output needs to be like this :
Query:-
select *
from q1('ECO%', 6);
pattern_number | uoc_number
80 | 5
I get an error saying:
ERROR: structure of query does not match function result type
DETAIL: Returned type bigint does not match expected type integer in column 1.
CONTEXT: PL/pgSQL function q1(text,integer) line 3 at RETURN QUERY
How do I fix this?
Is it what you want?..
create or replace function q1(pattern text, uoc_threshold integer)
returns setof IR
as $$
BEGIN
RETURN QUERY
select (select count(code) from temp where code like $1)::integer
,(
select count(code) from temp where code like $1 and uoc > $2)::integer;
END;
$$ language plpgsql;

query has no destination for result data - PostgreSQL

I have created the following stored procedure in PostgreSQL:
CREATE OR REPLACE function incomingdel(IN del_ID varchar) RETURNS VOID AS $$
DECLARE xyz integer;
BEGIN
SELECT * INTO xyz FROM incomingcheck(cast(del_ID as integer));
IF xyz <> 1
THEN
SELECT * INTO xyz FROM perfdel(cast(del_ID as integer));
END IF;
END
$$ LANGUAGE plpgsql
even though the function returns VOID, I am still getting
Error: query has no destination for result data
when i execute the function. Can someone please help?
Thanks
When you do SELECT * INTO ... in a PL/pgSQL function you need to supply a variable of type record or of the row type of the row source, even if the function only returns an integer. The functions incomingcheck(int) and perfdel(int) are obviously returning a single integer in which case you can simplify your function:
CREATE FUNCTION incomingdel(del_ID integer) RETURNS VOID AS $$
DECLARE
xyz integer;
BEGIN
xyz := incomingcheck(del_ID);
IF xyz <> 1 THEN
xyz := perfdel(del_ID);
END IF;
-- Do something with xyz
END; $$ LANGUAGE plpgsql;
If the functionality is actually in the called functions (so you do not process the xyz value), then it becomes simpler still:
CREATE FUNCTION incomingdel(del_ID integer) RETURNS VOID AS $$
BEGIN
IF incomingcheck(del_ID) <> 1 THEN
perfdel(del_ID);
END IF;
END; $$ LANGUAGE plpgsql;

passing cursor values into another function

*i have a function which will delete the rows in the table for the given input id, the input is given to the function by another cursor_function.*
select * from t1;
id | col1
----+-------
1 | user1
2 | user2
3 | user3
4 | user4
5 | user5
(5 rows)
create or replace function del_t1(int) returns void as $$
declare
a alias for $1;
begin
delete from t1 where id = a;
return;
end;
$$language plpgsql;
create or replace function del_cur(ref refcursor) returns void as $$
declare
a int;
begin
open ref scroll for select id from t1 where id > 3 order by id desc;
fetch first from ref into a;
perform del_t1(a);
loop
a := 0;
fetch next from ref into a;
perform del_t1(a);
if (a=0) then
exit;
end if;
end loop;
end;
$$ language plpgsql;
when the function is executed,
postgres# select del_cur('t1');
it shows no error, no outputs, cursor just blinks, plz help me to solve this, this is small description of my big database tables, i need a cursor function which will pass its values one by one to another function.
In your example the function del_cur(refcursor) is declared to take a cursor. But you never actually use it inside the function - the construct makes no sense at all.
What you are trying to do should be much easier with the implicit cursor of a FOR loop:
CREATE OR REPLACE FUNCTION del_stuff()
RETURNS void AS
$BODY$
DECLARE
_a int;
BEGIN
FOR _a IN
SELECT id FROM t1 WHERE id > 3 ORDER BY id DESC
LOOP
DELETE FROM t1 WHERE id = _a;
-- do other stuff?
END LOOP;
END;
$BODY$ LANGUAGE plpgsql;
I don't understand the need to delete the rows one by one in descending order. Are triggers involved? Maybe the whole thing can be as simple as:
DELETE FROM t1 WHERE id > 3;

PostgreSQL simple trigger question

trigger:
CREATE TRIGGER "tr_update_ts" BEFORE INSERT OR UPDATE
ON "public"."test" FOR EACH ROW
EXECUTE PROCEDURE "public"."update_ts"();
and the function is:
CREATE OR REPLACE FUNCTION "public"."update_ts" () RETURNS trigger AS
$body$
DECLARE
BEGIN
NEW.ts := now();
RETURN NEW;
END;
$body$
LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER;
Why is this not working? No error thrown, but the ts is still null...
I tested your code and it works:
First, let's create table:
# create table test (x int4, ts timestamptz);
CREATE TABLE
Now, Let's add function:
# CREATE OR REPLACE FUNCTION "public"."update_ts" () RETURNS trigger AS
>> $body$
>> DECLARE
>> BEGIN
>> NEW.ts := now();
>> RETURN NEW;
>> END;
>> $body$
>> LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER;
CREATE FUNCTION
And finally, add a trigger:
# CREATE TRIGGER "tr_update_ts" BEFORE INSERT OR UPDATE
>> ON "public"."test" FOR EACH ROW
>> EXECUTE PROCEDURE "public"."update_ts"();
CREATE TRIGGER
So, now, let's test ON INSERT part of it:
# insert into test (x) values (1);
INSERT 0 1
# select * from test;
x | ts
---+-------------------------------
1 | 2009-09-12 19:54:50.812139+02
(1 row)
Clearly it works.
Now, the update:
# update test set x = 2;
UPDATE 1
# select * from test;
x | ts
---+-------------------------------
2 | 2009-09-12 19:54:57.463933+02
(1 row)
ts has been changed. Clearly the code you shown works, so the error must be someplace else.
Show us "\d test" output from psql, and \df+ of the trigger function.
What is the full syntax of your create function? Here is the full syntax of the function that I created, and it is working as expected.
create function update_timestamp() RETURNS trigger AS $$
BEGIN
NEW.ts := now();
RETURN NEW;
END;
$$ language plpgsql;