Skip to content
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

Add check "Tables are not linked to other tables" #55

Merged
merged 2 commits into from
Oct 20, 2024
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 @@ -45,6 +45,7 @@ For more information please see [PostgreSQL Versioning Policy](https://www.postg
21. Duplicated (completely identical) foreign keys ([sql](https://github.com/mfvanek/pg-index-health-sql/blob/master/sql/duplicated_foreign_keys.sql)).
22. Intersected (partially identical) foreign keys ([sql](https://github.com/mfvanek/pg-index-health-sql/blob/master/sql/intersected_foreign_keys.sql)).
23. Objects with possible name overflow ([sql](https://github.com/mfvanek/pg-index-health-sql/blob/master/sql/possible_object_name_overflow.sql)).
24. Tables not linked to other tables ([sql](https://github.com/mfvanek/pg-index-health-sql/blob/master/sql/tables_not_linked_to_others.sql)).

## Local development

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

-- Finds tables that are not linked to other tables.
--
-- These are often service tables that are not part of the project, or
-- tables that are no longer in use or were created by mistake, but were not deleted in a timely manner.
--
-- Based on query from https://habr.com/ru/articles/803841/
with
nsp as (
select
nsp.oid,
nsp.nspname
from pg_catalog.pg_namespace nsp
where
nsp.nspname = :schema_name_param::text
),

fkeys as (
select c.conrelid
from
pg_catalog.pg_constraint c
inner join nsp on nsp.oid = c.connamespace
where
c.contype = 'f'

union

select c.confrelid
from
pg_catalog.pg_constraint c
inner join nsp on nsp.oid = c.connamespace
where
c.contype = 'f'
)

select
pc.oid::regclass::text as table_name,
pg_table_size(pc.oid) as table_size
from
pg_catalog.pg_class pc
inner join nsp on nsp.oid = pc.relnamespace
where
pc.relkind in ('r', 'p') and
pc.oid not in (select * from fkeys)
order by table_name;