schema_reaper 2.0.1 → 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.
Files changed (43) hide show
  1. checksums.yaml +4 -4
  2. data/.rubocop.yml +3 -0
  3. data/.schema_reaper.yml.example +17 -0
  4. data/CHANGELOG.md +126 -0
  5. data/README.md +66 -13
  6. data/RELEASE_CHECKLIST.md +13 -2
  7. data/lib/generators/schema_reaper/install/templates/initializer.rb.tt +8 -0
  8. data/lib/schema_reaper/alert_config.rb +21 -1
  9. data/lib/schema_reaper/alert_state.rb +35 -0
  10. data/lib/schema_reaper/analyzers/always_null_column.rb +12 -5
  11. data/lib/schema_reaper/analyzers/base.rb +75 -2
  12. data/lib/schema_reaper/analyzers/dead_column.rb +3 -2
  13. data/lib/schema_reaper/analyzers/dead_table.rb +11 -6
  14. data/lib/schema_reaper/analyzers/duplicate_foreign_key.rb +53 -0
  15. data/lib/schema_reaper/analyzers/duplicate_index.rb +11 -4
  16. data/lib/schema_reaper/analyzers/missing_fk_index.rb +10 -4
  17. data/lib/schema_reaper/analyzers/sequence_exhaustion.rb +55 -0
  18. data/lib/schema_reaper/analyzers/single_value_column.rb +17 -5
  19. data/lib/schema_reaper/analyzers/unused_index.rb +13 -7
  20. data/lib/schema_reaper/baseline.rb +95 -10
  21. data/lib/schema_reaper/cli/baseline_support.rb +45 -0
  22. data/lib/schema_reaper/cli.rb +69 -14
  23. data/lib/schema_reaper/config.rb +28 -0
  24. data/lib/schema_reaper/doctor.rb +151 -0
  25. data/lib/schema_reaper/explain.rb +102 -0
  26. data/lib/schema_reaper/gem_awareness.rb +31 -1
  27. data/lib/schema_reaper/inflect.rb +36 -0
  28. data/lib/schema_reaper/introspect/postgres.rb +312 -53
  29. data/lib/schema_reaper/migration_generator.rb +90 -4
  30. data/lib/schema_reaper/notifier.rb +58 -6
  31. data/lib/schema_reaper/railtie.rb +1 -1
  32. data/lib/schema_reaper/reporters/sarif.rb +15 -6
  33. data/lib/schema_reaper/reporters/slack.rb +67 -0
  34. data/lib/schema_reaper/runner.rb +58 -6
  35. data/lib/schema_reaper/runtime.rb +94 -11
  36. data/lib/schema_reaper/schema.rb +58 -4
  37. data/lib/schema_reaper/schema_locator.rb +75 -0
  38. data/lib/schema_reaper/static/cache.rb +66 -0
  39. data/lib/schema_reaper/static/scanner.rb +174 -6
  40. data/lib/schema_reaper/version.rb +1 -1
  41. data/lib/schema_reaper.rb +7 -0
  42. data/schema_reaper.gemspec +0 -1
  43. metadata +13 -4
@@ -32,22 +32,111 @@ module SchemaReaper
32
32
  # expression itself contains: COALESCE(a, b), ROUND(x, 2), etc.
33
33
  COLUMN_SEPARATOR = 31.chr
34
34
 
35
- def initialize(url)
35
+ # Ceiling of each integer column type, for the sequence-exhaustion check:
36
+ # a bigint sequence feeding an integer column overflows at the column's
37
+ # limit, not the sequence's.
38
+ TYPE_MAX = {
39
+ "smallint" => 32_767, "integer" => 2_147_483_647, "bigint" => 9_223_372_036_854_775_807
40
+ }.freeze
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
+
93
+ # Tables in `public` keep their bare name, so every existing config,
94
+ # baseline and finding id stays valid; tables in any other scanned schema
95
+ # are reported as `schema.table`.
96
+ def self.display_name(namespace, table)
97
+ namespace == "public" ? table : "#{namespace}.#{table}"
98
+ end
99
+
100
+ def initialize(url, schemas: Config::DEFAULTS["schemas"])
36
101
  Introspect.require_pg!
37
102
  raise Error, NO_URL if url.nil? || url.empty?
38
103
 
104
+ @schemas = Array(schemas)
39
105
  @conn = connect(url)
