I have a small piece of code to get all sequences and the current and maximum value of all sequences in a database. I have tried with recursive
and some other alternatives through plain sqls, however I couldn't find it. So I decided to use the dynamic sql as below:
do
language plpgsql
$$
declare qy text;
rs record;
begin
for qy in select
'select current_database(), iss.sequence_schema || ''.'' || ind.sequence_name,
concat(''Cur'', ind.lvalue,'',Max:'',iss.maximum_value) from
(select sequence_name, last_value lvalue from ' || quote_ident(sequence_schema) || '.' || quote_ident(sequence_name) || ') as ind,
information_schema.sequences iss where iss.sequence_name = ind.sequence_name and iss.sequence_schema = ''' || sequence_schema || '''' from information_schema.sequences
loop
execute qy into rs;
raise notice '%', rs;
end loop;
end
$$;
It works well in pgAdmin however, its not working in psql
as expected. I do have two questions here:
Can I return the
res
values as result in dynamic sql? (I could if I do these operation via a function but I will not be having create / execute function privilege in the database since I will be using a guest user)Why the
RAISE NOTICE
orRAISE DEBUG
not showing anything in the console (usingpsql
) even if I set theclient_min_messages
todebug
ornotice
? I querying a rds instance. Is it something to deal with rds functionality?
Bottom of the line, I need to get all sequence's current value and max value along with schema name. It would be great if anyone shares an another way to achieve this without increasing the sequence value.
(I am using postgres 9.6)
psql
likeSELECT format($$SELECT * FROM %I $$, c.oid::regclass) FROM pg_class AS c WHERE relkind = 'S';
and then running\gexec
. As for the NOTICE, I don't know, it works as expected locally, and I am not in the position to set up an Aurora cluster to check this.SELECT format($$SELECT '%I' schemaname, '%I' sequencename, concat(last_value, ',', trim('%I','"')) FROM "%I"."%I" union $$, n.nspname, c.relname, s.maximum_value, n.nspname, c.relname) FROM pg_class c, information_schema.sequences s, pg_namespace n WHERE relkind = 'S' and s.sequence_name = c.relname and n.oid = c.relnamespace and s.sequence_schema = n.nspname
I could save this as in plain.sql
file and remove theunion
from last line and execute it. Is there any other feasible way I'm missing here?