Getting syntax error when running a simple perform - database

Why am I getting a syntax error on this simple perform call
create or replace function foo ()
returns void
as $$
begin
end;
$$ language 'plpgsql';
perform * from foo ();
I tested it online at ExtendsClass

PERFORM is a PL/pgSQL statement, not a SQL one. This means it can only be used between the BEGIN and END of a function definition. See below, where I call bar() from foo() using PERFORM.
create or replace function bar ()
returns void
as $$
begin
RAISE NOTICE 'bar() ran';
end;
$$ language 'plpgsql';
create or replace function foo ()
returns void
as $$
begin
perform bar();
end;
$$ language 'plpgsql';
The SQL fiddle site you've linked doesn't show stderr, but if you paste the above into psql and then select * from foo();, you'll see that bar() ran.
testdb=# select * from foo();
NOTICE: bar() ran
foo
-----
(1 row)

Related

My function with array as parameter does not work

I proceed to specify my question and the solution I gave to the problem, for the benefit of the community.
I was trying to perform a multi-column insert using the identifier with a function.
For which, I was getting an error, my code was the following:
CREATE OR REPLACE FUNCTION acc.asignar_periodo(ids NUMERIC[], periodo INTEGER,codigo_subdiario VARCHAR)
RETURNS void
VOLATILE
AS
$$
DECLARE
cant_registros integer:= 0;
BEGIN
cant_registros := array_length(ids,1);
FOR i IN 1..cant_registros LOOP
EXECUTE'UPDATE '||$3||' SET periodo_tributario = $2 WHERE id = ids[i]';
END LOOP;
END;
$$ LANGUAGE plpgsql;
and my query is:
SELECT acc.asignar_periodo('{2291,2292,2293,2294,2295,2296,2297,2298,2299,2300,2301,2302}'::NUMERIC[],201612,'_08');
My solution was the following:
CREATE OR REPLACE FUNCTION acc.asignar_periodo(INTEGER[],INTEGER,INTEGER) RETURNS text VOLATILE AS
$$
DECLARE
qty integer:= array_length($1,1);
respuesta varchar := null;
BEGIN
FOR i IN 1..qty LOOP
EXECUTE'UPDATE _'||$3||' SET periodo_tributario = '||$2||' WHERE id = '||$1[i];
END LOOP;
respuesta := 'Periodo '||$2||' asignado a '||qty||' comprobantes del subdiario '||$3;
RETURN respuesta;
END;
$$ LANGUAGE plpgsql;
Note the correction, since when using EXECUTE it is necessary that the arguments escape the statements
There is no to loop needed to process the array. Postgres will process the entry array at once. After all set processing is what SQL is all about. Get into the mindset that whenever you write loop, likely incorrect and much slower. (Yes there occasions where it is necessary, but very few.) So: (see demo)
create or replace function asignar_periodo(ids numeric[], periodo integer,codigo_subdiario varchar)
returns void
language plpgsql
as $$
declare
stmt constant text = 'update %I set periodo_tributario = %s where id = any (''%s'')';
torun text;
begin
--torun = format(stmt, $3, $2, $1); -- this would work but
torun = format(stmt, codigo_subdiario, periodo, ids); -- I perfer parameter names to position reference
raise notice '%', torun;
execute torun;
end ;
$$;

How to CAST empty array value of an ANYARRAY-function to ANYARRAY?

I am using pgv10. The function that I need seems this wrong function:
CREATE FUNCTION array_coalesce(ANYARRAY) RETURNS ANYARRAY AS $f$
SELECT CASE WHEN $1 IS NULL THEN array[]::ANYARRAY ELSE $1 END;
$f$ language SQL IMMUTABLE;
Curiosity
... I started to simplify a complex problem, and arrives in the test select coalesce(null::text[], array[]::text[]) that not worked... So it was a good question, how to implement it? But sorry, I do something workng, COALESCE(array,array) is working fine (phew!).
So, "coalesce problem" is merely illustrative/didatic. What I really want to understand here is: How to use ANYARRAY?
PS: other curiosity, the string concat(), || and other concatenation operators in PostgreSQL do some "coalescing",
select concat(NULL::text, 'Hello', NULL::text); -- 'Hello'
select null::text[] || array[]::text[]; -- []
select array[]::text[] || null::text[]; -- []
How to use anyarray?
It's an interesting issue, in the context of the usage described in the question. The only way I know is to use an argument as a variable. It's possible in plpgsql (not in plain sql) function:
create or replace function array_coalesce(anyarray)
returns anyarray as $f$
begin
if $1 is null then
select '{}' into $1;
end if;
return $1;
end
$f$ language plpgsql immutable;
select array_coalesce(null::int[]);
array_coalesce
----------------
{}
(1 row)
By the way, you can simply use coalesce() for arrays:
select coalesce(null::text[], '{}'::text[]);
coalesce
----------
{}
(1 row)

Mocking postgresql with a stored procedure