40
106
  end
41
107
 
42
108
  def call
109
+ deps = dependents
43
110
  DatabaseSchema.new(
44
- tables: table_names.map { |n| build_table(n) },
45
- index_scan_total: index_scan_total
111
+ tables: table_refs.map { |ns, name| build_table(ns, name, deps.fetch([ns, name], NO_DEPENDENTS)) },
112
+ index_scan_total: index_scan_total,
113
+ sequences: sequences
46
114
  )
47
115
  end
48
116
 
117
+ # Health facts for `schema_reaper doctor`, separate from #call so a scan
118
+ # never pays for them.
119
+ def diagnostics
120
+ {
121
+ server_version: exec("SHOW server_version").first&.fetch("server_version"),
122
+ stats_reset: exec(<<~SQL).first&.fetch("stats_reset"),
123
+ SELECT stats_reset FROM pg_stat_database WHERE datname = current_database()
124
+ SQL
125
+ never_analyzed: never_analyzed,
126
+ in_recovery: exec("SELECT pg_is_in_recovery() AS r").first&.fetch("r") == "t"
127
+ }
128
+ end
129
+
49
130
  private
50
131
 
132
+ def never_analyzed
133
+ exec(<<~SQL, [pg_array(@schemas)]).map { |r| self.class.display_name(r["schemaname"], r["relname"]) }
134
+ SELECT schemaname, relname FROM pg_stat_user_tables
135
+ WHERE schemaname = ANY($1::text[]) AND last_analyze IS NULL AND last_autoanalyze IS NULL
136
+ ORDER BY schemaname, relname
137
+ SQL
138
+ end
139
+
51
140
  # Kept out of #initialize: a `rescue PG::Error` there is evaluated for
52
141
  # *any* exception, including require_pg!'s, and would itself raise NameError
53
142
  # when pg is the thing that failed to load.
@@ -65,29 +154,40 @@ module SchemaReaper
65
154
  .first&.fetch("total")&.to_i
66
155
  end
67
156
 
68
- def table_names
69
- exec(<<~SQL).map { |r| r["tablename"] }
70
- SELECT tablename FROM pg_tables WHERE schemaname = 'public' ORDER BY tablename
157
+ # Partitions are left out: the app (and every analyzer) deals with the
158
+ # partitioned parent, so reporting `events_2026_01` as an unreferenced
159
+ # table would be wrong. The parent's row count and index usage are
160
+ # rolled up from its partitions instead.
161
+ def table_refs
162
+ exec(<<~SQL, [pg_array(@schemas)]).map { |r| [r["schemaname"], r["tablename"]] }
163
+ SELECT n.nspname AS schemaname, c.relname AS tablename
164
+ FROM pg_class c
165
+ JOIN pg_namespace n ON n.oid = c.relnamespace
166
+ WHERE c.relkind IN ('r', 'p') AND NOT c.relispartition AND n.nspname = ANY($1::text[])
167
+ ORDER BY n.nspname = 'public' DESC, n.nspname, c.relname
71
168
  SQL
72
169
  end
73
170
 
74
- def build_table(name)
171
+ def build_table(namespace, name, deps)
172
+ fks = foreign_key_constraints_for(namespace, name)
75
173
  Table.new(
76
- name: name,
77
- columns: columns_for(name),
78
- indexes: indexes_for(name),
79
- primary_key: primary_key_for(name),
80
- foreign_keys: foreign_keys_for(name),
81
- row_count: row_count_for(name)
174
+ name: self.class.display_name(namespace, name),
175
+ columns: columns_for(namespace, name, deps[:columns]),
176
+ indexes: indexes_for(namespace, name),
177
+ primary_key: primary_key_for(namespace, name),
178
+ foreign_keys: fks.flat_map(&:columns).uniq,
179
+ foreign_key_constraints: fks,
180
+ row_count: row_count_for(namespace, name),
181
+ dependents: deps[:table]
82
182
  )
83
183
  end
84
184
 
85
- def columns_for(table)
86
- stats = column_stats_for(table)
87
- exec(<<~SQL, [table]).map do |r|
185
+ def columns_for(namespace, table, dependents)
186
+ stats = column_stats_for(namespace, table)
187
+ exec(<<~SQL, [namespace, table]).map do |r|
88
188
  SELECT column_name, data_type, is_nullable, column_default
