Skip to content

Add check "Don't use varchar(n) by default" #89

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ For more information please see [PostgreSQL Versioning Policy](https://www.postg
27. Objects whose names do not follow naming convention ([sql](https://github.com/mfvanek/pg-index-health-sql/blob/master/sql/objects_not_following_naming_convention.sql)).
28. Columns whose names do not follow naming convention ([sql](https://github.com/mfvanek/pg-index-health-sql/blob/master/sql/columns_not_following_naming_convention.sql)).
29. Primary keys with varchar columns instead of uuids ([sql](https://github.com/mfvanek/pg-index-health-sql/blob/master/sql/primary_keys_with_varchar.sql)).
30. Columns with [varchar(n)](https://www.postgresql.org/docs/current/datatype-character.html) type ([sql](https://github.com/mfvanek/pg-index-health-sql/blob/master/sql/columns_with_fixed_length_varchar.sql)).

## Local development

Expand Down
27 changes: 27 additions & 0 deletions sql/columns_with_fixed_length_varchar.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* Copyright (c) 2019-2025. Ivan Vakhrushev and others.
* https://github.com/mfvanek/pg-index-health-sql
*
* Licensed under the Apache License 2.0
*/

-- Finds columns of type 'varchar(n)'.
--
-- See also https://wiki.postgresql.org/wiki/Don%27t_Do_This#Don.27t_use_varchar.28n.29_by_default
select
t.oid::regclass::text as table_name,
col.attnotnull as column_not_null,
quote_ident(col.attname) as column_name
from
pg_catalog.pg_class t
inner join pg_catalog.pg_namespace nsp on nsp.oid = t.relnamespace
inner join pg_catalog.pg_attribute col on col.attrelid = t.oid
where
t.relkind in ('r', 'p') and
not t.relispartition and
col.attnum > 0 and /* to filter out system columns such as oid, ctid, xmin, xmax, etc. */
not col.attisdropped and
col.atttypid = 'varchar'::regtype and
col.atttypmod > 0 and /* only for fixed length varchar (not varchar without n) */
nsp.nspname = :schema_name_param::text
order by table_name, column_name;