I've been going through the test files of https://github.com/DATA-DOG/go-sqlmock to figure out how to create a stored procedure for mocking purposes. I have:
_, err = db.Exec(`
CREATE OR REPLACE FUNCTION val() RETURNS INT AS
$$ SELECT 1; $$
LANGUAGE sql;
`)
if err != nil {
t.Fatal(err)
}
I get:
all expectations were already fulfilled, call to exec 'CREATE OR REPLACE FUNCTION val() RETURNS INT AS $$ SELECT 1; $$ LANGUAGE sql;' query with args [] was not expected
If, instead, I try it with
mock.ExpectExec(`
CREATE OR REPLACE FUNCTION val() RETURNS INT AS
$$ SELECT 1; $$
LANGUAGE sql;
`,
).WillReturnResult(sqlmock.NewResult(0, 0))
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatal(err)
}
I get:
there is a remaining expectation which was not matched: ExpectedExec => expecting Exec which:
- matches sql: 'CREATE OR REPLACE FUNCTION val() RETURNS INT AS $$ SELECT 1; $$ LANGUAGE sql;'
- is without arguments
- should return Result having:
LastInsertId: 0
RowsAffected: 0
I am really confused on how to setup a basic stored procedure.
The sqlmock library works pretty well for this.
But please note that the ExpectExec receives a regular expression in order to match:
// ExpectExec expects Exec() to be called with sql query
// which match sqlRegexStr given regexp.
// the *ExpectedExec allows to mock database response
ExpectExec(sqlRegexStr string) *ExpectedExec
You are sending that function the exact string you expect to receive without any escaping.
To escape the string, add this:
import (
"regexp"
)
And then when adding the expectation, escape your string (note the regexp.QuoteMeta):
mock.ExpectExec(regexp.QuoteMeta(`
CREATE OR REPLACE FUNCTION val() RETURNS INT AS
$$
SELECT 1;
$$
LANGUAGE sql;
`),
).WillReturnResult(sqlmock.NewResult(0, 0))
That way, the escaped regexp will match your exec command.

PL/pgSQL "Malformed array literal" error within for loop

I have the following pl/pgsql function. (Obviously, this is not the full function, it's just the minimal amount of code needed to reproduce the problem)
CREATE OR REPLACE FUNCTION test_func(infos TEXT[][])
RETURNS void AS
$$
DECLARE
info TEXT[];
type TEXT[];
name TEXT;
BEGIN
FOREACH info SLICE 1 IN ARRAY infos LOOP
RAISE NOTICE 'Stuff: %', info;
type := info[1];
name := info[2];
RAISE NOTICE 'Done with stuff';
END LOOP;
RETURN;
END;
$$ LANGUAGE plpgsql;
When I run the function using SELECT test_func('{{something, things},{other, data}}'::TEXT[][]);, I get the following output:
NOTICE: Stuff: {something,things}
ERROR: malformed array literal: "something"
DETAIL: Array value must start with "{" or dimension information.
CONTEXT: PL/pgSQL function test_func(text[]) line 10 at assignment
I don't understand how this error is happening. When the value of info is printed, it shows {something,things}, which seems to me to be a proper array literal.
I am using PostgreSQL version 9.4.7, in case it matters.
The variable type should be text (not text[]):
CREATE OR REPLACE FUNCTION test_func(infos TEXT[][])
RETURNS void AS
$$
DECLARE
info TEXT[];
type TEXT;
name TEXT;
...

Returning array via INOUT parameter without modifications

I'm using PostgreSQL 9.1.3 and the following functions:
CREATE OR REPLACE FUNCTION cad(INOUT args text[], OUT retval int4) AS $cad$
BEGIN
retval := 0;
RAISE NOTICE 'cad: %', args;
END;
$cad$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION dodo(in_args text[]) RETURNS text[] AS $dodo$
DECLARE
_res text[];
_rv int4;
BEGIN
_res := in_args;
EXECUTE 'SELECT cad($1)' USING _res INTO _res, _rv;
RETURN _res;
END;
$dodo$ LANGUAGE plpgsql;
When I call cad directly, I get expected output:
psql$ select cad(ARRAY['Quiz']);
NOTICE: cad: {Quiz}
-[ RECORD 1 ]---
cad | ({Quiz},0)
Time: 0,319 ms
My expected result for the dodo(ARRAY['Quiz']) call is the input array without changes. But instead I receive the following error:
psql$ select dodo(ARRAY['Quiz']);
NOTICE: cad: {Quiz}CONTEXT: SQL statement "SELECT cad($1)"
PL/pgSQL function "dodo" line 8 at EXECUTE statement
ERROR: array value must start with "{" or dimension information
CONTEXT: PL/pgSQL function "dodo" line 8 at EXECUTE statement
What is wrong here?
P.S.: I have to use EXECUTE as function to call will vary, code simplified for the purpose of question.
You want something like:
EXECUTE 'SELECT * FROM cad($1)' USING _res INTO _res, _rv;
The return type isn't two columns of text[],int it's a record of (text[],int) which needs unwrapping.

Resources