postgresqlamazon-aurorapostgresql-12

Increment all sequences in Postgresql DB


I migrating a PostgreSQL DB using AWS DMS. The source DB is on Aurora Postgres 10.xx and the target DB is on Aurora Postgres 12.xx.

Since DMS does not sync sequences, so I am using the following query (on the target DB) to create Dynamic sql queries which will increment my sequences by max_value of the associated column + 1000:

SELECT 
    'SELECT SETVAL(' ||
       quote_literal(quote_ident(sequence_namespace.nspname) || '.' || quote_ident(class_sequence.relname)) ||
       ', COALESCE(MAX(' ||quote_ident(pg_attribute.attname)|| '), 1)+ 1000 ) FROM ' || -- Buffer of 1000
       quote_ident(table_namespace.nspname)|| '.'||quote_ident(class_table.relname)|| ';'
FROM pg_depend 
    INNER JOIN pg_class AS class_sequence
        ON class_sequence.oid = pg_depend.objid 
            AND class_sequence.relkind = 'S'
    INNER JOIN pg_class AS class_table
        ON class_table.oid = pg_depend.refobjid
    INNER JOIN pg_attribute 
        ON pg_attribute.attrelid = class_table.oid
            AND pg_depend.refobjsubid = pg_attribute.attnum
    INNER JOIN pg_namespace as table_namespace
        ON table_namespace.oid = class_table.relnamespace
    INNER JOIN pg_namespace AS sequence_namespace
        ON sequence_namespace.oid = class_sequence.relnamespace
    where sequence_namespace.nspname='public' -- This is the schema name
ORDER BY sequence_namespace.nspname, class_sequence.relname;

This returns a total of 15 SQL statements which means 15 sequences in total in the public schema.

Now when I do a \ds public.* on the same database, it gives me 25 sequences. I am not able to figure out why the SELECT query is not able to pick up all the 25 sequences.

Can someone please help here?

Thanks


Solution

  • Your query only returns sequences that are owned by a table column:

    ALTER SEQUENCE seq OWNED BY tab.id;
    

    The other sequences seem not to have such a relationship to a table column.