schema_reaper 2.1.0 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 65c5a4cc1857d1fbf940b5907cbb7d8e48de74cebb7b69eb6dd1b8e2a0c26bfa
4
- data.tar.gz: 679e01d41a797c37dfd94858464127b1ce8789bda1d92cb905f011a2369fe1c8
3
+ metadata.gz: 1f8b717dee83af6edded334ff81b43b7b9a59de190b9400bfa348bee13cbd61f
4
+ data.tar.gz: 5c5bcfb497f5116b72c3fc6a407b9338668da91296aaa28b088cee78cc58f29d
5
5
  SHA512:
6
- metadata.gz: ef8476dfea36578ef5c97c43fc97c7334371ce38aa14f0d736028d57e42d370b43363922511676af417d76f5fd9b9b35536e98168253efc9c6a663230c56d8c6
7
- data.tar.gz: cf4f22deed425352ac3d0553deefb34495e4c234170f402167866fa445b4b4bf707fc3d078a3a612fc99477ed39b9c152f96f4cdfb45555ecfa7a0eaaab9cd82
6
+ metadata.gz: 5ab316dffd15ac5a31c5843cc7d2e8bdb75f594af67bcc656a623b7730338aec58b7c3698067b571463380e4704eab080f2801dd21030b40638c5025ec99fa9b
7
+ data.tar.gz: 884282a90df32ef8d06cd23fe529c561c683bb7aa1331924ed2451995b53083eb7c2796ae2e78782135e35d83306ff76fe6e3daf5e32395c0d759e281a375893
data/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.1.1] - 2026-11-27
4
+
5
+ ### Fixed
6
+ - **Columns and tables the database itself reads are no longer reported as
7
+ dead.** A column read only by a view, a materialized view, a rule, a
8
+ generated column's expression or an `UPDATE OF` trigger looked unused to
9
+ the code scan, so `dead_column` suggested a `remove_column` that PostgreSQL
10
+ refuses (or that takes the view with it under `CASCADE`). The same went for
11
+ a table only a view or another table's rule uses, and `dead_table`.
12
+ Introspection now reads these dependencies from `pg_depend` -- in one query
13
+ for the whole database, not one per table -- and files any that point at a
14
+ partition under its partitioned parent. `dead_column` and `dead_table` skip
15
+ what they cover, and `always_null_column` / `single_value_column` still
16
+ report the column but name what blocks its removal. Trigger *functions*
17
+ record no column dependencies, so columns they alone touch are still
18
+ invisible. (#30, @mitkush)
19
+ - **Indexes that back a constraint are never offered for removal.**
20
+ `unused_index` flagged the index behind an `EXCLUDE` constraint (it is not
21
+ unique, so the existing guard missed it), and `duplicate_index` could pick a
22
+ `UNIQUE` constraint's index over a plain unique index on the same columns.
23
+ In both cases the suggested `remove_index` fails: only dropping the
24
+ constraint removes such an index. `duplicate_index` now keeps the
25
+ constraint's index and flags the plain one. (#30, @mitkush)
26
+
3
27
  ## [2.1.0] - 2026-10-14
4
28
 
5
29
  ### Fixed
data/README.md CHANGED
@@ -307,9 +307,9 @@ for watching the real, live database.
307
307
 
308
308
  | type | what it flags | main signal |
309
309
  |---|---|---|
310
- | `dead_column` | column no code path references | static scan (+ runtime) |
311
- | `dead_table` | table with no model or query reference | static scan + row count |
312
- | `unused_index` | non-unique index with `idx_scan = 0` (needs query history; stats are per server, so check replicas too) | `pg_stat_user_indexes` |
310
+ | `dead_column` | column no code path references, and no view, rule, generated column or `UPDATE OF` trigger reads (on the table or any of its partitions) | static scan (+ runtime) + `pg_depend` |
311
+ | `dead_table` | table with no model or query reference, and no view or rule using it | static scan + row count + `pg_depend` |
312
+ | `unused_index` | non-unique index with `idx_scan = 0`, other than one backing an `EXCLUDE` constraint (needs query history; stats are per server, so check replicas too) | `pg_stat_user_indexes` |
313
313
  | `duplicate_index` | index that exactly duplicates another, or is a prefix of a wider one | schema shape |
314
314
  | `missing_fk_index` | `*_id` / foreign-key column with no index (polymorphic pairs need a `(type, id)` index) | schema shape |
315
315
  | `always_null_column` | `null_frac = 1.0` — no data at all | `pg_stats` |
@@ -30,7 +30,7 @@ module SchemaReaper
30
30
  severity: :high,
31
31
  confidence: sampled_stats?(table) ? 0.7 : 0.85,
32
32
  bytes_per_row: col.bytes,
33
- evidence: evidence_for(table),
33
+ evidence: evidence_for(table) + dependents_evidence(col),
34
34
  suggested_fix: "verify with `SELECT count(#{col.name}) FROM #{table.name}` " \
35
35
  "then stage a removal"
36
36
  )