89
189
  FROM information_schema.columns
90
- WHERE table_schema = 'public' AND table_name = $1
190
+ WHERE table_schema = $1 AND table_name = $2
91
191
  ORDER BY ordinal_position
92
192
  SQL
93
193
  s = stats[r["column_name"]] || {}
@@ -96,37 +196,80 @@ module SchemaReaper
96
196
  sql_type: r["data_type"],
97
197
  null: r["is_nullable"] == "YES",
98
198
  default: r["column_default"],
99
- bytes: AVG_TYPE_BYTES.fetch(r["data_type"], 16),
199
+ bytes: measured_bytes(s) || AVG_TYPE_BYTES.fetch(r["data_type"], 16),
100
200
  null_fraction: s[:null_frac],
101
- distinct_values: s[:n_distinct]
201
+ distinct_values: s[:n_distinct],
202
+ dependents: dependents.fetch(r["column_name"], [])
102
203
  )
103
204
  end
104
205
  end
105
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
+
219
+ # avg_width covers non-null values only, and a NULL takes no space in
220
+ # the row (just its bit in the null bitmap), so scale by the share of
221
+ # rows that actually hold a value.
222
+ def measured_bytes(stats)
223
+ return 0 if stats[:null_frac].to_f >= 1.0 # all NULL: only the null-bitmap bit, avg_width 0
224
+ return nil unless stats[:avg_width]
225
+
226
+ (stats[:avg_width] * (1.0 - stats[:null_frac].to_f)).round
227
+ end
228
+
106
229
  # pg_stats.n_distinct: >= 0 is an absolute count, < 0 is a ratio of rows.
107
- def column_stats_for(table)
108
- exec(<<~SQL, [table]).each_with_object({}) do |r, h|
109
- SELECT attname, null_frac, n_distinct
110
- FROM pg_stats WHERE schemaname = 'public' AND tablename = $1
230
+ # avg_width is the measured average stored width of the non-null values,
231
+ # far closer to reality than a per-type guess for text/jsonb/arrays.
232
+ def column_stats_for(namespace, table)
233
+ exec(<<~SQL, [namespace, table]).each_with_object({}) do |r, h|
234
+ SELECT attname, null_frac, n_distinct, avg_width
235
+ FROM pg_stats WHERE schemaname = $1 AND tablename = $2
236
+ -- later rows win below: a plain row (inherited = false) beats an inherited one, and a
237
+ -- partitioned parent, which only has inherited rows, still gets those
238
+ ORDER BY inherited DESC
111
239
  SQL
112
240
  nd = r["n_distinct"].to_f
241
+ width = r["avg_width"]&.to_i
113
242
  h[r["attname"]] = {
114
243
  null_frac: r["null_frac"].to_f,
115
- n_distinct: nd >= 0 ? nd.round : nil
244
+ n_distinct: nd >= 0 ? nd.round : nil,
245
+ avg_width: width&.positive? ? width : nil
116
246
  }
117
247
  end
118
248
  end
119
249
 
250
+ # A partitioned parent's index (relkind 'I') is never scanned itself --
251
+ # the planner scans each partition's index -- so its usage is the sum
252
+ # over the leaf partitions, or every such index would look unused.
253
+ #
120
254
  # Columns come back in index-key order via pg_get_indexdef(indexrelid,
121
255
  # column_no, pretty), keyed by column position rather than table attnum
122
256
  # so it renders a plain column and an expression uniformly and never
123
257
  # silently drops one. indnkeyatts excludes INCLUDE columns, which are
124
258
  # payload only. partial (indpred IS NOT NULL) lets analyzers refuse to
