schema_reaper 1.0.0

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 +7 -0
  2. data/.rspec +3 -0
  3. data/.rubocop.yml +56 -0
  4. data/.schema_reaper.yml.example +43 -0
  5. data/CHANGELOG.md +45 -0
  6. data/CODE_OF_CONDUCT.md +84 -0
  7. data/LICENSE.txt +21 -0
  8. data/README.md +136 -0
  9. data/Rakefile +12 -0
  10. data/exe/schema_reaper +6 -0
  11. data/lib/schema_reaper/analyzers/always_null_column.rb +43 -0
  12. data/lib/schema_reaper/analyzers/base.rb +54 -0
  13. data/lib/schema_reaper/analyzers/dead_column.rb +72 -0
  14. data/lib/schema_reaper/analyzers/dead_table.rb +60 -0
  15. data/lib/schema_reaper/analyzers/duplicate_index.rb +41 -0
  16. data/lib/schema_reaper/analyzers/missing_fk_index.rb +43 -0
  17. data/lib/schema_reaper/analyzers/registry.rb +20 -0
  18. data/lib/schema_reaper/analyzers/single_value_column.rb +46 -0
  19. data/lib/schema_reaper/analyzers/unused_index.rb +43 -0
  20. data/lib/schema_reaper/baseline.rb +35 -0
  21. data/lib/schema_reaper/cli.rb +68 -0
  22. data/lib/schema_reaper/config.rb +78 -0
  23. data/lib/schema_reaper/finding.rb +28 -0
  24. data/lib/schema_reaper/gem_awareness.rb +80 -0
  25. data/lib/schema_reaper/history.rb +60 -0
  26. data/lib/schema_reaper/introspect/postgres.rb +134 -0
  27. data/lib/schema_reaper/migration_generator.rb +67 -0
  28. data/lib/schema_reaper/railtie.rb +21 -0
  29. data/lib/schema_reaper/reporters/bytes.rb +22 -0
  30. data/lib/schema_reaper/reporters/json.rb +31 -0
  31. data/lib/schema_reaper/reporters/markdown.rb +41 -0
  32. data/lib/schema_reaper/reporters/sarif.rb +67 -0
  33. data/lib/schema_reaper/reporters/table.rb +45 -0
  34. data/lib/schema_reaper/runner.rb +64 -0
  35. data/lib/schema_reaper/runtime.rb +111 -0
  36. data/lib/schema_reaper/schema.rb +34 -0
  37. data/lib/schema_reaper/static/scanner.rb +88 -0
  38. data/lib/schema_reaper/tasks/schema_reaper.rake +26 -0
  39. data/lib/schema_reaper/version.rb +5 -0
  40. data/lib/schema_reaper.rb +44 -0
  41. data/schema_reaper.gemspec +47 -0
  42. data/sig/schema_reaper.rbs +4 -0
  43. metadata +167 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 7c7a7ccaeefa1c6ddc5597a3b54ebb358fdac16ba72e8413b79cc70ecdf9223e
