How to select into multiple variables inside a trigger function? - postgresql

This is what I'd like to achieve:
CREATE FUNCTION f() RETURNS trigger AS $$
BEGIN
SELECT COUNT(*) AS total_num, SUM(width) AS total_width
FROM some_table WHERE foo = NEW.foo;
IF total_num > 0 AND total_width > 100
THEN
RAISE EXCEPTION 'this is bad';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
But it's not yet syntactically correct.
I've read I first need to DECLARE the variables (in this case total_num and total_width) so I can use those and use SELECT INTO but I've seen examples with a single variable / SELECT statement only. What if I have more of them?

You can list multiple variables in the into part. And the declare section needs to come before the first begin:
CREATE FUNCTION f() RETURNS trigger
AS $$
declare
total_num bigint;
total_width bigint;
BEGIN
SELECT COUNT(*), SUM(width)
into total_num, total_width
FROM some_table
WHERE foo = NEW.foo;
IF total_num > 0 AND total_width > 100 THEN
RAISE EXCEPTION 'this is bad';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;

Edit: I'm not sure whether the emphasis here is on the use of variables or the actual IF. This is meant as an answer on the latter:
You can do this without variables using HAVING and EXISTS.
IF EXISTS (SELECT ''
FROM some_table
WHERE foo = new.foo
HAVING count(*) > 0
AND sum(width) > 100) THEN
RAISE EXCEPTION 'this is bad';
END IF;

Related

PostgreSQL subquery with IF EXISTS in trigger function

I have a PostgreSQL trigger function like so:
CREATE FUNCTION playlists_tld_update_trigger() RETURNS TRIGGER AS
$$
BEGIN
IF EXISTS (SELECT 1 FROM "subjects" WHERE "subjects"."id" = new.subject_id) THEN
new.tld = (SELECT "subjects"."tld" FROM "subjects" WHERE "subjects"."id" = new.subject_id LIMIT 1);
END IF;
RETURN new;
END
$$
LANGUAGE plpgsql;
The trigger function will set the playlist's "tld" column to match the subject's "tld" column, but only if there exists a subject referenced by the subject_id foreign key. How do I use a subquery to combine the 2 queries into 1, or to avoid redundancy?
CREATE FUNCTION playlists_tld_update_trigger()
RETURNS TRIGGER
AS $$
DECLARE
my_tld <data_type_of_tld>;
BEGIN
SELECT subjects.tld
INTO my_tld
FROM subjects
WHERE subjects.id = new.subject_id
LIMIT 1
;
IF FOUND
THEN
new.tld = my_tld;
RETURN NEW;
ELSE
-- do something else
RETURN OLD;
END IF;
END
$$ LANGUAGE plpgsql;

Assigning query output to variable in postgres stored proc

I am trying to assign a variable the result of a query in a postgres stored procedure.
Here is what I am trying to run:
CREATE OR Replace PROCEDURE schema.MyProcedure()
AS $$
DECLARE
RowCount int = 100;
BEGIN
select cnt into RowCount
from (
Select count(*) as cnt
From schema.MyTable
) ;
RAISE NOTICE 'RowCount: %', RowCount;
END;
$$
LANGUAGE plpgsql;
schema.MyTable is just some arbitrary table name but the script is not displaying anything, not even the random value I assigned RowCount to (100).
What am I doing wrong?
Thanks
You need an alias for the subquery, for example : as sub
CREATE OR Replace PROCEDURE schema.MyProcedure()
AS $$
DECLARE
RowCount int = 100;
BEGIN
select cnt into RowCount
from (
Select count(*) as cnt
From schema.MyTable
) as sub ;
RAISE NOTICE 'RowCount: %', RowCount;
END;
$$
LANGUAGE plpgsql;
You can also assign any variable with a query result in parenthesis.
CREATE OR REPLACE PROCEDURE schema.my_procedure()
AS
$$
DECLARE
row_count BIGINT;
BEGIN
row_count = (SELECT COUNT(*) FROM schema.my_table);
RAISE NOTICE 'RowCount: %', row_count;
END;
$$ LANGUAGE plpgsql;
You should use BIGINT instead of INT.
And it's far better to write your code and table definition with snake_case style as possible.

Example use of ASSERT with PostgreSQL

