Trigger doesn't work and doesn't show any errors - postgresql

I'm trying to create a trigger that will shorten the name and the middle name to initials.
That's what i have:
CREATE OR REPLACE FUNCTION myfunc() RETURNS TRIGGER AS $$
DECLARE nm VARCHAR(50);
DECLARE mdnm VARCHAR(50);
BEGIN
nm = LEFT(NEW.name, 1);
mdnm = LEFT(NEW.middle_name, 1);
SET NEW.name = nm;
SET NEW.middle_name = mdnm;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER table_before_insert BEFORE INSERT OR UPDATE ON table1
FOR EACH ROW EXECUTE PROCEDURE myfunc();
But for some reasons it doesn't work, what can it be?

As documented in the manual variables are assigned with := or =. But not with the SET command - which changes configuration properties. You also don't need a separate DECLARE block for each variable:
So your trigger function should look like this:
CREATE OR REPLACE FUNCTION myfunc() RETURNS TRIGGER AS $$
DECLARE
nm VARCHAR(50);
mdnm VARCHAR(50);
BEGIN
nm := LEFT(NEW.name, 1);
mdnm := LEFT(NEW.middle_name, 1);
NEW.name := nm;
NEW.middle_name := mdnm;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
You don't even need the variables:
CREATE OR REPLACE FUNCTION myfunc() RETURNS TRIGGER AS $$
BEGIN
NEW.name := LEFT(NEW.name, 1);
NEW.middle_name := LEFT(NEW.middle_name, 1);
RETURN NEW;
END;
$$ LANGUAGE plpgsql;

Related

How to initialize row datatype variables?

I would like to create a function that initialize and return the row datatype of a table as
CREATE FUNCTION get_default_table_row_object()
RETURNS mytable AS $$
DECLARE
row mytable;
BEGIN
row.field1 := 0;
row.field2 := -1;
row.record_reg_id := 1;
row.record_upd_id := 1;
row.record_reg_date := current_timestamp;
row.record_upd_date := current_timestamp;
RETURN row;
END;
$$ LANGUAGE plpgsql;
becuase my table has alot of columns and I need to create dozens of variables at several functions. I would like to use above function as
CREATE FUNCTION some_function() RETURNS VOID AS $$
DECLARE
i_obj1 mytable := get_default_table_row_object(); -- declare and initialize default values
BEGIN
-- function body
END;
$$ LANGUAGE plpgsql;
But this give me the error ERROR: default value for row or record variable is not supported. Has someway to figure it out ?
You can set it in the body instead, like so:
CREATE FUNCTION some_function() RETURNS VOID AS $$
DECLARE
i_obj1 mytable; -- declare only
BEGIN
i_obj1 := get_default_table_row_object(); -- set default values
END;
$$ LANGUAGE plpgsql;

How postgresql return a data set like the follows?

Just like the below function. I don't know how to return a set of inside parameter in postgresql?
create or replace function g_i(num int)
returns setof integer
as $$
declare
i int;
begin
while i < $1 loop
select i; -- How to write statements here?
end loop;
end;
$$ language plpgsql;
create or replace function g_i(num int)
returns setof integer
as $$
declare
i int;
begin
i := 0;
while i< $1 loop
i := i+1;
return query select i;
end loop;
end;
$$ language plpgsql;

PL/pgSQL syntax error

I have a very simple PL/pgSQL script:
declare x varchar(100);
When I run it I get a message:
[WARNING ] declare x varchar(100)
ERROR: syntax error at or near "varchar"
LINE 1: declare x varchar(100)
^
I really don't understand what is wrong with this.
you can use procedural statements only inside function body in PostgreSQL.
CREATE OR REPLACE FUNCTION foo()
RETURNS int AS
$$ -- here start procedural part
DECLARE x int;
BEGIN
x := 10;
RETURN x;
END;
$$ -- here finish procedural part
LANGUAGE plpgsql; -- language specification
or in temporary function (anonymous block)
DO $$
DECLARE x int;
BEGIN
x := 10;
RAISE NOTICE '>>>%<<<', x;
END;
$$;
isn't possible to use procedural statements as SQL statements like T-SQL.
Use exemple
DO $$
Declare
test varchar;
begin
test := 'teste';
if (char_length(test) > 0) then
RAISE NOTICE '>>>%<<<', test;
end if;
end;
$$;
I have resolved this by the following piece of code:
do $$
declare TypeId int;
declare MasterId int;
begin
TypeId := null;
MasterId := null;
end;
$$;