4
+ data.tar.gz: e6a801a21a746da04c63416669c0cf35e55975b8af85b631502847bdba769189
5
+ SHA512:
6
+ metadata.gz: fd33e938eddd3fd6ffb0e50dca359a62ac6974573838605f627a999bed26114d7501f92ae9edb769053ba65b8ee2d5a6f1d5f7b01f84b39f8abb8707ca6113ce
7
+ data.tar.gz: aceba9a2f2fdcb55d8b780b5d1e85a7431c9a587f3592e019c3434e7e0e7343d60d10ee8f7063f4b888027f4bdf3c59e7caa09f04b82c1803e3d96afcef239a3
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,56 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.1
3
+ NewCops: enable
4
+ SuggestExtensions: false
5
+
6
+ Style/StringLiterals:
7
+ EnforcedStyle: double_quotes
8
+
9
+ Style/StringLiteralsInInterpolation:
10
+ EnforcedStyle: double_quotes
11
+
12
+ Style/FormatStringToken:
13
+ Enabled: false
14
+
15
+ Style/Documentation:
16
+ Exclude:
17
+ - "lib/schema_reaper/runtime.rb" # nested Hook/Tracker helpers
18
+
19
+ Style/SafeNavigationChainLength:
20
+ Enabled: false
21
+
22
+ Layout/LineLength:
23
+ Max: 120
24
+
25
+ Naming/MethodParameterName:
26
+ AllowedNames: [f, n, io, id, at, to, db]
27
+
28
+ Metrics/BlockLength:
29
+ Exclude:
30
+ - "spec/**/*"
31
+ - "*.gemspec"
32
+
33
+ Metrics/ParameterLists:
34
+ Exclude:
35
+ - "spec/**/*"
36
+
37
+ Gemspec/DevelopmentDependencies:
38
+ Enabled: false
39
+
40
+ Lint/StructNewOverride:
41
+ Enabled: false
42
+
43
+ Metrics/MethodLength:
44
+ Max: 20
45
+
46
+ Metrics/ClassLength:
47
+ Max: 130
48
+
49
+ Metrics/CyclomaticComplexity:
50
+ Max: 12
51
+
52
+ Metrics/PerceivedComplexity:
53
+ Max: 13
54
+
55
+ Metrics/AbcSize:
56
+ Max: 28
@@ -0,0 +1,43 @@
1
+ # Copy to .schema_reaper.yml and edit. Every key is optional.
2
+ ---
3
+ # database_url: postgres://localhost/myapp_development # else ENV["DATABASE_URL"]
4
+
5
+ scan_paths:
6
+ - app
7
+ - lib
8
+ - config
9
+
10
+ view_globs:
11
+ - app/**/*.erb
12
+ - app/**/*.haml
13
+ - app/**/*.slim
14
+ - app/**/*.jbuilder
15
+
16
+ ignore:
17
+ tables:
18
+ - schema_migrations
19
+ - ar_internal_metadata
20
+ columns:
21
+ - "/_cache$/" # wrap in slashes for a regex
22
+ - legacy_notes
23
+
24
+ always_keep_columns:
25
+ - id
26
+ - created_at
27
+ - updated_at
28
+ - type
29
+
30
+ # Auto-whitelist columns owned by gems in your bundle (devise, paper_trail,
31
+ # activestorage, actiontext, friendly_id, audited, pg_search, ahoy_matey, ...).
32
+ gem_awareness: true
33
+
34
+ # Runtime usage log written by the tracker (see README > Runtime signal).
35
+ runtime_log: .schema_reaper/runtime.jsonl
36
+
37
+ # Append-only snapshot log for `schema_reaper trend`.
38
+ history_log: .schema_reaper/history.jsonl
39
+
40
+ baseline: .schema_reaper/baseline.json
41
+
42
+ # Extra Ruby files to load before analysis -- register custom analyzers here.
43
+ require: []
data/CHANGELOG.md ADDED
@@ -0,0 +1,45 @@
1
+ # Changelog
2
+
3
+ ## [1.0.0] - 2026-09-04
4
+
5
+ First stable release.
6
+
7
+ ### Analyzers
8
+ - `dead_column` — schema column never referenced in code; fuses in runtime
9
+ signal when present to break the 0.6 static-only confidence cap.
10
+ - `dead_table` — table with no model/query reference and (when known) zero rows.
11
+ - `unused_index` — non-unique index with `idx_scan = 0` in `pg_stat_user_indexes`.
12
+ - `duplicate_index` — index that is a leading prefix of a wider index.
13
+ - `missing_fk_index` — foreign-key / `*_id` column with no covering index.
14
+ - `always_null_column` — column with `null_frac = 1.0` in `pg_stats`.
15
+ - `single_value_column` — column with one distinct value on a large table.
16
+
17
+ ### Signal
18
+ - Postgres introspection now also reads row counts (`pg_class.reltuples`),
19
+ per-column `pg_stats` (`null_frac`, `n_distinct`) and index scan counts.
20
+ - Optional runtime tracker: samples ActiveRecord attribute reads into a JSONL
21
+ log; `Runtime::Report` aggregates it and analyzers fuse it in.
22
+ - Gem-awareness maps auto-whitelist columns owned by devise, paper_trail,
23
+ audited, friendly_id, activestorage, actiontext, pg_search, ahoy_matey and
24
+ the paranoia family, scoped to tables that actually carry the anchor column.
25
+
26
+ ### Output & workflow
27
+ - Reporters: `table`, `json`, `markdown` (PR-comment ready), `sarif` 2.1.0
28
+ (GitHub code scanning).
29
+ - Reclaimable-bytes estimate per finding and per run, from row counts.
30
+ - `schema_reaper trend` + append-only history log for cleanup burndown.
31
+ - `scan --ci` gates only findings absent from `.schema_reaper/baseline.json`;
32
+ `scan --record`, `scan --min-confidence`.
33
+ - Whole-dead-table findings suppress their own column/index noise.
34
+ - Rails railtie: `rake schema_reaper:scan|baseline|trend`, opt-in runtime
35
+ tracker via `SCHEMA_REAPER_TRACK=1`.
36
+ - Custom analyzers loadable through the `require:` config key.
37
+
38
+ ### Not in 1.0 (planned)
39
+ - MySQL adapter.
40
+ - Mountable dashboard engine.
41
+ - Orphan-row and schema-drift analyzers.
42
+
43
+ ## [0.1.0]
44
+ - Initial scaffold: `dead_column` static analyzer, table/JSON reporters,
45
+ baseline, staged migration generator.
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at akshatpegwar5@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 aksshatt
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,136 @@
1
+ # schema_reaper
2
+
3
+ Find dead columns, dead tables, unused indexes and other schema dead-weight in
4
+ Rails / ActiveRecord apps — then remove them safely.
5
+
6
+ `schema_reaper` reads your **live PostgreSQL schema and planner statistics** and
7
+ cross-references them against a **static scan of your codebase** (Ruby via the
8
+ Prism AST, plus views and SQL string literals). Optionally it also fuses in a
9
+ **runtime signal** — a sampled log of which columns are actually read in
10
+ production. Every finding is scored by confidence and severity, carries an
11
+ estimate of the disk it reclaims, and comes with a concrete fix.
12
+
13
+ ## Install
14
+
15
+ ```ruby
16
+ # Gemfile
17
+ gem "schema_reaper", group: :development
18
+ ```
19
+
20
+ ```
21
+ bundle install
22
+ ```
23
+
24
+ Requires Ruby >= 3.1 and PostgreSQL. The database connection resolves from
25
+ `database_url` in `.schema_reaper.yml`, else `ENV["DATABASE_URL"]`.
26
+
27
+ ## Usage
28
+
29
+ ```
30
+ bundle exec schema_reaper scan # human-readable report
31
+ bundle exec schema_reaper scan --format markdown # PR-comment table
32
+ bundle exec schema_reaper scan --format sarif # GitHub code scanning
33
+ bundle exec schema_reaper scan --format json
34
+ bundle exec schema_reaper scan --ci # exit 1 on new findings
35
+ bundle exec schema_reaper scan --min-confidence 0.8
36
+ bundle exec schema_reaper baseline # accept current findings
37
+ bundle exec schema_reaper trend # snapshot + progress delta
38
+ bundle exec schema_reaper generate-migration users legacy_api_token
39
+ ```
40
+
41
+ In a Rails app the railtie also gives you
42
+ `rake schema_reaper:scan|baseline|trend` (with `FORMAT=`).
43
+
44
+ ## Analyzers
45
+
46
+ | type | what it flags | main signal |
47
+ |---|---|---|
48
+ | `dead_column` | column no code path references | static scan (+ runtime) |
49
+ | `dead_table` | table with no model/query reference | static scan + row count |
50
+ | `unused_index` | non-unique index, `idx_scan = 0` | `pg_stat_user_indexes` |
51
+ | `duplicate_index` | index that is a prefix of a wider one | schema shape |
52
+ | `missing_fk_index` | `*_id` / FK column with no index | schema shape |
53
+ | `always_null_column` | `null_frac = 1.0` — no data at all | `pg_stats` |
54
+ | `single_value_column` | one distinct value on a large table | `pg_stats` |
55
+
56
+ Columns owned by common gems (devise, paper_trail, activestorage, actiontext,
57
+ friendly_id, audited, pg_search, ahoy_matey, paranoia family) are whitelisted
58
+ automatically when the gem is in your bundle.
59
+
60
+ ## Runtime signal (optional, raises confidence)
61
+
62
+ Static analysis alone can't see metaprogrammed access, so `dead_column`
63
+ confidence is capped at **0.6** without runtime data. To lift the cap:
64
+
65
+ ```ruby
66
+ # config/initializers or manually
67
+ SchemaReaper::Runtime::Tracker.install!(
68
+ store: SchemaReaper::Runtime::Store.new(path: ".schema_reaper/runtime.jsonl"),
69
+ sample_rate: 0.05
70
+ )
71
+ ```
72
+
73
+ or, in Rails, boot with `SCHEMA_REAPER_TRACK=1`. Let it run in staging or
74
+ production for a couple of weeks. A column unseen in **both** code and
75
+ >= 14 observed days of runtime data reaches ~0.9 confidence.
76
+
77
+ ## Safety model
78
+
79
+ `schema_reaper` never drops anything itself. `generate-migration` emits a pair:
80
+
81
+ 1. **Ignore** — you add `self.ignored_columns += %w[col]` to the model and
82
+ deploy. Nothing is dropped.
83
+ 2. **Drop** — run only after step 1 has soaked in production and nothing broke.
84
+
85
+ `always_null_column` / `single_value_column` fixes ask you to confirm with a
86
+ `SELECT` first.
87
+
88
+ ## CI
89
+
90
+ ```yaml
91
+ # .github/workflows/schema_reaper.yml
92
+ - run: bundle exec schema_reaper scan --ci --format sarif > reaper.sarif
93
+ - uses: github/codeql-action/upload-sarif@v3
94
+ with: { sarif_file: reaper.sarif }
95
+ ```
96
+
97
+ Commit `.schema_reaper/baseline.json` so the job fails only when a change adds
98
+ *new* dead weight.
99
+
100
+ ## Custom analyzers
101
+
102
+ ```ruby
103
+ # lib/schema_reaper/analyzers/my_check.rb
104
+ class MyCheck < SchemaReaper::Analyzers::Base
105
+ SchemaReaper::Analyzers::Registry.register(self)
106
+
107
+ def call
108
+ schema.tables.filter_map { |t| ... finding(type: :my_check, table: t.name, ...) }
109
+ end
110
+ end
111
+ ```
112
+
113
+ ```yaml
114
+ # .schema_reaper.yml
115
+ require:
116
+ - lib/schema_reaper/analyzers/my_check.rb
117
+ ```
118
+
119
+ ## Roadmap
120
+
121
+ - Runtime verdict fusion for index and table findings
122
+ - Orphan-row and `schema.rb`↔DB drift analyzers
123
+ - Disk/$ reclaim from real `pg_total_relation_size`
124
+ - Mountable dashboard engine, trend charts
125
+ - MySQL adapter
126
+
127
+ ## Development
128
+
129
+ ```
130
+ bin/setup
131
+ bundle exec rake # rspec + rubocop
132
+ ```
133
+
134
+ ## License
135
+
136
+ MIT.
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/exe/schema_reaper ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "schema_reaper/cli"
5
+
6
+ SchemaReaper::CLI.start(ARGV)
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SchemaReaper
4
+ module Analyzers
5
+ # A column that is NULL in every row (per pg_stats). The data itself says
6
+ # it is dead, independent of code references.
7
+ class AlwaysNullColumn < Base
8
+ Registry.register(self)
9
+
10
+ def call
11
+ schema.tables.reject { |t| config.ignore_tables.include?(t.name) }
12
+ .flat_map { |t| null_in(t) }
13
+ end
14
+
15
+ private
16
+
17
+ def null_in(table)
18
+ return [] unless table.row_count&.positive?
19
+
20
+ table.columns.filter_map do |col|
21
+ next unless col.always_null?
22
+ next if config.always_keep_columns.include?(col.name)
23
+ next if gem_reserved?(table.name, col.name)
24
+
25
+ finding(
26
+ type: :always_null_column,
27
+ table: table.name,
28
+ column: col.name,
29
+ severity: :high,
30
+ confidence: 0.85,
31
+ bytes_per_row: col.bytes,
32
+ evidence: [
33
+ "pg_stats.null_frac = 1.0 across ~#{table.row_count} row(s)",
34
+ "column carries no data"
35
+ ],
36
+ suggested_fix: "verify with `SELECT count(#{col.name}) FROM #{table.name}` " \
37
+ "then stage a removal"
38
+ )
39
+ end
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SchemaReaper
4
+ module Analyzers
5
+ # Context passed to every analyzer's #call.
6
+ # schema - DatabaseSchema
7
+ # used_tokens - Set<String> from the static scan
8
+ # runtime - Runtime::Report (may be empty)
9
+ # gem_columns - Hash{table_name => Set<column_name>} reserved by gems
10
+ # config - Config
11
+ Context = Struct.new(:schema, :used_tokens, :runtime, :gem_columns, :config, keyword_init: true) do
12
+ def runtime = self[:runtime] || Runtime::Report.empty
13
+ def gem_columns = self[:gem_columns] || {}
14
+ end
15
+
16
+ # Shared plumbing for analyzers: schema access and token lookup helpers.
17
+ class Base
18
+ def self.type
19
+ name.split("::").last.gsub(/([a-z])([A-Z])/, '\1_\2').downcase.to_sym
20
+ end
21
+
22
+ def initialize(context)
23
+ @ctx = context
24
+ end
25
+
26
+ # @return [Array<Finding>]
27
+ def call = raise NotImplementedError
28
+
29
+ private
30
+
31
+ attr_reader :ctx
32
+
33
+ def schema = ctx.schema
34
+ def config = ctx.config
35
+ def runtime = ctx.runtime
36
+ def used?(token) = ctx.used_tokens.include?(token.to_s.downcase)
37
+
38
+ def gem_reserved?(table, column)
39
+ ctx.gem_columns.fetch(table, []).include?(column)
40
+ end
41
+
42
+ # Builds a Finding, filling in reclaimable_bytes from the row count.
43
+ def finding(table:, bytes_per_row: 0, row_count: nil, **rest)
44
+ rows = row_count || schema.table(table)&.row_count || 0
45
+ Finding.new(
46
+ table: table,
47
+ bytes_per_row: bytes_per_row,
48
+ reclaimable_bytes: bytes_per_row * rows,
49
+ **rest
50
+ )
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SchemaReaper
4
+ module Analyzers
5
+ # Flags columns present in the schema but never referenced in code. When a
6
+ # runtime usage log is supplied, its signal is fused in: a column unseen in
7
+ # BOTH code and >= 14 observed days of runtime reaches high confidence.
8
+ class DeadColumn < Base
9
+ Registry.register(self)
10
+
11
+ STATIC_ONLY_CAP = 0.6
12
+ RUNTIME_MIN_DAYS = 14
13
+
14
+ def call
15
+ schema.tables.reject { |t| config.ignore_tables.include?(t.name) }
16
+ .flat_map { |t| dead_in(t) }
17
+ end
18
+
19
+ private
20
+
21
+ def dead_in(table)
22
+ table.columns.filter_map do |col|
23
+ next if keep?(table, col)
24
+ next if used?(col.name)
25
+ next if runtime.read?(table.name, col.name)
26
+
27
+ finding(
28
+ type: :dead_column,
29
+ table: table.name,
30
+ column: col.name,
31
+ severity: col.null ? :medium : :high,
32
+ confidence: confidence_for(col),
33
+ bytes_per_row: col.bytes,
34
+ evidence: evidence_for(table, col),
35
+ suggested_fix: "Stage removal: `self.ignored_columns += %w[#{col.name}]` on the " \
36
+ "model, deploy, then `remove_column :#{table.name}, :#{col.name}`."
37
+ )
38
+ end
39
+ end
40
+
41
+ def keep?(table, col)
42
+ config.always_keep_columns.include?(col.name) ||
43
+ config.ignored_column?(col.name) ||
44
+ col.name == table.primary_key ||
45
+ table.foreign_keys.include?(col.name) ||
46
+ col.name.end_with?("_id", "_type") ||
47
+ gem_reserved?(table.name, col.name)
48
+ end
49
+
50
+ def confidence_for(col)
51
+ if runtime.present? && runtime.observed_days >= RUNTIME_MIN_DAYS
52
+ col.null ? 0.9 : 0.8
53
+ else
54
+ base = col.null ? 0.5 : 0.4
55
+ [base, STATIC_ONLY_CAP].min
56
+ end
57
+ end
58
+
59
+ def evidence_for(table, col)
60
+ ev = ["no `#{col.name}` reference found in scanned code"]
61
+ ev << "column is nullable" if col.null
62
+ ev << if runtime.present?
63
+ "not read in #{runtime.observed_days} observed day(s) of runtime data"
64
+ else
65
+ "static signal only — confidence capped at #{STATIC_ONLY_CAP}"
66
+ end
67
+ ev << "table holds ~#{table.row_count} row(s)" if table.row_count
68
+ ev
69
+ end
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SchemaReaper
4
+ module Analyzers
5
+ # A table with no model reference in code, no runtime access, and (if known)
6
+ # zero rows. Reported as one finding for the whole table.
7
+ class DeadTable < Base
8
+ Registry.register(self)
9
+
10
+ def call
11
+ schema.tables.reject { |t| ignored?(t) }.filter_map { |t| dead(t) }
12
+ end
13
+
14
+ private
15
+
16
+ def ignored?(table)
17
+ config.ignore_tables.include?(table.name) ||
18
+ table.name.start_with?("active_storage_", "action_text_", "action_mailbox_")
19
+ end
20
+
21
+ def dead(table)
22
+ return if referenced?(table)
23
+ return if runtime.accessed.any? { |k| k.start_with?("#{table.name}.") }
24
+
25
+ finding(
26
+ type: :dead_table,
27
+ table: table.name,
28
+ column: nil,
29
+ severity: :high,
30
+ confidence: confidence_for(table),
31
+ bytes_per_row: table.columns.sum(&:bytes),
32
+ evidence: evidence_for(table),
33
+ suggested_fix: "confirm no external consumer, then `drop_table :#{table.name}`"
34
+ )
35
+ end
36
+
37
+ # Match the table name and its singular/camelized model form.
38
+ def referenced?(table)
39
+ singular = table.name.sub(/s\z/, "")
40
+ [table.name, singular, camelize(table.name), camelize(singular)]
41
+ .any? { |form| used?(form) }
42
+ end
43
+
44
+ def confidence_for(table)
45
+ return 0.5 if table.row_count.nil?
46
+
47
+ table.row_count.zero? ? 0.85 : 0.4
48
+ end
49
+
50
+ def evidence_for(table)
51
+ ev = ["no model or query reference to `#{table.name}` in scanned code"]
52
+ ev << "runtime data shows no access" if runtime.present?
53
+ ev << "table holds ~#{table.row_count} row(s)" unless table.row_count.nil?
54
+ ev
55
+ end
56
+
57
+ def camelize(str) = str.split("_").map(&:capitalize).join
58
+ end
59
+ end
60
+ end