125
- # treat a conditional index as if it covered every row.
126
- def indexes_for(table)
127
- exec(<<~SQL, [table]).map do |r|
128
- SELECT i.relname AS name, ix.indisunique AS "unique", ix.indisprimary AS "primary",
129
- (ix.indpred IS NOT NULL) AS partial, s.idx_scan AS scans,
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.
264
+ def indexes_for(namespace, table)
265
+ exec(<<~SQL, [namespace, table]).map do |r|
266
+ SELECT i.relname AS name, (i.relkind = 'I') AS partitioned,
267
+ ix.indisunique AS "unique", ix.indisprimary AS "primary",
268
+ (ix.indpred IS NOT NULL) AS partial,
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,
130
273
  array_to_string(
131
274
  array_agg(pg_get_indexdef(ix.indexrelid, k.ord::int, true) ORDER BY k.ord),
132
275
  '#{COLUMN_SEPARATOR}'
@@ -136,55 +279,171 @@ module SchemaReaper
136
279
  JOIN pg_class i ON i.oid = ix.indexrelid
137
280
  JOIN LATERAL generate_series(1, ix.indnkeyatts) AS k(ord) ON TRUE
138
281
  LEFT JOIN pg_stat_user_indexes s ON s.indexrelid = i.oid
139
- WHERE t.relname = $1 AND t.relnamespace = 'public'::regnamespace
140
- GROUP BY i.relname, ix.indisunique, ix.indisprimary, ix.indpred, s.idx_scan
282
+ WHERE t.relnamespace = $1::regnamespace AND t.relname = $2
283
+ GROUP BY t.oid, i.oid, i.relname, i.relkind, ix.indisunique, ix.indisprimary, ix.indpred, s.idx_scan
141
284
  SQL
142
- Index.new(
143
- name: r["name"], columns: r["cols"].split(COLUMN_SEPARATOR),
144
- unique: r["unique"] == "t", primary: r["primary"] == "t", partial: r["partial"] == "t",
145
- scans: r["scans"]&.to_i
146
- )
285
+ build_index(r)
147
286
  end
148
287
  end
149
288
 
289
+ def build_index(row)
290
+ Index.new(
291
+ name: row["name"], columns: row["cols"].split(COLUMN_SEPARATOR),
292
+ unique: row["unique"] == "t", primary: row["primary"] == "t", partial: row["partial"] == "t",
293
+ scans: row["scans"]&.to_i, partitioned: row["partitioned"] == "t",
294
+ constraint: row["constraint_name"]
295
+ )
296
+ end
297
+
150
298
  # Every primary-key column, in key order. A composite key needs the whole
151
299
  # list: returning one arbitrary column leaves the rest looking like
152
- # ordinary columns to the analyzers.
153
- def primary_key_for(table)
154
- exec(<<~SQL, [table]).map { |r| r["attname"] }
300
+ # ordinary columns to the analyzers. The relation is resolved by schema
301
+ # and name rather than a ::regclass cast, which would follow search_path.
302
+ def primary_key_for(namespace, table)
303
+ exec(<<~SQL, [namespace, table]).map { |r| r["attname"] }
155
304
  SELECT a.attname
156
305
  FROM pg_index i
306
+ JOIN pg_class t ON t.oid = i.indrelid
157
307
  JOIN LATERAL unnest(i.indkey::int2[]) WITH ORDINALITY AS k(attnum, ord) ON TRUE
158
308
  JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum
159
- WHERE i.indrelid = $1::regclass AND i.indisprimary
309
+ WHERE t.relnamespace = $1::regnamespace AND t.relname = $2 AND i.indisprimary
160
310
  ORDER BY k.ord
161
311
  SQL
162
312
  rescue Error, PG::Error
163
313
  nil
164
314
  end
165
315
 
166
- def foreign_keys_for(table)
167
- exec(<<~SQL, [table]).map { |r| r["column_name"] }
168
- SELECT kcu.column_name
169
- FROM information_schema.table_constraints tc
170
- JOIN information_schema.key_column_usage kcu
171
- ON tc.constraint_name = kcu.constraint_name
172
- WHERE tc.constraint_type = 'FOREIGN KEY'
173
- AND tc.table_schema = 'public' AND tc.table_name = $1
316
+ # Read from pg_constraint rather than information_schema: constraint
317
+ # names are only unique per table, so joining key_column_usage on the
318
+ # name alone mixes up two tables' same-named constraints. conkey keeps
319
+ # a composite key's columns together and in order.
320
+ def foreign_key_constraints_for(namespace, table)
321
+ exec(<<~SQL, [namespace, table]).map { |r| build_foreign_key(r) }
322
+ SELECT c.conname AS name,
323
+ array_to_string(array_agg(a.attname ORDER BY k.ord), ',') AS cols,
324
+ rn.nspname AS ref_schema, rt.relname AS ref_table,
325
+ c.confkey::text AS ref_key, c.confupdtype, c.confdeltype, c.confmatchtype,
326
+ c.condeferrable, c.condeferred, c.convalidated
327
+ FROM pg_constraint c
328
+ JOIN pg_class t ON t.oid = c.conrelid
329
+ JOIN pg_class rt ON rt.oid = c.confrelid
330
+ JOIN pg_namespace rn ON rn.oid = rt.relnamespace
331
+ JOIN LATERAL unnest(c.conkey) WITH ORDINALITY AS k(attnum, ord) ON TRUE
332
+ JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.attnum
333
+ WHERE c.contype = 'f' AND t.relnamespace = $1::regnamespace AND t.relname = $2
334
+ #{"AND c.conparentid = 0" if version_num >= 110_000}
335
+ GROUP BY c.conname, rn.nspname, rt.relname, c.confkey, c.confupdtype, c.confdeltype,
336
+ c.confmatchtype, c.condeferrable, c.condeferred, c.convalidated
337
+ ORDER BY c.conname
174
338
  SQL
175
339
  end
176
340
 
341
+ def build_foreign_key(row)
342
+ ForeignKey.new(
343
+ name: row["name"], columns: row["cols"].split(","),
344
+ references: self.class.display_name(row["ref_schema"], row["ref_table"]),
345
+ # Everything that changes what the constraint does. Two FKs are
346
+ # only interchangeable when all of it matches.
347
+ behaviour: [row["ref_key"], row["confupdtype"], row["confdeltype"], row["confmatchtype"],
348
+ row["condeferrable"], row["condeferred"]].join(":"),
349
+ validated: row["convalidated"] == "t"
350
+ )
351
+ end
352
+
177
353
  # pg_class.reltuples is an estimate maintained by ANALYZE/VACUUM. On
178
354
  # PostgreSQL 14+ it is -1 for a relation that has never been analysed,
179
355
  # which is "unknown", not "minus one row". Map anything negative to nil so
180
356
  # analyzers treat the count as unavailable.
181
- def row_count_for(table)
182
- raw = exec(<<~SQL, [table]).first&.fetch("reltuples")&.to_f
183
- SELECT reltuples FROM pg_class WHERE relname = $1
357
+ # A partitioned parent holds no rows itself: sum its leaf partitions,
358
+ # and treat the count as unknown if any leaf is unanalysed.
359
+ def row_count_for(namespace, table)
360
+ return legacy_row_count_for(namespace, table) unless pg12?
361
+
362
+ rows = exec(<<~SQL, [namespace, table])
363
+ SELECT leaf.reltuples
364
+ FROM pg_class t
365
+ JOIN LATERAL (
366
+ SELECT c.reltuples FROM pg_partition_tree(t.oid) pt JOIN pg_class c ON c.oid = pt.relid
367
+ WHERE t.relkind = 'p' AND pt.isleaf
368
+ UNION ALL
369
+ SELECT t.reltuples WHERE t.relkind = 'r'
370
+ ) leaf ON TRUE
371
+ WHERE t.relnamespace = $1::regnamespace AND t.relname = $2
372
+ SQL
373
+ counts = rows.map { |r| r["reltuples"].to_f }
374
+ return nil if counts.empty? || counts.any?(&:negative?)
375
+
376
+ counts.sum.round
377
+ end
378
+
379
+ # A CYCLE sequence wraps instead of running out, and a descending one
380
+ # counts towards min_value, so neither is reported.
381
+ #
382
+ # Sequences owned by a column (serial, bigserial or IDENTITY), with the
383
+ # ceiling that actually applies: the lower of the sequence's max_value
384
+ # and the owning column type's. pg_sequences.last_value is NULL until
385
+ # the sequence has been used, and unreadable without USAGE/SELECT on it.
386
+ def sequences
387
+ exec(<<~SQL, [pg_array(@schemas)]).map { |r| build_sequence(r) }
388
+ SELECT s.schemaname, s.sequencename, s.last_value, s.max_value, s.min_value,
389
+ tn.nspname AS table_schema, t.relname AS table_name, a.attname AS column_name,
390
+ format_type(a.atttypid, NULL) AS column_type
391
+ FROM pg_sequences s
392
+ JOIN pg_class sc ON sc.relname = s.sequencename AND sc.relnamespace = s.schemaname::regnamespace
393
+ JOIN pg_depend d ON d.objid = sc.oid AND d.classid = 'pg_class'::regclass
394
+ AND d.refclassid = 'pg_class'::regclass AND d.deptype IN ('a', 'i')
395
+ JOIN pg_class t ON t.oid = d.refobjid
396
+ JOIN pg_namespace tn ON tn.oid = t.relnamespace
397
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = d.refobjsubid
398
+ WHERE s.schemaname = ANY($1::text[]) AND s.last_value IS NOT NULL
399
+ AND NOT s.cycle AND s.increment_by > 0
184
400
  SQL
185
- return nil if raw.nil? || raw.negative?
401
+ rescue Error
402
+ [] # PG < 10 has no pg_sequences, or no privilege: skip, never fail the scan
403
+ end
404
+
405
+ def build_sequence(row)
406
+ ceiling = [row["max_value"].to_i, TYPE_MAX.fetch(row["column_type"], row["max_value"].to_i)].min
407
+ Sequence.new(
408
+ name: self.class.display_name(row["schemaname"], row["sequencename"]),
409
+ table: self.class.display_name(row["table_schema"], row["table_name"]),
410
+ column: row["column_name"], column_type: row["column_type"],
411
+ last_value: row["last_value"].to_i, max_value: ceiling
412
+ )
413
+ end
414
+
415
+ # PostgreSQL 10/11 lack pg_partition_tree (and 10 lacks conparentid).
416
+ # Both are still worth supporting; on them partitioned parents get the
417
+ # pre-partition-aware treatment.
418
+ def version_num
419
+ @version_num ||= exec("SHOW server_version_num").first["server_version_num"].to_i
420
+ end
421
+
422
+ def pg12?
423
+ version_num >= 120_000
424
+ end
425
+
426
+ def partitioned_index_scans_sql
427
+ return "s.idx_scan" unless pg12?
428
+
429
+ <<~SQL.strip
430
+ CASE WHEN i.relkind = 'I' THEN (
431
+ SELECT sum(cs.idx_scan) FROM pg_partition_tree(i.oid) pt
432
+ JOIN pg_stat_user_indexes cs ON cs.indexrelid = pt.relid
433
+ WHERE pt.isleaf
434
+ ) ELSE s.idx_scan END
435
+ SQL
436
+ end
437
+
438
+ def legacy_row_count_for(namespace, table)
439
+ raw = exec(<<~SQL, [namespace, table]).first&.fetch("reltuples")&.to_f
440
+ SELECT reltuples FROM pg_class WHERE relnamespace = $1::regnamespace AND relname = $2
441
+ SQL
442
+ raw.nil? || raw.negative? ? nil : raw.round
443
+ end
186
444
 
187
- raw.round
445
+ def pg_array(values)
446
+ PG::TextEncoder::Array.new.encode(values)
188
447
  end
189
448
 
190
449
  def exec(sql, params = nil)
@@ -3,7 +3,9 @@
3
3
  require "fileutils"
4
4
 
5
5
  module SchemaReaper
6
- # Emits a two-step, reversible migration pair for a dead column.
6
+ # Emits removal migrations: a two-step pair for a dead column (ignore, then
7
+ # drop), or a single migration for an index (index:) or a whole table (no
8
+ # column: and no index:).
7
9
  class MigrationGenerator
8
10
  # Enough of Rails' inflector for table names in this comment text -- a
9
11
  # wrong guess doesn't break anything functional, just reads oddly.
@@ -13,19 +15,99 @@ module SchemaReaper
13
15
  [/s\z/, ""] # employees -> employee
14
16
  ].freeze