@@ -110,6 +110,15 @@ module SchemaReaper
110
110
  config.ignored_column?(name)
111
111
  end
112
112
 
113
+ # Evidence for a column some view, rule, generated column or trigger reads:
114
+ # removing it fails until those are changed, or silently cascades.
115
+ def dependents_evidence(col)
116
+ return [] if col.dependents.empty?
117
+
118
+ ["read by #{col.dependents.join(", ")} -- change #{col.dependents.size == 1 ? "it" : "them"} " \
119
+ "before removing the column"]
120
+ end
121
+
113
122
  # The removal command for an index. DROP INDEX CONCURRENTLY is refused
114
123
  # on a partitioned index ("cannot drop partitioned index ...
115
124
  # concurrently"), and its per-partition indexes can't be dropped on
@@ -43,6 +43,7 @@ module SchemaReaper
43
43
  config.ignored_column?(col.name) ||
44
44
  table.primary_key?(col.name) ||
45
45
  table.foreign_keys.include?(col.name) ||
46
+ col.dependents.any? || # read by a view, rule, generated column or trigger
46
47
  col.name.end_with?("_id", "_type") ||
47
48
  gem_reserved?(table.name, col.name)
48
49
  end
@@ -30,6 +30,7 @@ module SchemaReaper
30
30
 
31
31
  def dead(table)
32
32
  return if referenced?(table)
33
+ return if table.dependents.any? # a view or rule uses it: DROP TABLE would fail, or CASCADE
33
34
  return if runtime.table_accessed?(table.name)
34
35
 
35
36
  finding(
@@ -27,7 +27,12 @@ module SchemaReaper
27
27
  non_pk.filter_map { |index| finding_for(table, index, non_pk, by_columns) }
28
28
  end
29
29
 
30
+ # An index backing a UNIQUE or EXCLUDE constraint is never offered for
31
+ # removal: DROP INDEX refuses it, so the suggested remove_index would
32
+ # fail, and only dropping the constraint itself could remove it.
30
33
  def finding_for(table, index, non_pk, by_columns)
34
+ return if index.constraint_backed?
35
+
31
36
  covering = covering_for(index, non_pk, by_columns)
32
37
  return unless covering
33
38
 
@@ -62,11 +67,13 @@ module SchemaReaper
62
67
  end
63
68
 
64
69
  # Keep a unique index over a non-unique one -- it enforces a guarantee
65
- # the others don't -- breaking further ties by name for a stable,
66
- # order-independent choice.
70
+ # the others don't -- and among unique ones, the one backing a
71
+ # constraint, since that one cannot be dropped. Further ties break by
72
+ # name for a stable, order-independent choice.
67
73
  def survivor_of(peers)
68
74
  unique_peers = peers.select(&:unique)
69
- (unique_peers.empty? ? peers : unique_peers).min_by(&:name)
75
+ candidates = unique_peers.empty? ? peers : unique_peers
76
+ candidates.min_by { |index| [index.constraint_backed? ? 0 : 1, index.name] }
70
77
  end
71
78
 
72
79
  def prefix_covering_for(index, non_pk)
@@ -51,7 +51,7 @@ module SchemaReaper
51
51
  "column has the same value in every row"
52
52
  end
53
53
  ev << "estimated from a #{STATS_SAMPLE_ROWS}-row ANALYZE sample" if sampled_stats?(table)
54
- ev
54
+ ev + dependents_evidence(col)
55
55
  end
56
56
  end
57
57
  end
@@ -22,7 +22,8 @@ module SchemaReaper
22
22
 
23
23
  def unused_in(table)
24
24
  table.indexes.filter_map do |ix|
25
- next if ix.primary || ix.unique # keep constraint-backing indexes
25
+ next if ix.primary || ix.unique # enforce a guarantee even when never scanned
26
+ next if ix.constraint_backed? # EXCLUDE: DROP INDEX refuses it, and it enforces one too
26
27
  next if ix.scans.nil? # no stats available
27
28
  next unless ix.scans.zero?
28
29
 
@@ -39,6 +39,57 @@ module SchemaReaper
39
39
  "smallint" => 32_767, "integer" => 2_147_483_647, "bigint" => 9_223_372_036_854_775_807
40
40
  }.freeze
