You don't really need a function for that. With a variation of this answer this can be done with a single statement:
First we need to find all columns that have use a sequence as a default value:
select table_schema, table_name, column_name,
pg_get_serial_sequence(format('%I.%I', table_schema, table_name), column_name)
from information_schema.columns
where table_schema = 'public'
and column_default like 'nextval%'
Then we can calculate the max value for each of those columns using query_to_xml()
and use that result to call setval()
for each sequence.
with sequences as (
select table_schema, table_name, column_name,
pg_get_serial_sequence(format('%I.%I', table_schema, table_name), column_name) as col_sequence
from information_schema.columns
where table_schema = 'public' --<< adjust for your schemas
and column_default like 'nextval%'
), maxvals as (
select table_schema, table_name, column_name, col_sequence,
(xpath('/row/max/text()',
query_to_xml(format('select coalesce(max(%I),0) from %I.%I', column_name, table_schema, table_name), true, true, ''))
)[1]::text::bigint as max_val
from sequences
where col_sequence is not null
)
select table_schema,
table_name,
column_name,
col_sequence,
max_val,
setval(col_sequence, max_val)
from maxvals;