|
| 1 | +/* |
| 2 | + * Copyright (c) 2019-2024. Ivan Vakhrushev and others. |
| 3 | + * https://github.com/mfvanek/pg-index-health-sql |
| 4 | + * |
| 5 | + * Licensed under the Apache License 2.0 |
| 6 | + */ |
| 7 | + |
| 8 | +-- Finds primary keys columns with serial type (smallserial/serial/bigserial) |
| 9 | +-- Instead of old smallserial/serial/bigserial new "generated as identity" syntax should be used |
| 10 | +-- for defining primary keys |
| 11 | +-- Based on https://dba.stackexchange.com/questions/90555/postgresql-select-primary-key-as-serial-or-bigserial/ |
| 12 | +-- See also https://wiki.postgresql.org/wiki/Don't_Do_This#Don.27t_use_serial |
| 13 | +-- and https://stackoverflow.com/questions/55300370/postgresql-serial-vs-identity |
| 14 | +select |
| 15 | + col.attrelid::regclass as table_name, |
| 16 | + col.attname as column_name, |
| 17 | + col.attnotnull as column_not_null, |
| 18 | + case col.atttypid |
| 19 | + when 'int'::regtype then 'serial' |
| 20 | + when 'int8'::regtype then 'bigserial' |
| 21 | + when 'int2'::regtype then 'smallserial' end as column_type, |
| 22 | + pg_get_serial_sequence(col.attrelid::regclass::text, col.attname) as sequence_name |
| 23 | +from pg_catalog.pg_class t |
| 24 | + join pg_catalog.pg_namespace nsp on nsp.oid = t.relnamespace |
| 25 | + join pg_catalog.pg_attribute col on col.attrelid = t.oid |
| 26 | + join pg_catalog.pg_attrdef ad on ad.adrelid = col.attrelid and ad.adnum = col.attnum |
| 27 | + join pg_catalog.pg_constraint c on c.conrelid = col.attrelid and col.attnum = any(c.conkey) |
| 28 | +where col.atttypid = any('{int,int8,int2}'::regtype[]) |
| 29 | + and not col.attisdropped |
| 30 | + and c.contype = 'p' -- primary keys |
| 31 | + and pg_get_expr(ad.adbin, ad.adrelid) = 'nextval(''' || pg_get_serial_sequence(col.attrelid::regclass::text, col.attname)::regclass || '''::regclass)' |
| 32 | + and nsp.nspname = :schema_name_param::text; |
0 commit comments