# Return all sequences from a database together with their max value
WITH sequences AS (
    SELECT
        seq.relname AS sequence_name,
        table_.relname AS table_name,
        attribute.attname AS column_name,
        pg_sequence_last_value(sequence_data.seqrelid) AS last_value,
        sequence_data.seqincrement,
        least(
            sequence_data.seqmax,
            CASE attribute.atttypid
                WHEN 'int4'::regtype THEN 2147483647::bigint
                WHEN 'int8'::regtype THEN 9223372036854775807::bigint
            END) AS max_value
    FROM pg_sequence AS sequence_data
    JOIN pg_class AS seq ON seq.oid = sequence_data.seqrelid
    JOIN pg_depend AS dependency
      ON dependency.objid = sequence_data.seqrelid
     AND dependency.classid = 'pg_class'::regclass
     AND dependency.refclassid = 'pg_class'::regclass
     AND dependency.deptype IN ('a', 'i')
    JOIN pg_class AS table_ ON table_.oid = dependency.refobjid
    JOIN pg_attribute AS attribute
      ON attribute.attrelid = table_.oid
     AND attribute.attnum = dependency.refobjsubid
    WHERE table_.relnamespace = 'public'::regnamespace
      AND table_.relkind IN ('r', 'p')
      AND attribute.atttypid IN ('int4'::regtype, 'int8'::regtype)
      AND sequence_data.seqincrement > 0
      AND NOT sequence_data.seqcycle
),
next_values AS (
    SELECT
        sequence_name,
        table_name,
        column_name,
        CASE
            WHEN last_value IS NULL THEN NULL
            ELSE last_value::numeric + seqincrement::numeric
        END AS next_value,
        max_value
    FROM sequences
)
SELECT sequence_name, table_name, column_name, next_value, max_value
FROM next_values
WHERE next_value IS NOT NULL