After reading the documentation for ASSERT, I am still confused how to use it, and can't find any examples online of how I would do something simple using ASSERT in a .sql script.
For example, say I want to ASSERT that the number of rows returned from SELECT * FROM my_table WHERE my_col = 3 is equal to 10.
Can someone provide a working example of that?
I would assume you try todo smth similar?
so=# select count(*) from pg_database;
count
-------
21
(1 row)
so=# do $$ begin assert (select count(*) from pg_database) = 21, 'not 21!';end;$$;
DO
so=# do $$ begin assert (select count(*) from pg_database) = 22, 'not 22!';end;$$;
ERROR: not 22!
CONTEXT: PL/pgSQL function inline_code_block line 1 at ASSERT
do $$
begin
ASSERT 1 = 2;
end;
$$ LANGUAGE plpgsql;
But note, it works only starting from PostgreSql 9.5. In older versions you can define your own assert-function such like this
CREATE OR REPLACE FUNCTION __assert(boolean) RETURNS VOID AS $$
BEGIN
IF NOT $1 THEN
RAISE EXCEPTION 'ASSERTING FAILED';
END IF;
END;
$$ LANGUAGE plpgsql;
And then use in this way
do $$
declare
tmp char;
begin
tmp := __assert(tmp_to_https('https') = 'https');
end;
$$ LANGUAGE plpgsql;

How to use the ELSIF statement in Postgres

I'm wondering if I can run the if statement by itself, or it can't stand on its own, has to be in a nested statement. I can't directly run the following code.
IF tax_year=2005 THEN
UPDATE table1 SET column1=column1*3;
ELSIF tax_year=2006 THEN
UPDATE table1 SET column1=column1*5;
ELSIF tax_year=2007 THEN
UPDATE table1 SET column1=column1*7;
END IF;
Also, I didn't write it out that when tax_year=2008, column1=column1. I'm not sure if it needs to be in the code since column1 won't change in 2008.
Thanks for your help!
IF / ELSIF / ELSE is part of PL/pgsql, which is an extension of pg, and it's enabled for new database by default.
You can create a function to wrap the IF statements. And call the function to execute these statements.
e.g
-- create function,
CREATE OR REPLACE FUNCTION fun_dummy_tmp(id_start integer, id_end integer) RETURNS setof dummy AS $$
DECLARE
BEGIN
IF id_start <= 0 THEN
id_start = 1;
END IF;
IF id_end < id_start THEN
id_end = id_start;
END IF;
return query execute 'select * from dummy where id between $1 and $2' using id_start,id_end;
return;
END;
$$ LANGUAGE plpgsql;
-- call function,
select * from fun_dummy_tmp(1, 4);
-- drop function,
DROP FUNCTION IF EXISTS fun_dummy_tmp(integer, integer);
And, there is a CASE statement, which might be a better choice for your requirement.
e.g
-- create function,
CREATE OR REPLACE FUNCTION fun_dummy_tmp(id integer) RETURNS varchar AS $$
DECLARE
msg varchar;
BEGIN
CASE id%2
WHEN 0 THEN
msg := 'even';
WHEN 1 THEN
msg := 'odd';
ELSE
msg := 'impossible';
END CASE;
return msg;
END;
$$ LANGUAGE plpgsql;
-- call function,
select * from fun_dummy_tmp(6);
-- drop function,
DROP FUNCTION IF EXISTS fun_dummy_tmp(integer);
You can refer to postgresql document for control statement for the details.
I did it with the following code:
-- UPDATE houston_real_acct_1single1property
-- SET convert_market_value=
-- CASE
-- WHEN tax_year=2005 THEN total_market_value*1.21320615034169
-- WHEN tax_year=2006 THEN total_market_value*1.17961794019934
-- WHEN tax_year=2007 THEN total_market_value*1.15884093604151
-- WHEN tax_year=2008 THEN total_market_value*1.12145267335906
-- WHEN tax_year=2009 THEN total_market_value*1.11834431349904
-- WHEN tax_year=2010 THEN total_market_value*1.0971664297633
-- WHEN tax_year=2011 THEN total_market_value*1.06256515125065
-- WHEN tax_year=2012 THEN total_market_value*1.04321957955664
-- WHEN tax_year=2013 THEN total_market_value*1.02632796014915
-- WHEN tax_year=2014 THEN total_market_value*0.998472101797389
-- WHEN tax_year=2015 THEN total_market_value
-- 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;