15
17
 
16
- def initialize(table:, column:, dir: "db/migrate")
18
+ def initialize(table:, column: nil, index: nil, dir: "db/migrate")
19
+ raise ArgumentError, "pass column: or index:, not both" if column && index
20
+
17
21
  @table = table
18
22
  @column = column
23
+ @index = index
19
24
  @dir = dir
20
25
  end
21
26
 
22
27
  def call
23
28
  FileUtils.mkdir_p(@dir)
29
+ return [drop_index] if @index
30
+ return [drop_table] unless @column
31
+
24
32
  [stage_one, stage_two]
25
33
  end
26
34
 
27
35
  private
28
36
 
37
+ # CREATE/DROP INDEX CONCURRENTLY cannot run inside a transaction, hence
38
+ # disable_ddl_transaction!. A partitioned index can't be dropped
39
+ # concurrently at all, and the generator never sees the database, so the
40
+ # migration checks pg_class itself when it runs. The down raises rather
41
+ # than guessing at the index's definition; recreate it from db/schema.rb.
42
+ def drop_index
43
+ down_msg = "recreate #{@index} on :#{@table} from db/schema.rb if you need it back"
44
+ write "remove_#{@index}", <<~RUBY
45
+ # frozen_string_literal: true
46
+
47
+ # Removes #{@index} -- concurrently, so writes to #{@table} are not
48
+ # blocked, unless it is a partitioned index, which PostgreSQL can only
49
+ # drop with a lock on the table and every partition.
50
+ class Remove#{camelize(@index)} < ActiveRecord::Migration[#{migration_version}]
51
+ disable_ddl_transaction!
52
+
53
+ def up
54
+ if partitioned_index?
55
+ say "#{@index} is a partitioned index: dropping it without CONCURRENTLY (locks #{@table})"
56
+ remove_index #{@table.to_sym.inspect}, name: #{@index.to_sym.inspect}, if_exists: true
57
+ else
58
+ remove_index #{@table.to_sym.inspect}, name: #{@index.to_sym.inspect}, algorithm: :concurrently, if_exists: true
59
+ end
60
+ end
61
+
62
+ def down
63
+ raise ActiveRecord::IrreversibleMigration, #{down_msg.inspect}
64
+ end
65
+
66
+ #{partitioned_check}
67
+ end
68
+ RUBY
69
+ end
70
+
71
+ # The generated migration's private helper, indented to sit inside the
72
+ # class body (the first line lands where the template places it).
73
+ def partitioned_check
74
+ [
75
+ "private",
76
+ "",
77
+ "def partitioned_index?",
78
+ " select_value(<<~SQL) == \"I\"",
79
+ " SELECT relkind FROM pg_class WHERE oid = to_regclass(\#{connection.quote(#{qualified_index.inspect})})",
80
+ " SQL",
81
+ "end"
82
+ ].map.with_index { |line, i| i.zero? || line.empty? ? line : " #{line}" }.join("\n")
83
+ end
84
+
85
+ # An index lives in its table's schema; qualify it so to_regclass doesn't
86
+ # depend on search_path.
87
+ def qualified_index
88
+ @table.include?(".") ? "#{@table.split(".").first}.#{@index}" : @index
89
+ end
90
+
91
+ def drop_table
92
+ down_msg = "#{@table} and its rows are gone; restore from a backup if you need them back"
93
+ write "drop_#{@table}", <<~RUBY
94
+ # frozen_string_literal: true
95
+
96
+ # Drops #{@table} and every row in it. Run only after confirming no
97
+ # external consumer (reports, ETL, other services) reads it, and with
98
+ # a backup taken. Remove the #{model} model, if any, in the same deploy.
99
+ class Drop#{camelize(@table)}Table < ActiveRecord::Migration[#{migration_version}]
100
+ def up
101
+ drop_table #{@table.to_sym.inspect}
102
+ end
103
+
104
+ def down
105
+ raise ActiveRecord::IrreversibleMigration, #{down_msg.inspect}
106
+ end
107
+ end
108
+ RUBY
109
+ end
110
+
29
111
  def stage_one
30
112
  note = "Add `self.ignored_columns += %w[#{@column}]` to the #{model} model, " \
31
113
  "then deploy STEP 2 after a soak period."
@@ -67,7 +149,7 @@ module SchemaReaper
67
149
  def write(slug, body)
68
150
  @seq = (@seq || -1) + 1
69
151
  ts = (Time.now + @seq).strftime("%Y%m%d%H%M%S")
70
- path = File.join(@dir, "#{ts}_#{slug}.rb")
152
+ path = File.join(@dir, "#{ts}_#{slug.tr(".", "_")}.rb")
71
153
  File.write(path, body)
72
154
  path
73
155
  end
@@ -81,7 +163,11 @@ module SchemaReaper
81
163
  end
82
164
 
83
165
  def camel
84
- "#{@table}_#{@column}".split("_").map(&:capitalize).join
166
+ camelize("#{@table}_#{@column}")
167
+ end
168
+
169
+ def camelize(str)
170
+ str.split(/[_.]/).map(&:capitalize).join
85
171
  end
86
172
 
87
173
  def model