41
41
 
42
+ # Database objects that would block dropping a scanned table or one of
43
+ # its columns, keyed by [schema, table], from pg_depend's normal (deptype
44
+ # 'n') edges -- the ones that make DROP fail without CASCADE:
45
+ # pg_rewrite -- a view or materialized view's query, or a rule. It
46
+ # points at each column it reads, or at the table alone
47
+ # (attnum 0) when it reads none, e.g. SELECT count(*);
48
+ # pg_attrdef -- a generated column's expression;
49
+ # pg_trigger -- a trigger declared UPDATE OF the column.
50
+ # A CHECK constraint is left out: it is dropped along with its column.
51
+ # Trigger *functions* record no dependency on the columns they touch, so
52
+ # they stay invisible here.
53
+ #
54
+ # An edge onto a partition is filed under its partitioned root, since
55
+ # dropping the root's column or the root itself recurses into it. A
56
+ # rule on the table itself blocks dropping a column it reads, but is no
57
+ # sign that anything outside the table uses it, so it is left out of
58
+ # :table.
59
+ #
60
+ # One query for every scanned schema: per table, planning this join
61
+ # costs far more than running it.
62
+ DEPENDENTS_SQL = <<~SQL
63
+ SELECT n.nspname AS schemaname, root.relname AS tablename, a.attname,
64
+ (d.classid = 'pg_rewrite'::regclass AND v.oid <> t.oid AND v.oid <> root.oid) AS external,
65
+ CASE d.classid
66
+ WHEN 'pg_rewrite'::regclass THEN
67
+ CASE v.relkind
68
+ WHEN 'v' THEN 'view ' || v.oid::regclass::text
69
+ WHEN 'm' THEN 'materialized view ' || v.oid::regclass::text
70
+ ELSE 'rule ' || r.rulename || ' on ' || v.oid::regclass::text
71
+ END
72
+ WHEN 'pg_attrdef'::regclass THEN 'generated column ' || ga.attname
73
+ ELSE 'trigger ' || tg.tgname
74
+ END AS dependent
75
+ FROM pg_depend d
76
+ JOIN pg_class t ON t.oid = d.refobjid AND t.relkind IN ('r', 'p')
77
+ JOIN pg_class root ON root.oid = %<root>s
78
+ JOIN pg_namespace n ON n.oid = root.relnamespace
79
+ LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = d.refobjsubid AND d.refobjsubid > 0
80
+ LEFT JOIN pg_rewrite r ON d.classid = 'pg_rewrite'::regclass AND r.oid = d.objid
81
+ LEFT JOIN pg_class v ON v.oid = r.ev_class
82
+ LEFT JOIN pg_attrdef ad ON d.classid = 'pg_attrdef'::regclass AND ad.oid = d.objid
83
+ LEFT JOIN pg_attribute ga ON ga.attrelid = ad.adrelid AND ga.attnum = ad.adnum
84
+ LEFT JOIN pg_trigger tg ON d.classid = 'pg_trigger'::regclass AND tg.oid = d.objid
85
+ WHERE d.refclassid = 'pg_class'::regclass AND d.deptype = 'n'
86
+ AND d.classid IN ('pg_rewrite'::regclass, 'pg_attrdef'::regclass, 'pg_trigger'::regclass)
87
+ AND n.nspname = ANY($1::text[])
88
+ ORDER BY dependent
89
+ SQL
90
+
91
+ NO_DEPENDENTS = { columns: {}, table: [] }.freeze
92
+
42
93
  # Tables in `public` keep their bare name, so every existing config,
43
94
  # baseline and finding id stays valid; tables in any other scanned schema
44
95
  # are reported as `schema.table`.
@@ -55,8 +106,9 @@ module SchemaReaper
55
106
  end
56
107
 
57
108
  def call
109
+ deps = dependents
58
110
  DatabaseSchema.new(
59
- tables: table_refs.map { |ns, name| build_table(ns, name) },
111
+ tables: table_refs.map { |ns, name| build_table(ns, name, deps.fetch([ns, name], NO_DEPENDENTS)) },
60
112
  index_scan_total: index_scan_total,
61
113
  sequences: sequences
62
114
  )
@@ -116,20 +168,21 @@ module SchemaReaper
116
168
  SQL
117
169
  end
118
170
 
119
- def build_table(namespace, name)
171
+ def build_table(namespace, name, deps)
120
172
  fks = foreign_key_constraints_for(namespace, name)