Iterating over integer[] in plpgsql

How can I iterate over integer[] if I have:
operators_ids = string_to_array(operators_ids_g,',')::integer[];
I want iterate over operators_ids.
I can't do it in this way:
FOR oid IN operators_ids LOOP
and this:
FOR oid IN SELECT operators_ids LOOP
oid is integer;
You can iterate over an array like
DO
$body$
DECLARE your_array integer[] := '{1, 2, 3}'::integer[];
BEGIN
FOR i IN array_lower(your_array, 1) .. array_upper(your_array, 1)
LOOP
-- do something with your value
raise notice '%', your_array[i];
END LOOP;
END;
$body$
LANGUAGE plpgsql;
But the main question in my view is: why do you need to do this? There are chances you can solve your problem in better ways, for example:
DO
$body$
DECLARE i record;
BEGIN
FOR i IN (SELECT operators_id FROM your_table)
LOOP
-- do something with your value
raise notice '%', i.operators_id;
END LOOP;
END;
$body$
LANGUAGE plpgsql;
I think Dezso is right. You do not need to use looping the array using an index.
If you make a select statement grouping by person_id in combination with limit 1, you have the result set you wanted:
create or replace function statement_example(p_data text[]) returns int as $$
declare
rw event_log%rowtype;
begin
for rw in select * from "PRD".events_log where (event_type_id = 100 or event_type_id = 101) and person_id = any(operators_id::int[]) and plc_time < begin_date_g order by plc_time desc group by person_id limit 1 loop
raise notice 'interesting log: %', rw.field;
end loop;
return 1;
end;
$$ language plpgsql volatile;
That should perform much better.
If you still prefer looping an integer array and there are a lot of person_ids to look after, then might you consider using the flyweight design pattern:
create or replace function flyweight_example(p_data text[]) returns int as $$
declare
i_id int;
i_min int;
i_max int;
begin
i_min := array_lower(p_data,1);
i_max := array_upper(p_data,1);
for i_id in i_min .. i_max loop
raise notice 'interesting log: %',p_data[i_id];
end loop;
return 1;
end;
$$ language plpgsql volatile;

Postgresql before update/insert trigger doesn't appear to work

I have the following trigger function:
CREATE OR REPLACE FUNCTION update_modelname_function()
RETURNS trigger AS
$BODY$
BEGIN
IF tg_op = 'INSERT' THEN
new.model_name := upper(new.model_name);
RETURN new;
END IF;
IF tg_op = 'UPDATE' THEN
old.model_name := upper(old.model_name);
RETURN new;
END IF;
END
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
What I'm trying to achieve is for the value of the column model_name to always be uppercased when it's persisted in the table. However nothing seems to happen. Any ideas?
You accidentally updated OLD instead of NEW. Try:
CREATE OR REPLACE FUNCTION update_modelname_function()
RETURNS trigger
LANGUAGE plpgsql AS
$func$
BEGIN
IF TG_OP = 'INSERT' THEN
NEW.model_name := upper(NEW.model_name);
RETURN NEW;
ELSIF TG_OP = 'UPDATE' THEN
NEW.model_name := upper(NEW.model_name); -- !
RETURN NEW;
END IF;
END
$func$;
If the example shows the whole code, and the actual trigger(s) only fires on INSERT and/or UPDATE, further simplify:
CREATE OR REPLACE FUNCTION update_modelname_function()
RETURNS trigger
LANGUAGE plpgsql AS
$func$
BEGIN
NEW.model_name := upper(NEW.model_name);
RETURN NEW;
END
$func$;