121
173
  Table.new(
122
174
  name: self.class.display_name(namespace, name),
123
- columns: columns_for(namespace, name),
175
+ columns: columns_for(namespace, name, deps[:columns]),
124
176
  indexes: indexes_for(namespace, name),
125
177
  primary_key: primary_key_for(namespace, name),
126
178
  foreign_keys: fks.flat_map(&:columns).uniq,
127
179
  foreign_key_constraints: fks,
128
- row_count: row_count_for(namespace, name)
180
+ row_count: row_count_for(namespace, name),
181
+ dependents: deps[:table]
129
182
  )
130
183
  end
131
184
 
132
- def columns_for(namespace, table)
185
+ def columns_for(namespace, table, dependents)
133
186
  stats = column_stats_for(namespace, table)
134
187
  exec(<<~SQL, [namespace, table]).map do |r|
135
188
  SELECT column_name, data_type, is_nullable, column_default
@@ -145,11 +198,24 @@ module SchemaReaper
145
198
  default: r["column_default"],
146
199
  bytes: measured_bytes(s) || AVG_TYPE_BYTES.fetch(r["data_type"], 16),
147
200
  null_fraction: s[:null_frac],
148
- distinct_values: s[:n_distinct]
201
+ distinct_values: s[:n_distinct],
202
+ dependents: dependents.fetch(r["column_name"], [])
149
203
  )
150
204
  end
151
205
  end
152
206
 
207
+ def dependents
208
+ exec(dependents_sql, [pg_array(@schemas)]).each_with_object({}) do |r, out|
209
+ deps = out[[r["schemaname"], r["tablename"]]] ||= { columns: Hash.new { |h, k| h[k] = [] }, table: [] }
210
+ deps[:columns][r["attname"]] |= [r["dependent"]] if r["attname"]
211
+ deps[:table] |= [r["dependent"]] if r["external"] == "t"
212
+ end
213
+ end
214
+
215
+ def dependents_sql
216
+ format(DEPENDENTS_SQL, root: pg12? ? "COALESCE(pg_partition_root(t.oid), t.oid)" : "t.oid")
217
+ end
218
+
153
219
  # avg_width covers non-null values only, and a NULL takes no space in
154
220
  # the row (just its bit in the null bitmap), so scale by the share of
155
221
  # rows that actually hold a value.
@@ -190,13 +256,20 @@ module SchemaReaper
190
256
  # so it renders a plain column and an expression uniformly and never
191
257
  # silently drops one. indnkeyatts excludes INCLUDE columns, which are
192
258
  # payload only. partial (indpred IS NOT NULL) lets analyzers refuse to
193
- # treat a conditional index as if it covered every row.
259
+ # treat a conditional index as if it covered every row. constraint_name
260
+ # is the PRIMARY KEY / UNIQUE / EXCLUDE constraint the index enforces;
261
+ # contype keeps out foreign keys, whose conindid is the *referenced*
262
+ # table's index; matching conrelid first lets the lookup use
263
+ # pg_constraint's conrelid index, as conindid has none.
194
264
  def indexes_for(namespace, table)
195
265
  exec(<<~SQL, [namespace, table]).map do |r|
196
266
  SELECT i.relname AS name, (i.relkind = 'I') AS partitioned,
197
267
  ix.indisunique AS "unique", ix.indisprimary AS "primary",
198
268
  (ix.indpred IS NOT NULL) AS partial,
199
269
  #{partitioned_index_scans_sql} AS scans,
270
+ (SELECT con.conname FROM pg_constraint con
271
+ WHERE con.conrelid = t.oid AND con.conindid = i.oid AND con.contype IN ('p', 'u', 'x')
272
+ LIMIT 1) AS constraint_name,
200
273
  array_to_string(
201
274
  array_agg(pg_get_indexdef(ix.indexrelid, k.ord::int, true) ORDER BY k.ord),
202
275
  '#{COLUMN_SEPARATOR}'
@@ -207,7 +280,7 @@ module SchemaReaper
207
280
  JOIN LATERAL generate_series(1, ix.indnkeyatts) AS k(ord) ON TRUE
208
281
  LEFT JOIN pg_stat_user_indexes s ON s.indexrelid = i.oid
209
282
  WHERE t.relnamespace = $1::regnamespace AND t.relname = $2
210
- GROUP BY i.oid, i.relname, i.relkind, ix.indisunique, ix.indisprimary, ix.indpred, s.idx_scan
283
+ GROUP BY t.oid, i.oid, i.relname, i.relkind, ix.indisunique, ix.indisprimary, ix.indpred, s.idx_scan
211
284
  SQL
212
285
  build_index(r)
213
286
  end
@@ -217,7 +290,8 @@ module SchemaReaper
217
290
  Index.new(
218
291
  name: row["name"], columns: row["cols"].split(COLUMN_SEPARATOR),
219
292
  unique: row["unique"] == "t", primary: row["primary"] == "t", partial: row["partial"] == "t",
220
- scans: row["scans"]&.to_i, partitioned: row["partitioned"] == "t"
293
+ scans: row["scans"]&.to_i, partitioned: row["partitioned"] == "t",
294
+ constraint: row["constraint_name"]
221
295
  )
222
296
  end
223
297
 
@@ -3,11 +3,20 @@
3
3
  module SchemaReaper
4
4
  # Plain-data representation of the database, produced by an introspector.
5
5
  # No ActiveRecord objects leak past this boundary.
6
+ # dependents: database objects that read the column -- views, materialized
7
+ # views, rules, generated columns, `UPDATE OF` triggers -- as labels such as
8
+ # "view active_users". Dropping the column would fail or cascade into them.
6
9
  Column = Struct.new(
7
10
  :name, :sql_type, :null, :default, :bytes,
8
- :distinct_values, :null_fraction,
11
+ :distinct_values, :null_fraction, :dependents,
9
12
  keyword_init: true
10
13
  ) do
14
+ # Introspectors (and hand-built test schemas) that predate dependency
15
+ # tracking leave this nil.
16
+ def dependents
17
+ self[:dependents] || []
18
+ end
19
+
11
20
  # true when every row holds NULL (pg_stats null_frac == 1)
12
21
  def always_null?
13
22
  null_fraction && null_fraction >= 1.0
@@ -21,7 +30,11 @@ module SchemaReaper
21
30
 
22
31
  # partitioned: an index on a partitioned parent (relkind 'I'). PostgreSQL
23
32
  # cannot DROP one CONCURRENTLY, so removal advice differs.
24
- Index = Struct.new(:name, :columns, :unique, :primary, :scans, :partial, :partitioned, keyword_init: true) do
33
+ # constraint: the PRIMARY KEY, UNIQUE or EXCLUDE constraint the index
34
+ # enforces, if any. DROP INDEX refuses such an index -- only dropping the
35
+ # constraint removes it -- so it is never offered as a remove_index.
36
+ Index = Struct.new(:name, :columns, :unique, :primary, :scans, :partial, :partitioned, :constraint,
37
+ keyword_init: true) do
25
38
  def covers?(other)
26
39
  columns.first(other.columns.length) == other.columns
27
40
  end
@@ -33,6 +46,10 @@ module SchemaReaper
33
46
  def partial?
34
47
  !!partial
35
48
  end
49
+
50
+ def constraint_backed?
51
+ !!constraint
52
+ end
36
53
  end
37
54
 
38
55
  # A declared FOREIGN KEY constraint. columns is in key order; references
@@ -52,8 +69,12 @@ module SchemaReaper
52
69
  end
53
70
  end
54
71
 
72
+ # dependents: views, materialized views and rules on other tables that use
73
+ # this table, as labels such as "view active_users" or "rule log_to_t on
74
+ # audit". A table one of them uses is not dead, whatever the application
75
+ # code says -- and DROP TABLE would fail, or CASCADE them away.
55
76
  Table = Struct.new(
56
- :name, :columns, :indexes, :primary_key, :foreign_keys, :foreign_key_constraints, :row_count,
77
+ :name, :columns, :indexes, :primary_key, :foreign_keys, :foreign_key_constraints, :row_count, :dependents,
57
78
  keyword_init: true
58
79
  ) do
59
80
  # Introspectors (and hand-built test schemas) that predate constraint
@@ -62,6 +83,10 @@ module SchemaReaper
62
83
  self[:foreign_key_constraints] || []
63
84
  end
64
85
 
86
+ def dependents
87
+ self[:dependents] || []
88
+ end
89
+
65
90
  def column_names
66
91
  columns.map(&:name)
67
92
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module SchemaReaper
4
- VERSION = "2.1.0"
4
+ VERSION = "2.1.1"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: schema_reaper
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.1.0
4
+ version: 2.1.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - aksshatt
@@ -9,7 +9,7 @@ authors:
9
9
  autorequire:
10
10
  bindir: exe
11
11
  cert_chain: []
12
- date: 2026-10-14 00:00:00.000000000 Z
12
+ date: 2026-11-27 00:00:00.000000000 Z
13
13
  dependencies:
14
14
  - !ruby/object:Gem::Dependency
15
15
  name: prism