sqlite_doctor 0.4.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 9216547333de49de65d7457372ca0d7cca8f946d07ca6759e4314ea2e70cb032
4
+ data.tar.gz: 1649bd84e43bd57f48eba888699f90e8972a503860e0a6460d2d2d7cd7de6691
5
+ SHA512:
6
+ metadata.gz: 785a6319878dd5169160f08606e6ab95255afba016b4b76d67e7f6cedb6f64cd8c3f2e5dd6da3a4feb90a7a4125b258152a120dcc5a54ea49c03a33401849a5c
7
+ data.tar.gz: 713d71ef7cf6b70aae3dcf5177458d3fdfb3dde715afffb91248f172a56dec543a23f94ca64f61d3a9c758a7a82d4c17dd65c71d1c695ecd5c2a0aec22ea0bdc
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Oleksandr Kholodniak
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 all
13
+ 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 THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,326 @@
1
+ # sqlite-doctor
2
+
3
+ Checks SQLite migration SQL for table rebuilds that can delete or change dependent rows, or drop indexes and
4
+ triggers.
5
+
6
+ ```bash
7
+ cargo install sqlite-doctor
8
+ sqlite-doctor migration.sql
9
+ ```
10
+
11
+ Release archives for Linux x86_64 and macOS arm64, with SHA-256 checksums, are on the
12
+ [releases page](https://github.com/kholdrex/sqlite-doctor/releases), and `cargo binstall sqlite-doctor` installs
13
+ one without compiling. In GitHub Actions on those runners:
14
+
15
+ ```yaml
16
+ - uses: kholdrex/sqlite-doctor@v0.3.0 # installs the 0.3.0 binary after checking its SHA-256
17
+ - run: sqlite-doctor --format json migration.sql
18
+ ```
19
+
20
+ Building from source needs Rust 1.88 or newer. Exit code `0` means nothing found, `1` means at least one finding,
21
+ `2` means bad arguments, an unreadable file or an incomplete check (see
22
+ [Directives](#directives-for-migration-adapters)). Add `--format json` for CI, and pass `-` to read from stdin.
23
+
24
+ From Rust, `sqlite_doctor::check_sql` returns the same findings; see the [API docs](https://docs.rs/sqlite-doctor).
25
+
26
+ ## JSON output
27
+
28
+ ```json
29
+ {
30
+ "version": 1,
31
+ "source": "migration.sql",
32
+ "complete": true,
33
+ "incomplete": [],
34
+ "findings": [
35
+ {
36
+ "code": "SQLD003",
37
+ "title": "table rebuild may drop an index or trigger",
38
+ "line": 4,
39
+ "related_line": 1,
40
+ "location": { "source": "migration.sql", "line": 4, "synthetic": false },
41
+ "related_location": { "source": "migration.sql", "line": 1, "synthetic": false },
42
+ "detail": "...",
43
+ "remediation": "..."
44
+ }
45
+ ]
46
+ }
47
+ ```
48
+
49
+ `source` is the path as given, or `-` for stdin. `line` is the one-based line of the statement the finding is
50
+ about, and `related_line` the line of the reference, index or trigger it concerns, or `null`. `location` and
51
+ `related_location` say where those lines came from (see below); without directives they repeat `source` and the
52
+ line. `complete` is `false` when the input marks the check as incomplete, and `incomplete` lists each reason with
53
+ its line. `code` and the meaning of each field are stable within `version` 1. Later releases may add codes and
54
+ fields, so ignore the ones you don't know. `title`, `detail` and `remediation` are text for people and may be
55
+ reworded in any release.
56
+
57
+ ## Directives for migration adapters
58
+
59
+ A migration tool runs more SQL than its migration files hold: it opens the transaction, sets connection state and
60
+ records the migration. An adapter that runs the migrations and hands the executed SQL to `sqlite-doctor` can mark
61
+ where each line came from with comment lines, which SQLite ignores:
62
+
63
+ | Directive | Following lines |
64
+ | --- | --- |
65
+ | `-- sqlite-doctor:file <line> <path>` | come from `<path>`, starting at line `<line>` |
66
+ | `-- sqlite-doctor:migration <name>` | were recorded while migration `<name>` ran, with no file line |
67
+ | `-- sqlite-doctor:synthetic <text>` | were added by the migration runner, for example its `BEGIN` and `COMMIT` |
68
+ | `-- sqlite-doctor:incomplete <reason>` | (none) the check did not see everything, so the exit code is `2` |
69
+
70
+ An origin directive applies until the next one, and directive lines are not counted as lines of the file. A
71
+ directive is a line comment that starts its line, outside any string, quoted identifier or block comment; an unknown
72
+ or malformed `-- sqlite-doctor:` directive makes the check incomplete. Directives only relabel locations or mark the
73
+ check incomplete: no directive removes a finding. Findings are still printed for an incomplete check, but the exit
74
+ code is `2`, so a wrapper must not treat that run as passing. Directives need sqlite-doctor 0.3.0 or newer: older
75
+ versions read them as plain comments, so an adapter should check that the JSON output has a `complete` field.
76
+
77
+ An adapter writes:
78
+
79
+ - each argument on one line: replace line breaks and other control characters in a path, name or reason, or write
80
+ `incomplete` instead of a directive it cannot represent;
81
+ - the starting schema, then the initial `PRAGMA foreign_keys` state of the connection that runs the migrations;
82
+ - the statements that connection ran successfully, in order, including the runner's own transaction and `PRAGMA`
83
+ statements marked `synthetic` or labelled with the migration they run for, each ended outside any comment (as `SqliteDoctor::Capture.terminate` in
84
+ `contrib/rails` does) so a trailing comment cannot swallow what follows;
85
+ - `incomplete` when the migration failed, a statement failed (SQLite can roll back the whole transaction on a
86
+ failure), a statement's outcome is unknown, a second connection ran migration SQL, or the pending migrations are
87
+ not known. No pending migrations is a complete check.
88
+
89
+ A wrapper that pipes an adapter into `sqlite-doctor` must also fail when the adapter exits with an error: a capture
90
+ cut short can look like a complete one. Input that ends inside a string, quoted name or block comment is reported
91
+ as incomplete.
92
+
93
+ A line comment in copied SQL that starts its line with `-- sqlite-doctor:` would be read as a directive. An adapter
94
+ must not rewrite such lines by text alone, because the same text can sit inside a quoted name; the Rails capture
95
+ leaves the SQL as it is and marks the check incomplete instead.
96
+
97
+ ## Why this exists
98
+
99
+ SQLite can't change most column definitions in place, so ORMs rebuild the table: copy the rows out, drop the
100
+ table, create it again, copy the rows back. Dropping the table also fires every `ON DELETE` action that points at
101
+ it. If foreign keys are on, children with `ON DELETE CASCADE` are deleted and children with `ON DELETE SET NULL`
102
+ lose their reference. Turning foreign keys off doesn't help inside a transaction, because SQLite ignores changes
103
+ to `PRAGMA foreign_keys` there.
104
+
105
+ In Rails 8.1.4, with foreign keys on and the default migration transaction, `change_column_null` or
106
+ `remove_column` on a parent table deletes its cascading children. Drizzle ORM 0.45.4 with Kit 0.31.11 does the
107
+ same when a column is made `NOT NULL`. In both, the migration reports success.
108
+
109
+ ## What it reports
110
+
111
+ | Code | Meaning |
112
+ |---|---|
113
+ | `SQLD001` | A table is rebuilt while a table created earlier in the input, or given a column by `ALTER TABLE ... ADD COLUMN`, references it with `ON DELETE CASCADE`, `SET NULL` or `SET DEFAULT`. Reported unless the input turns foreign keys off before the drop, or drops that child table first. |
114
+ | `SQLD002` | `PRAGMA foreign_keys` is changed inside a transaction, where SQLite ignores the change. |
115
+ | `SQLD003` | An index or trigger created on a table before the rebuild is not created again afterwards. |
116
+
117
+ To rebuild a table safely, follow SQLite's order:
118
+
119
+ 1. `PRAGMA foreign_keys = OFF;` before `BEGIN`
120
+ 2. `BEGIN;`, then the rebuild: create the new table under another name, copy the rows, drop the old table, and
121
+ rename the new one. Don't rename the old table away first: SQLite points the references of other tables at
122
+ the renamed table, and they break when it is dropped. Views and triggers on other tables that name the old
123
+ table make the final rename fail. Save the definitions of those views, of views built on them and of triggers
124
+ on any of them, drop them first, and create them again in dependency order before `COMMIT`.
125
+ 3. `PRAGMA foreign_key_check;` and `ROLLBACK;` if it reports anything
126
+ 4. `COMMIT;`
127
+ 5. `PRAGMA foreign_keys = ON;` after `COMMIT`
128
+
129
+ For `SQLD003`, recreate the index or trigger after the rebuild, or drop it first if you meant to remove it. An
130
+ index on a plain column that the rebuilt table no longer has is not reported, because `remove_column` and
131
+ `remove_reference` drop that index on purpose. Expression indexes, and tables whose column list can't be read,
132
+ are still reported.
133
+
134
+ Example that reports `SQLD003`, because SQLite drops `idx_users_email` together with `users`:
135
+
136
+ ```sql
137
+ CREATE INDEX idx_users_email ON users(email);
138
+ CREATE TABLE __new_users(id INTEGER, email TEXT);
139
+ INSERT INTO __new_users SELECT id, email FROM users;
140
+ DROP TABLE users;
141
+ ALTER TABLE __new_users RENAME TO users;
142
+ ```
143
+
144
+ ## Rails
145
+
146
+ A migration file doesn't show the SQL that matters: ActiveRecord opens the transaction, sets `foreign_keys = OFF`
147
+ inside it (which does nothing), and rebuilds the table through a holding copy.
148
+
149
+ Add the gem (from GitHub until it is on RubyGems) and run the check:
150
+
151
+ ```ruby
152
+ gem "sqlite_doctor", github: "kholdrex/sqlite-doctor", group: [:development, :test]
153
+ ```
154
+
155
+ ```bash
156
+ bin/rails sqlite_doctor:check
157
+ ```
158
+
159
+ It needs the `sqlite-doctor` binary, 0.3.0 or newer, on `PATH` or named by `SQLITE_DOCTOR`. If the app itself fails
160
+ to start, Rails ends the command before the check runs, with its own exit code. It prints each finding
161
+ with the migration it came from. It exits `1` with findings and `2` when the check is incomplete or fails; when
162
+ nothing is found it returns, so Rake tasks that depend on it still run. `OUTPUT=tmp/migration.sql` keeps the
163
+ captured SQL; `bin/rails sqlite_doctor:capture OUTPUT=...` only writes it. An app that migrates more than one
164
+ database in the current environment must name one with `DATABASE=<name>`; the others are not checked.
165
+
166
+ In CI the database is usually migrated already, so nothing is pending. Name the commit the change starts from
167
+ instead, from the GitHub event:
168
+
169
+ ```yaml
170
+ - uses: actions/checkout@v4
171
+ with:
172
+ fetch-depth: 0
173
+ - uses: kholdrex/sqlite-doctor@v0.3.0
174
+ - run: bin/rails sqlite_doctor:check
175
+ env:
176
+ BASE: ${{ github.event.pull_request.base.sha || github.event.before }}
177
+ ```
178
+
179
+ On a push that creates a branch, `before` is all zeros and the check fails with exit code `2`; run it on pull
180
+ requests or skip that case. With `BASE`, the database is built from the schema file (`db/schema.rb` or
181
+ `db/structure.sql`) at that commit, and exactly the migration files present there count as applied, so the pending
182
+ migrations are the ones the change adds, whatever their timestamps. The configured database is not used: the
183
+ check refuses to run if another connection pool in the app is open on it, and fails if it changes while migrating,
184
+ but a migration that connects to it on its own still writes to it.
185
+
186
+ That database has the schema but no rows, so the check covers what the migration SQL does, not data. It misses a
187
+ migration whose SQL depends on the rows it finds, and an index, trigger or view the schema file leaves out:
188
+ `db/schema.rb` keeps no triggers or views, so use `structure.sql` if you rely on them. For those cases run the
189
+ check without `BASE` on a copy of a database that has representative rows.
190
+
191
+ The check points ActiveRecord at a `VACUUM INTO` copy of the database and runs your pending migrations there. The
192
+ output holds the current schema, the `foreign_keys` setting and the SQL that ActiveRecord reported for that copy
193
+ while the migrations ran. SQL that a migration sends to another database, or straight to the SQLite driver, is not
194
+ in it. Failed statements are kept as comments, and the capture is marked incomplete (exit code `2`) when a migration
195
+ raised, a statement failed, SQL ran on a second connection to the copy or on another database, the migrating
196
+ connection reconnected or copied SQL has a line starting with `-- sqlite-doctor:`. Tables that still exist but have
197
+ fewer rows at the end are listed in the header. The `sqlite3` gem must be the version your Rails needs (2.1 or newer
198
+ for Rails 8); with another, the check exits with `2`.
199
+
200
+ Before migrating, it refuses to start when:
201
+
202
+ - another connection pool in the app uses the same database file, by path or by `file:` URI;
203
+ - `OUTPUT` names the database or any other database file the app configures or has a pool on (compared without
204
+ case), or ends in `-wal`, `-shm` or `-journal`.
205
+
206
+ It writes `OUTPUT` only if nothing is there or it is a regular file holding an earlier capture. Anything else,
207
+ including an empty file, a symbolic link and a database a migration created at that path, is refused at the write.
208
+
209
+ Only the primary database is copied. A migration that writes through another pool, such as a queue or cache
210
+ database, changes that database for real, and so do other side effects such as HTTP calls or file writes. Run
211
+ those migrations against a disposable configuration. A new capture file is readable only by you; a replaced one
212
+ keeps its group and permissions, or becomes readable only by you if its group can't be kept. The capture can contain literal data from data migrations.
213
+
214
+ A migration that opens its own connection to the original database is not redirected, and it can change that
215
+ database. The task notices afterwards (`PRAGMA data_version`) and fails without writing a capture. A concurrent
216
+ `wal_checkpoint(TRUNCATE)` from another process trips the same check; run the task again.
217
+
218
+ Without Rails, run `ruby contrib/rails/lib/sqlite_doctor/capture.rb DATABASE MIGRATIONS_DIR OUTPUT` from a clone, with
219
+ the `activerecord` and `sqlite3` gems installed. The capture code is tested on ActiveRecord 7.1, 7.2 and 8.1.
220
+
221
+ ## Drizzle
222
+
223
+ With better-sqlite3, Drizzle ORM 0.45.4 runs all pending migration files in one transaction, so a generated file
224
+ alone hides the problem: its `PRAGMA foreign_keys=OFF` looks effective. Scan one input that matches what runs:
225
+
226
+ 1. The starting schema: `CREATE TABLE`, `CREATE INDEX` and `CREATE TRIGGER` statements.
227
+ 2. `PRAGMA foreign_keys = ON;` (better-sqlite3 turns foreign keys on by default).
228
+ 3. One `BEGIN;`, every pending migration file in order, one `COMMIT;`
229
+
230
+ ## Results in the paper
231
+
232
+ The tool is evaluated in "Successful Migrations, Lost Data: Silent Preservation Failures in SQLite Table Rebuilds
233
+ Across Five ORMs". The paper used two builds, kept here as tags:
234
+
235
+ | Tag | Commit | Use in the paper |
236
+ |---|---|---|
237
+ | [`study-original`](https://github.com/kholdrex/sqlite-doctor/tree/study-original) | `a65e428` | The linter in the experiments. It knows the create, copy, drop, rename rebuild and `ON DELETE CASCADE`. |
238
+ | [`study-relint`](https://github.com/kholdrex/sqlite-doctor/tree/study-relint) | `2bf86dc` | A later build run on the same inputs. It adds the Rails rebuild and `SET NULL` and `SET DEFAULT` children. |
239
+
240
+ The [replication package](https://github.com/kholdrex/sqlite-migration-preservation/tree/v1.0.0#linter) has the build
241
+ commands, the hashes of both binaries, the inputs and the results. The READMEs at the two tags are historical: they
242
+ describe an early prototype, and the one at `study-relint` compares the tool with Atlas on inputs the paper does
243
+ not use. For usage read this README on `main`; for results read the package.
244
+
245
+ In the paper's matrix of schema operations, 178 cases lost data without an error and have a trace of the executed
246
+ SQL. Given the starting schema and that trace:
247
+
248
+ | Build | Named the affected dependent table, index or trigger |
249
+ |---|---|
250
+ | `study-original` | 29 of 178 |
251
+ | `study-relint` | 164 of 178 |
252
+
253
+ The rules of the later build were written with these results in view, so its row is not an independent test. It
254
+ named the affected dependent in all 48 Rails 8.1.4 cases. Leaving aside `SQLD002`, which fires on every Rails and
255
+ Drizzle rebuild, it warned on 25 of the 204 rebuilds that lost nothing: 19 that failed and were rolled back, and 6
256
+ Django migrations that remove a unique index on purpose. None of the 25 was a Rails rebuild. The package lists
257
+ each figure with its source file in `paper/numbers.md`; the later build's output is in
258
+ `results/relint-2026-11-01/relint.json`. `main` has changed since `study-relint`; the figures are for the tagged
259
+ builds.
260
+
261
+ ## Limits
262
+
263
+ - It is a lexical scanner for one SQLite input. It does not run SQL, assumes every statement succeeds, and does
264
+ not parse other SQL dialects.
265
+ - Include the starting schema. Tables, indexes and triggers from earlier migrations or the live database are
266
+ invisible otherwise; the Rails task includes them for you.
267
+ - A reference counts from its `CREATE TABLE` or `ALTER TABLE ... ADD COLUMN` until the input drops that child table or the column that declares
268
+ it, and follows both tables through `ALTER TABLE ... RENAME TO`. Rebuilding the child without the foreign key
269
+ clears it the same way. A child created in a transaction that rolls back does not count; a drop that a
270
+ `ROLLBACK` undoes before the parent rebuild does not clear it. When it can't tell whether a drop removed the
271
+ child (a temp table used that name earlier, a rollback names no open savepoint), it keeps warning.
272
+ - It recognises three rebuild shapes: create, copy, drop, rename (Drizzle, SQLite's documented procedure); copy
273
+ out, drop, create again, copy back (Rails); and rename the table away, create it again under the old name, copy,
274
+ drop the renamed table. The third is the order that SQLite's
275
+ [`ALTER TABLE` page](https://www.sqlite.org/lang_altertable.html) warns against: the rename points the children's
276
+ references at the new name, so the drop fires their `ON DELETE` actions and leaves the references on a table
277
+ that is gone. A rebuild is evidence for a finding, not proof of harm: one inside a transaction that later rolls
278
+ back is still reported.
279
+ - The copy is an `INSERT ... SELECT`, with or without a `WITH` clause, an `INSERT ... VALUES` that reads a table
280
+ in a subquery, or a `CREATE TABLE ... AS SELECT`, which creates the table and copies into it in one statement.
281
+ The tables the rows come from are the names that follow `FROM` and `JOIN`; a table named after a comma in a
282
+ `FROM` list is not read. A replacement filled only with literal values reads no table, so dropping the original
283
+ is not reported as a rebuild.
284
+ - `SQLD003` matches objects by schema and name, and an index or trigger stays with its table through a rename.
285
+ Recreating an index under a different name still reports the old one as missing. Recreating it only after the table has been rebuilt again, or in a transaction that rolls back,
286
+ does not count. A `DROP INDEX` or `DROP TRIGGER` that a `ROLLBACK` undoes does not count as removing it. An
287
+ indexed column is followed through `ALTER TABLE ... RENAME COLUMN`; when the rebuild itself renames the column,
288
+ a plain-column index on it counts as removed, so its loss is not reported. `CREATE TABLE ... AS SELECT` lists
289
+ no columns, so an index is reported even when the query leaves its column out. Views are not checked
290
+ because `DROP TABLE` does not drop them.
291
+ - Known gaps, where a rebuild that loses rows is not reported: an `INSERT INTO new AS alias ...` copy or a
292
+ copy `FROM (old)` in parentheses; a temp table that takes the name of a main-schema replacement or original
293
+ during the rebuild; a trigger body that uses `end` as a column name; a referencing column that a rolled-back
294
+ `DROP COLUMN` or a later rename leaves in place; a rename while `legacy_alter_table` is on but never set
295
+ in the input, which is assumed off; either table renamed to an intermediate name during the rebuild; and an
296
+ unqualified `ALTER TABLE ... ADD COLUMN` after `ATTACH` or after a rolled-back `CREATE TEMP TABLE` of that
297
+ name, which may be read as the wrong table. A `CREATE TABLE IF NOT EXISTS` for a table that already exists is
298
+ still read as declaring its references, which can report a rebuild that loses nothing.
299
+
300
+ ## Background
301
+
302
+ - [rails/rails#55866](https://github.com/rails/rails/issues/55866) reported the data loss;
303
+ [#55907](https://github.com/rails/rails/pull/55907) fixed part of it. Rebuilds inside a transaction still lose
304
+ rows on 8.1.4. On 26 November 2026 [#57128](https://github.com/rails/rails/pull/57128) and
305
+ [#58709](https://github.com/rails/rails/pull/58709), which keep the cascades from firing, and
306
+ [#56811](https://github.com/rails/rails/pull/56811), which recreates triggers, were open.
307
+ - [drizzle-team/drizzle-orm#4938](https://github.com/drizzle-team/drizzle-orm/issues/4938) and
308
+ [#5782](https://github.com/drizzle-team/drizzle-orm/issues/5782) report the same cascade loss in Drizzle.
309
+ - [SQLite foreign keys](https://www.sqlite.org/foreignkeys.html): SQLite ignores changes to `PRAGMA foreign_keys`
310
+ inside a transaction.
311
+
312
+ ## Development
313
+
314
+ ```bash
315
+ cargo fmt --all -- --check
316
+ cargo clippy --all-targets --all-features -- -D warnings
317
+ cargo test --all-features
318
+ sh tests/sqlite_outcomes.sh
319
+ cargo build
320
+ AR_VERSION=8.1.4 ruby contrib/rails/test/capture_test.rb
321
+ AR_VERSION=8.1.4 ruby contrib/rails/test/check_test.rb
322
+ AR_VERSION=8.1.4 ruby contrib/rails/test/railtie_test.rb
323
+ ```
324
+
325
+ Each file under `tests/fixtures/sqlite` is a script for the `sqlite3` shell, and its first line records what
326
+ SQLite prints for it. `tests/sqlite_outcomes.sh` checks those lines against the `sqlite3` on your `PATH`.
@@ -0,0 +1,460 @@
1
+ # Runs pending ActiveRecord migrations against a copy of a SQLite database and
2
+ # writes one SQL file for `sqlite-doctor`: the baseline schema, the
3
+ # connection's PRAGMA foreign_keys state, and the SQL ActiveRecord reported
4
+ # while migrating, including transaction boundaries.
5
+ #
6
+ # ActiveRecord::Base is pointed at the copy for the run and restored
7
+ # afterwards. A migration or model that opens its own connection to the
8
+ # original database is not redirected; the capture fails if another connection
9
+ # committed to the original while migrating. A relative database path is
10
+ # resolved like ActiveRecord does: against Rails.root when Rails is loaded.
11
+ #
12
+ # Standalone:
13
+ # ruby capture.rb DATABASE MIGRATIONS_DIR OUTPUT
14
+ # In a Rails app, see lib/tasks/sqlite_doctor.rake.
15
+
16
+ require "active_record"
17
+ require "sqlite3"
18
+ require "tempfile"
19
+ require "tmpdir"
20
+
21
+ module SqliteDoctor
22
+ # Names the migration whose SQL is being recorded, for the directives that
23
+ # point findings at their migration file.
24
+ # Acts only while a capture runs on this thread. Thread variables, unlike
25
+ # Thread.current[], are shared with fibers the migration starts.
26
+ module LabelMigrations
27
+ def self.capturing?
28
+ Thread.current.thread_variable_get(:sqlite_doctor_capturing)
29
+ end
30
+
31
+ def self.current
32
+ Thread.current.thread_variable_get(:sqlite_doctor_migration)
33
+ end
34
+
35
+ def self.labelled(migration)
36
+ previous = current
37
+ name = migration.respond_to?(:filename) ? migration.filename : migration.name
38
+ Thread.current.thread_variable_set(:sqlite_doctor_migration, name)
39
+ yield
40
+ ensure
41
+ Thread.current.thread_variable_set(:sqlite_doctor_migration, previous)
42
+ end
43
+
44
+ private
45
+
46
+ def execute_migration_in_transaction(migration)
47
+ return super unless SqliteDoctor::LabelMigrations.capturing?
48
+
49
+ SqliteDoctor::LabelMigrations.labelled(migration) { super }
50
+ end
51
+ end
52
+ end
53
+
54
+ module SqliteDoctor::Capture
55
+ SIDE_FILES = ["", "-wal", "-shm", "-journal"].freeze
56
+ CAPTURE_HEADER = "-- sqlite-doctor capture:".freeze
57
+ # A line sqlite-doctor could read as a directive. Copied SQL is never
58
+ # rewritten, because the same text can sit inside a quoted name.
59
+ RESERVED_LINE = /^[ \t\f\r\u{feff}]*-- sqlite-doctor:/
60
+
61
+ # A capture that cannot run safely or cannot see what it needs.
62
+ class Refused < RuntimeError; end
63
+
64
+ module_function
65
+
66
+ # name and env_name keep the selected database's identity on the copy.
67
+ # watch: another file that must not change while migrating, such as the
68
+ # configured database when the capture runs on a substitute.
69
+ def capture(config:, migrations_paths:, output:, root: nil, name: nil, env_name: nil, watch: nil)
70
+ database = resolve_database_path(config.fetch(:database).to_s)
71
+ raise ArgumentError, "#{database} does not exist" unless File.file?(database)
72
+ database = File.realpath(database)
73
+ output = File.expand_path(output)
74
+ output = File.join(File.realpath(File.dirname(output)), File.basename(output))
75
+ reject_output_aliasing(database, output)
76
+ reject_other_pools(database)
77
+
78
+ reject_in_memory_connection
79
+ previous_config = current_db_config
80
+ Dir.mktmpdir("sqlite-doctor") do |dir|
81
+ copy = File.join(dir, File.basename(database))
82
+ SQLite3::Database.new(database, readonly: true) do |db|
83
+ db.execute("VACUUM INTO ?", [copy])
84
+ end
85
+
86
+ begin
87
+ ActiveRecord::Base.establish_connection(named_config(config.merge(database: copy), name, env_name))
88
+ copy_pool = ActiveRecord::Base.connection_pool
89
+ connection = base_connection
90
+ unless main_database_path(connection) == File.realpath(copy)
91
+ raise Refused, "refusing to migrate: the connection is not attached to the copy"
92
+ end
93
+
94
+ schema = connection.select_values(<<~SQL)
95
+ SELECT sql FROM sqlite_schema
96
+ WHERE sql IS NOT NULL AND name NOT GLOB 'sqlite_*'
97
+ ORDER BY rowid
98
+ SQL
99
+ foreign_keys = connection.select_value("PRAGMA foreign_keys")
100
+ rows_before = row_counts(connection)
101
+
102
+ # data_version changes when another connection commits to the file,
103
+ # and not when WAL frames are checkpointed (except TRUNCATE).
104
+ watchers = [database, watch].compact.uniq.map do |path|
105
+ watcher = SQLite3::Database.new(path, readonly: true)
106
+ [path, watcher, watcher.get_first_value("PRAGMA data_version")]
107
+ end
108
+ run = run_migrations(migrations_paths, copy_pool, connection)
109
+ statements = run[:statements]
110
+ failures = run[:failures]
111
+ error = run[:error]
112
+ rows_after = row_counts(base_connection)
113
+ watchers.each do |path, watcher, version|
114
+ next if watcher.get_first_value("PRAGMA data_version") == version
115
+
116
+ raise Refused, "#{path} changed while migrating the copy: a migration, model or " \
117
+ "other process committed to it (or ran a TRUNCATE checkpoint)"
118
+ end
119
+ ensure
120
+ watchers&.each { |_, watcher, _| watcher.close }
121
+ restore_connection(previous_config)
122
+ end
123
+
124
+ shrunk = rows_before.filter_map do |table, before|
125
+ after = rows_after[table]
126
+ "#{single_line(table)} #{before} -> #{after}" if after && after < before
127
+ end
128
+ incomplete = []
129
+ # The class only: messages such as StatementInvalid's quote SQL, which
130
+ # can hold data, and this reason is printed.
131
+ incomplete << "the migration raised #{error.class}" if error
132
+ if failures.any?
133
+ incomplete << "#{failures.size} statement(s) failed; a failure can roll back earlier statements"
134
+ end
135
+ incomplete << "migration SQL ran on a second connection to the copy" if run[:other_connection]
136
+ incomplete << "migration SQL ran on another database, which the capture does not record" if run[:other_database]
137
+ if run[:reconnected]
138
+ incomplete << "the migrating connection reconnected, which resets PRAGMA foreign_keys without a trace"
139
+ end
140
+ copied = schema + statements.reject { |_, failed| failed }.map(&:first)
141
+ if copied.any? { |sql| sql.match?(RESERVED_LINE) }
142
+ incomplete << "copied SQL has a line that starts with `-- sqlite-doctor:`"
143
+ end
144
+ write_atomically(output, render(schema, foreign_keys, statements, failures, shrunk, error, incomplete, root))
145
+ { output: output, statements: statements.size - failures.size, failed: failures.size,
146
+ pending: run[:pending]&.map { |name| relative_label(name, root) },
147
+ shrunk_tables: shrunk, error: error, incomplete: incomplete }
148
+ end
149
+ end
150
+
151
+ # Records the SQL the migrating connection ran on the copy. SQL from
152
+ # another connection to the copy has its own transaction and PRAGMA state,
153
+ # so it is left out and the capture is marked incomplete.
154
+ # Rails sets PRAGMA foreign_keys on the raw connection whenever it
155
+ # reconnects, outside the notifications, so a reconnect is recorded.
156
+ # SQL this thread sends to any other database is not recorded either, so
157
+ # it also makes the capture incomplete. Migration announcements are
158
+ # suppressed: they print SQL, which can hold data.
159
+ def run_migrations(migrations_paths, copy_pool, migrating_connection)
160
+ statements = []
161
+ failures = []
162
+ other_connection = false
163
+ other_database = false
164
+ reconnected = false
165
+ pending = nil
166
+ watch_reconnects = Module.new do
167
+ define_method(:configure_connection) do |*arguments, **options, &block|
168
+ reconnected = true
169
+ super(*arguments, **options, &block)
170
+ end
171
+ private :configure_connection
172
+ end
173
+ migrating_connection.singleton_class.prepend(watch_reconnects)
174
+ ActiveRecord::Migrator.prepend(SqliteDoctor::LabelMigrations) unless ActiveRecord::Migrator < SqliteDoctor::LabelMigrations
175
+ subscription = ActiveSupport::Notifications.subscribe("sql.active_record") do |*, payload|
176
+ next if payload[:cached]
177
+
178
+ # From any thread: a migration may hand work to a thread of its own.
179
+ unless payload[:connection]&.pool.equal?(copy_pool)
180
+ other_database = true
181
+ next
182
+ end
183
+
184
+ unless payload[:connection].equal?(migrating_connection)
185
+ other_connection = true
186
+ next
187
+ end
188
+
189
+ # A failed statement did not change the schema, so it must not count as
190
+ # restoring an object. Keep it visible as a comment.
191
+ failures << payload[:sql] if payload[:exception]
192
+ statements << [payload[:sql], !payload[:exception].nil?, SqliteDoctor::LabelMigrations.current]
193
+ end
194
+ Thread.current.thread_variable_set(:sqlite_doctor_capturing, true)
195
+ begin
196
+ context = ActiveRecord::MigrationContext.new(Array(migrations_paths))
197
+ pending = context.open.pending_migrations.map(&:filename)
198
+ ActiveRecord::Migration.suppress_messages { context.migrate }
199
+ error = nil
200
+ rescue StandardError => e
201
+ error = e
202
+ ensure
203
+ Thread.current.thread_variable_set(:sqlite_doctor_capturing, nil)
204
+ ActiveSupport::Notifications.unsubscribe(subscription)
205
+ end
206
+ { statements: statements, failures: failures, error: error, other_connection: other_connection,
207
+ other_database: other_database, reconnected: reconnected, pending: pending }
208
+ end
209
+
210
+ # Switching ActiveRecord::Base to the copy and back reconnects, which
211
+ # discards an in-memory database the caller is using.
212
+ def reject_in_memory_connection
213
+ previous_config = current_db_config
214
+ return unless previous_config
215
+
216
+ in_memory = pool_database_path(previous_config).nil?
217
+ # A connection opened with SQLite's MEMORY flag has a file-like setting.
218
+ in_memory ||= ActiveRecord::Base.connection_pool.connected? && main_database_path(base_connection).nil?
219
+ return unless in_memory
220
+
221
+ raise Refused, "the current connection uses an in-memory database, which switching connections would " \
222
+ "discard; run against a file-backed configuration"
223
+ end
224
+
225
+ def named_config(config, name, env_name)
226
+ return config unless name
227
+
228
+ ActiveRecord::DatabaseConfigurations::HashConfig.new(env_name || "default_env", name, config)
229
+ end
230
+
231
+ def restore_connection(previous_config)
232
+ begin
233
+ ActiveRecord::Base.connection_pool.disconnect!
234
+ rescue ActiveRecord::ConnectionNotEstablished
235
+ nil
236
+ end
237
+ if previous_config
238
+ ActiveRecord::Base.establish_connection(previous_config)
239
+ else
240
+ ActiveRecord::Base.remove_connection
241
+ end
242
+ end
243
+
244
+ def resolve_database_path(path)
245
+ root = defined?(Rails) && Rails.respond_to?(:root) && Rails.root
246
+ File.expand_path(path, root || Dir.pwd)
247
+ end
248
+
249
+ def current_db_config
250
+ ActiveRecord::Base.connection_db_config
251
+ rescue ActiveRecord::ConnectionNotEstablished
252
+ nil
253
+ end
254
+
255
+ def base_connection
256
+ if ActiveRecord::Base.respond_to?(:lease_connection)
257
+ ActiveRecord::Base.lease_connection
258
+ else
259
+ ActiveRecord::Base.connection
260
+ end
261
+ end
262
+
263
+ def main_database_path(connection)
264
+ main = connection.select_rows("PRAGMA database_list").find { |row| row[1] == "main" }
265
+ main && !main[2].to_s.empty? ? File.realpath(main[2]) : nil
266
+ end
267
+
268
+ # Names are compared without case, which some file systems ignore.
269
+ def reject_output_aliasing(database, output)
270
+ if output.match?(/-(wal|shm|journal)\z/i)
271
+ raise ArgumentError, "refusing to write the capture to #{output}: " \
272
+ "SQLite uses names ending in -wal, -shm and -journal"
273
+ end
274
+
275
+ protected_databases(database).each do |path|
276
+ next unless output.casecmp?(path) ||
277
+ (File.exist?(output) && File.exist?(path) && File.identical?(output, path))
278
+
279
+ raise ArgumentError, "refusing to write the capture over #{path}"
280
+ end
281
+ end
282
+
283
+ # The database being migrated and every file the app configures a database
284
+ # at or has a connection pool on, including pools that are not connected
285
+ # yet. Adapter names are not checked: an alias can still open SQLite. A
286
+ # `file:` setting counts both as a URI and as a plain file name, because
287
+ # older sqlite3 gems open it as a plain name.
288
+ def protected_databases(database)
289
+ configs = ActiveRecord::Base.configurations.configs_for(include_hidden: true)
290
+ pools = ActiveRecord::Base.connection_handler.connection_pool_list(:all).map(&:db_config)
291
+ paths = (configs + pools).flat_map do |db_config|
292
+ setting = db_config.database.to_s
293
+ names = [pool_database_path(db_config)]
294
+ names << resolve_database_path(setting) if setting.start_with?("file:")
295
+ names.compact.flat_map do |path|
296
+ directory = File.dirname(path)
297
+ path = File.join(File.realpath(directory), File.basename(path)) if File.directory?(directory)
298
+ File.exist?(path) ? [path, File.realpath(path)] : [path]
299
+ end
300
+ end
301
+ [database, *paths].uniq
302
+ end
303
+
304
+ def reject_other_pools(database)
305
+ base_pool = current_db_config && ActiveRecord::Base.connection_pool
306
+ ActiveRecord::Base.connection_handler.connection_pool_list(:all).each do |pool|
307
+ next if pool.equal?(base_pool)
308
+
309
+ path = pool_database_path(pool.db_config)
310
+ next unless path && File.exist?(path) && File.identical?(path, database)
311
+
312
+ raise Refused, "refusing to migrate: connection pool #{pool.db_config.name} also uses #{database}"
313
+ end
314
+ end
315
+
316
+ # The file a pool's database setting names; nil for an in-memory database.
317
+ def pool_database_path(db_config)
318
+ path = db_config.database.to_s
319
+ return nil if path.empty? || path == ":memory:"
320
+ return resolve_database_path(path) unless path.start_with?("file:")
321
+
322
+ location, query = path.delete_prefix("file:").sub(/#.*\z/m, "").split("?", 2)
323
+ location = location.to_s
324
+ if location.start_with?("//")
325
+ authority, location = location[2..].split("/", 2)
326
+ unless ["", "localhost"].include?(authority.to_s)
327
+ raise Refused, "refusing to migrate: cannot tell which file connection pool " \
328
+ "#{db_config.name} uses (#{path})"
329
+ end
330
+ location = "/#{location}"
331
+ end
332
+ unescape = ->(text) { text.gsub(/%(\h\h)/) { Regexp.last_match(1).hex.chr } }
333
+ location = unescape.call(location)
334
+ return nil if location.empty? || location == ":memory:"
335
+ # With more than one mode parameter the file may still be opened.
336
+ modes = query.to_s.split("&").map(&unescape).select { |parameter| parameter.start_with?("mode=") }
337
+ return nil if modes == ["mode=memory"]
338
+
339
+ # SQLite resolves a relative URI path against the working directory.
340
+ File.expand_path(location)
341
+ end
342
+
343
+ def row_counts(connection)
344
+ tables = connection.select_values(<<~SQL)
345
+ SELECT name FROM sqlite_schema
346
+ WHERE type = 'table' AND name NOT GLOB 'sqlite_*'
347
+ SQL
348
+ tables.to_h do |table|
349
+ [table, connection.select_value("SELECT count(*) FROM #{connection.quote_table_name(table)}")]
350
+ end
351
+ end
352
+
353
+ def render(schema, foreign_keys, statements, failures, shrunk, error, incomplete, root = nil)
354
+ lines = []
355
+ lines << "#{CAPTURE_HEADER} ActiveRecord #{ActiveRecord::VERSION::STRING}, " \
356
+ "SQLite #{SQLite3::SQLITE_VERSION}"
357
+ lines << "-- Migration target: temporary database copy."
358
+ lines << "-- Migration failed: #{single_line("#{error.class}: #{error.message.lines.first&.strip}")}" if error
359
+ incomplete.each { |reason| lines << "-- sqlite-doctor:incomplete #{reason}" }
360
+ lines << "-- #{failures.size} statement(s) failed and are kept below as comments." if failures.any?
361
+ shrunk.each { |line| lines << "-- Observed on the copy: rows in #{line}" }
362
+ lines << ""
363
+ lines << "-- Baseline schema"
364
+ lines << "-- sqlite-doctor:migration schema before migrating"
365
+ schema.each { |sql| lines << terminate(sql) }
366
+ lines << ""
367
+ lines << "-- Connection state before migrating"
368
+ lines << "-- sqlite-doctor:synthetic connection state before migrating"
369
+ lines << "PRAGMA foreign_keys = #{foreign_keys};"
370
+ lines << ""
371
+ lines << "-- Executed statements"
372
+ current = :none
373
+ statements.each do |sql, failed, label|
374
+ if label != current
375
+ lines << (label ? "-- sqlite-doctor:migration #{relative_label(label, root)}" : "-- sqlite-doctor:synthetic ActiveRecord migrator")
376
+ current = label
377
+ end
378
+ lines << (failed ? "-- failed: #{sql.gsub(/\s+/, ' ')}" : terminate(sql))
379
+ end
380
+ lines.join("\n") + "\n"
381
+ end
382
+
383
+ def single_line(text)
384
+ text.gsub(/[[:cntrl:]]+/, " ")
385
+ end
386
+
387
+ # A migration file relative to the application root, on one line.
388
+ def relative_label(path, root = nil)
389
+ root ||= defined?(Rails) && Rails.respond_to?(:root) && Rails.root ? Rails.root.to_s : Dir.pwd
390
+ root = File.realpath(root) if File.directory?(root)
391
+ path = File.expand_path(path, root)
392
+ path = File.realpath(path) if File.exist?(path)
393
+ path = path.delete_prefix("#{root}/") if path.start_with?("#{root}/")
394
+ single_line(path)
395
+ end
396
+
397
+ # SQLite ends a comment at the end of each statement it is given, but here
398
+ # the statements are joined. After a newline, `/**/` closes a block comment
399
+ # left open and is an empty comment otherwise, so the semicolon always ends
400
+ # the statement.
401
+ def terminate(sql)
402
+ sql = sql.sub(/;?\s*\z/, "")
403
+ sql.include?("--") || sql.include?("/*") ? "#{sql}\n/**/;" : "#{sql};"
404
+ end
405
+
406
+ # Tempfile creates the staging file with O_EXCL and mode 0600, so a file or
407
+ # symlink already at that name is never followed or truncated, and removes
408
+ # it afterwards. A new capture is published with a hard link, which fails if
409
+ # anything appeared at OUTPUT meanwhile. Only a regular file holding an
410
+ # earlier capture is replaced, so a database a migration created there or
411
+ # one opened under another name is refused. A replaced capture keeps its
412
+ # group and mode when the group can be kept; the SQL can hold literal data
413
+ # from data migrations.
414
+ def write_atomically(output, content)
415
+ Tempfile.create([File.basename(output), ".tmp"], File.dirname(output)) do |staging|
416
+ staging.write(content)
417
+ staging.close
418
+ if File.symlink?(output)
419
+ raise ArgumentError, "refusing to write the capture over #{output}: it is a symbolic link"
420
+ elsif File.exist?(output)
421
+ unless File.file?(output) &&
422
+ File.open(output, "rb") { |file| file.read(CAPTURE_HEADER.bytesize) } == CAPTURE_HEADER
423
+ raise ArgumentError, "refusing to write the capture over #{output}: it is not an earlier capture"
424
+ end
425
+
426
+ stat = File.stat(output)
427
+ begin
428
+ File.chown(nil, stat.gid, staging.path)
429
+ File.chmod(stat.mode & 0o777, staging.path)
430
+ rescue Errno::EPERM
431
+ nil
432
+ end
433
+ File.rename(staging.path, output)
434
+ else
435
+ begin
436
+ File.link(staging.path, output)
437
+ rescue Errno::EEXIST
438
+ raise ArgumentError, "refusing to write the capture over #{output}: it appeared while migrating"
439
+ end
440
+ end
441
+ end
442
+ end
443
+ end
444
+
445
+ if $PROGRAM_NAME == __FILE__
446
+ database, migrations, output = ARGV
447
+ abort "usage: ruby #{File.basename(__FILE__)} DATABASE MIGRATIONS_DIR OUTPUT" unless output
448
+
449
+ result = SqliteDoctor::Capture.capture(
450
+ config: { adapter: "sqlite3", database: database },
451
+ migrations_paths: migrations,
452
+ output: output
453
+ )
454
+ warn "wrote #{result[:statements]} statements to #{output}"
455
+ result[:shrunk_tables].each { |line| warn "rows lost on the copy: #{line}" }
456
+ if result[:error]
457
+ warn "migration failed: #{result[:error].class}: #{result[:error].message}"
458
+ exit 1
459
+ end
460
+ end
@@ -0,0 +1,254 @@
1
+ # Captures the pending migrations, scans the capture with the sqlite-doctor
2
+ # binary and prints its findings. Returns the binary's exit status: 0 nothing
3
+ # found, 1 findings, 2 an incomplete check or an error.
4
+
5
+ require "json"
6
+ require "open3"
7
+ require "pathname"
8
+ require "tmpdir"
9
+ require_relative "capture"
10
+
11
+ module SqliteDoctor::Check
12
+ class Error < StandardError; end
13
+
14
+ # Rails' migration file name pattern.
15
+ MIGRATION_FILE = /\A([0-9]+)_([_a-z0-9]*)\.?([_a-z0-9]*)?\.rb\z/
16
+
17
+ module_function
18
+
19
+ # base: a git revision. The database is then built from the schema file and
20
+ # the migration files at that revision instead of the configured database.
21
+ def run(config:, migrations_paths:, base: nil, schema_file: nil, schema_format: :ruby,
22
+ root: Dir.pwd, output: nil, binary: nil, io: $stdout, name: nil, env_name: nil)
23
+ binary = find_binary(binary)
24
+ SqliteDoctor::Capture.reject_in_memory_connection
25
+ Dir.mktmpdir("sqlite-doctor-check") do |dir|
26
+ watch = nil
27
+ if base
28
+ watch = protect_configured_database(config)
29
+ config = config.merge(
30
+ database: database_at(base, dir: dir, root: root, schema_file: schema_file,
31
+ schema_format: schema_format, config: config,
32
+ migrations_paths: migrations_paths, name: name, env_name: env_name)
33
+ )
34
+ io.puts "Checking against the schema at #{base} (#{File.basename(schema_file)}, no rows). Findings come " \
35
+ "from the SQL alone: a migration whose SQL depends on rows, or a trigger or view the schema file " \
36
+ "leaves out, is not covered."
37
+ end
38
+ output ||= File.join(dir, "capture.sql")
39
+ result = SqliteDoctor::Capture.capture(config: config, migrations_paths: migrations_paths, output: output,
40
+ root: root, name: name, env_name: env_name, watch: watch)
41
+ report(binary, result, io)
42
+ end
43
+ rescue StandardError, ScriptError => e
44
+ known = e.is_a?(Error) || e.is_a?(SqliteDoctor::Capture::Refused)
45
+ io.puts(known ? "sqlite-doctor: #{e.message}" : "sqlite-doctor: #{e.class}: #{e.message}")
46
+ 2
47
+ end
48
+
49
+ def find_binary(binary)
50
+ binary ||= ENV.fetch("SQLITE_DOCTOR", nil)
51
+ return binary if binary && File.file?(binary) && File.executable?(binary)
52
+ raise Error, "SQLITE_DOCTOR=#{binary} is not an executable file" if binary
53
+
54
+ found = ENV.fetch("PATH", "").split(File::PATH_SEPARATOR).map { |dir| File.join(dir, "sqlite-doctor") }
55
+ .find { |path| File.file?(path) && File.executable?(path) }
56
+ found || raise(Error, "the sqlite-doctor binary is not on PATH; install it with `cargo install sqlite-doctor`, " \
57
+ "the kholdrex/sqlite-doctor GitHub Action or a release archive, or set SQLITE_DOCTOR")
58
+ end
59
+
60
+ def report(binary, result, io)
61
+ stdout, stderr, status = Open3.capture3(binary, "--format", "json", result[:output])
62
+ report = begin
63
+ JSON.parse(stdout)
64
+ rescue JSON::ParserError
65
+ nil
66
+ end
67
+ unless report.is_a?(Hash) && report.key?("complete")
68
+ detail = stderr.strip.empty? ? "" : ": #{stderr.strip}"
69
+ raise Error, "#{binary} did not produce sqlite-doctor 0.3.0 JSON output; 0.3.0 or newer is needed#{detail}"
70
+ end
71
+
72
+ pending = result[:pending]
73
+ if pending.nil?
74
+ io.puts "The pending migrations could not be determined."
75
+ elsif pending.empty?
76
+ io.puts "No pending migrations."
77
+ else
78
+ io.puts "#{pending.size} pending migration(s):"
79
+ pending.each { |name| io.puts " #{name}" }
80
+ end
81
+ report["findings"].each do |finding|
82
+ io.puts
83
+ io.puts "#{finding['code']}: #{finding['title']}"
84
+ io.puts " --> #{location(finding['location'])} (#{report['source']}:#{finding['line']})"
85
+ io.puts " #{finding['detail']}"
86
+ io.puts " help: #{finding['remediation']}"
87
+ end
88
+ result[:shrunk_tables].each { |line| io.puts "Rows lost on the copy: #{line}" }
89
+ unless report["complete"]
90
+ io.puts
91
+ io.puts "Check incomplete:"
92
+ report["incomplete"].each { |item| io.puts "- #{item['reason']}" }
93
+ end
94
+ if result[:error]
95
+ io.puts "Migration failed on the copy: #{result[:error].class}. Its message can quote SQL with data, so it " \
96
+ "is only in the capture: rerun with OUTPUT=<file> to keep it."
97
+ end
98
+
99
+ status = status.exitstatus
100
+ return 2 if status.nil? || status > 1 || !report["complete"]
101
+
102
+ status
103
+ end
104
+
105
+ def location(location)
106
+ return location["source"] unless location["line"]
107
+
108
+ "#{location['source']}:#{location['line']}"
109
+ end
110
+
111
+ # With BASE the configured database is replaced by a temporary one, so a
112
+ # model connected to it on its own pool would write to it for real. Returns
113
+ # the file to watch while migrating, if it exists.
114
+ def protect_configured_database(config)
115
+ db_config = ActiveRecord::DatabaseConfigurations::HashConfig.new("check", "primary", config)
116
+ path = SqliteDoctor::Capture.pool_database_path(db_config)
117
+ return unless path && File.exist?(path)
118
+
119
+ path = File.realpath(path)
120
+ SqliteDoctor::Capture.reject_other_pools(path)
121
+ path
122
+ end
123
+
124
+ # A SQLite database with the schema at `base` and the migrations of `base`
125
+ # recorded as applied, so the pending migrations are the ones added since.
126
+ def database_at(base, dir:, root:, schema_file:, schema_format:, config:, migrations_paths:, name: nil,
127
+ env_name: nil)
128
+ raise Error, "BASE must name a git revision" if base.empty? || base.start_with?("-") || base.match?(/[[:cntrl:]]/)
129
+ raise Error, "no schema file is configured" unless schema_file
130
+
131
+ top = git(root, "rev-parse", "--show-toplevel").chomp
132
+ prefix = git(root, "rev-parse", "--show-prefix").chomp
133
+ commit = git(top, "rev-parse", "--verify", "--end-of-options", "#{base}^{commit}").chomp
134
+ application = File.expand_path(root)
135
+ # Relative to the repository: the application's prefix from git, then the
136
+ # path from the application, which may lead to a sibling directory.
137
+ in_repository = lambda do |path|
138
+ from_application = Pathname(File.expand_path(path, application)).relative_path_from(Pathname(application))
139
+ relative = Pathname(prefix).join(from_application).cleanpath.to_s
140
+ raise Error, "#{path} is outside the git repository" if relative == ".." || relative.start_with?("../")
141
+
142
+ relative
143
+ end
144
+
145
+ schema_path = in_repository.call(schema_file)
146
+ entry = git(top, "ls-tree", "-z", commit, "--", ":(literal)#{schema_path}").split("\0").first
147
+ raise Error, "#{schema_path} does not exist at #{base}" unless entry
148
+
149
+ mode, type, object = entry.split("\t", 2).first.split(" ")
150
+ if mode == "120000"
151
+ raise Error, "#{schema_path} is a symbolic link at #{base}; point the schema setting at the file itself"
152
+ end
153
+ raise Error, "#{schema_path} is not a file at #{base}" unless type == "blob"
154
+
155
+ schema = git(top, "cat-file", "blob", object)
156
+ # Rails finds migrations with Dir["#{path}/**/[0-9]*_*.rb"], which skips
157
+ # hidden files and directories.
158
+ versions = Array(migrations_paths).flat_map do |path|
159
+ raise Error, "migrations path #{path} is a glob pattern, which BASE does not support" if path.to_s.match?(/[*?\[{]/)
160
+
161
+ directory = in_repository.call(path)
162
+ git(top, "ls-tree", "-r", "-z", "--name-only", commit, "--", ":(literal)#{directory}/")
163
+ .split("\0").filter_map do |entry|
164
+ parts = entry.delete_prefix("#{directory}/").split("/")
165
+ next if parts.any? { |part| part.start_with?(".") }
166
+
167
+ parts.last[MIGRATION_FILE, 1]
168
+ end
169
+ end
170
+
171
+ database = File.join(dir, "base.sqlite3")
172
+ if schema_format.to_sym == :sql
173
+ SQLite3::Database.new(database) { |db| load_structure(db, schema) }
174
+ else
175
+ load_ruby_schema(schema, database, dir, config, migrations_paths, name, env_name)
176
+ end
177
+ reset_ledger(database, versions)
178
+ database
179
+ end
180
+
181
+ # The table Rails reads applied migrations from, with any prefix or suffix.
182
+ def reset_ledger(database, versions)
183
+ ledger = "#{ActiveRecord::Base.table_name_prefix}#{ActiveRecord::Base.schema_migrations_table_name}" \
184
+ "#{ActiveRecord::Base.table_name_suffix}"
185
+ quoted = %("#{ledger.gsub('"', '""')}")
186
+ SQLite3::Database.new(database) do |db|
187
+ db.execute("CREATE TABLE IF NOT EXISTS #{quoted} (version varchar NOT NULL PRIMARY KEY)")
188
+ db.execute("DELETE FROM #{quoted}")
189
+ versions.uniq.each { |version| db.execute("INSERT INTO #{quoted} (version) VALUES (?)", [version]) }
190
+ end
191
+ end
192
+
193
+ # schema.rb marks migrations up to its version as applied; reset_ledger
194
+ # replaces that list with the migrations at the base revision.
195
+ # A table definition at the start of the remaining dump, with no quoted
196
+ # text inside, as the sqlite3 shell writes the tables SQLite creates itself.
197
+ TABLE_DEFINITION = /\A\s*CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`\[']?(\w+)["`\]']?\s*\([^;'"`]*\)\s*;/i
198
+ ONLY_COMMENTS = %r{\A(?:\s|--[^\n]*(?:\n|\z)|/\*.*?\*/)*\z}m
199
+
200
+ # Runs a structure dump one statement at a time, with SQLite finding each
201
+ # statement's end. Skips tables SQLite creates itself: reserved sqlite_*
202
+ # tables and the shadow tables of a virtual table already created. SQLite
203
+ # rejects both while preparing them.
204
+ def load_structure(db, schema)
205
+ rest = schema
206
+ until rest.match?(ONLY_COMMENTS)
207
+ begin
208
+ statement = db.prepare(rest)
209
+ rescue SQLite3::SQLException => e
210
+ table = rest.match(TABLE_DEFINITION)
211
+ raise unless table && created_by_sqlite?(db, table[1], e.message)
212
+
213
+ rest = table.post_match
214
+ next
215
+ end
216
+ begin
217
+ rest = statement.remainder
218
+ statement.execute!
219
+ ensure
220
+ statement.close
221
+ end
222
+ end
223
+ end
224
+
225
+ def created_by_sqlite?(db, table, message)
226
+ return table.downcase.start_with?("sqlite_") if message.include?("reserved for internal use")
227
+ return false unless message.include?("already exists")
228
+
229
+ db.execute("SELECT name FROM sqlite_schema WHERE type = 'table' AND sql LIKE 'CREATE VIRTUAL TABLE%'")
230
+ .flatten.any? { |virtual| table.start_with?("#{virtual}_") }
231
+ end
232
+
233
+ def load_ruby_schema(schema, database, dir, config, migrations_paths, name, env_name)
234
+ file = File.join(dir, "schema.rb")
235
+ File.write(file, schema)
236
+ previous = SqliteDoctor::Capture.current_db_config
237
+ begin
238
+ ActiveRecord::Base.establish_connection(
239
+ SqliteDoctor::Capture.named_config(config.merge(database: database, migrations_paths: migrations_paths),
240
+ name, env_name)
241
+ )
242
+ ActiveRecord::Migration.suppress_messages { load(file) }
243
+ ensure
244
+ SqliteDoctor::Capture.restore_connection(previous)
245
+ end
246
+ end
247
+
248
+ def git(directory, *arguments)
249
+ stdout, stderr, status = Open3.capture3("git", "-C", directory.to_s, *arguments, binmode: true)
250
+ raise Error, "git #{arguments.first} failed: #{stderr.strip}" unless status.success?
251
+
252
+ stdout.force_encoding(Encoding::UTF_8)
253
+ end
254
+ end
@@ -0,0 +1,7 @@
1
+ module SqliteDoctor
2
+ class Railtie < Rails::Railtie
3
+ rake_tasks do
4
+ load File.expand_path("../tasks/sqlite_doctor.rake", __dir__)
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,3 @@
1
+ module SqliteDoctor
2
+ VERSION = "0.4.0".freeze
3
+ end
@@ -0,0 +1,4 @@
1
+ require_relative "sqlite_doctor/version"
2
+ require_relative "sqlite_doctor/capture"
3
+ require_relative "sqlite_doctor/check"
4
+ require_relative "sqlite_doctor/railtie" if defined?(Rails::Railtie)
@@ -0,0 +1,115 @@
1
+ # bin/rails sqlite_doctor:check [BASE=<git revision>] [DATABASE=<name>] [OUTPUT=tmp/migration.sql]
2
+ # Runs the pending migrations on a copy of the SQLite database, or with BASE
3
+ # on a database built from the schema at that revision, and scans the SQL
4
+ # with the sqlite-doctor binary. Exits 1 with findings and 2 when the check
5
+ # is incomplete or fails; on success it returns, so later tasks still run.
6
+ # bin/rails sqlite_doctor:capture [DATABASE=<name>] [OUTPUT=tmp/migration.sql]
7
+ # Only writes the captured SQL.
8
+
9
+ module SqliteDoctor
10
+ module Tasks
11
+ module_function
12
+
13
+ # The database to check: DATABASE, or the only one in this environment
14
+ # whose migrations Rails runs.
15
+ def db_config
16
+ configs = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env).reject(&:replica?)
17
+ configs = configs.select(&:database_tasks?) if configs.first.respond_to?(:database_tasks?)
18
+ name = ENV["DATABASE"].to_s.strip
19
+ config =
20
+ if !name.empty?
21
+ configs.find { |candidate| candidate.name == name } ||
22
+ raise(SqliteDoctor::Check::Error, "no database named #{name} in #{Rails.env}")
23
+ elsif configs.empty?
24
+ raise SqliteDoctor::Check::Error, "no database to migrate is configured for #{Rails.env}"
25
+ elsif configs.size == 1
26
+ configs.first
27
+ else
28
+ raise SqliteDoctor::Check::Error,
29
+ "#{Rails.env} migrates #{configs.size} databases (#{configs.map(&:name).join(', ')}); " \
30
+ "choose one with DATABASE=<name>"
31
+ end
32
+ unless config.adapter == "sqlite3"
33
+ raise SqliteDoctor::Check::Error, "#{config.name} uses the #{config.adapter} adapter; only sqlite3 is supported"
34
+ end
35
+
36
+ config
37
+ end
38
+
39
+ def migrations_paths(config)
40
+ config.migrations_paths || ActiveRecord::Migrator.migrations_paths
41
+ end
42
+
43
+ def schema_format(config)
44
+ config.respond_to?(:schema_format) ? config.schema_format : ActiveRecord.schema_format
45
+ end
46
+
47
+ # The database file, resolved like Rails: a relative path against
48
+ # Rails.root. Which file a `file:` URI opens depends on the sqlite3 gem,
49
+ # so those are refused rather than guessed.
50
+ def database_file(config)
51
+ if config.database.to_s.start_with?("file:")
52
+ raise SqliteDoctor::Check::Error, "#{config.name} is a file: URI; set a plain path, or use BASE"
53
+ end
54
+
55
+ SqliteDoctor::Capture.pool_database_path(config) ||
56
+ raise(SqliteDoctor::Check::Error, "#{config.name} is not a file-backed database")
57
+ end
58
+
59
+ def fail_with(error)
60
+ warn "sqlite-doctor: #{error.message}"
61
+ exit 2
62
+ end
63
+ end
64
+ end
65
+
66
+ namespace :sqlite_doctor do
67
+ desc "Check pending migrations for SQLite rebuilds that lose rows (BASE=git revision, DATABASE=name, OUTPUT=file)"
68
+ task check: "db:load_config" do
69
+ status =
70
+ begin
71
+ config = SqliteDoctor::Tasks.db_config
72
+ base = ENV["BASE"].to_s.strip
73
+ base = nil if base.empty?
74
+ format = SqliteDoctor::Tasks.schema_format(config)
75
+ settings = config.configuration_hash
76
+ settings = settings.merge(database: SqliteDoctor::Tasks.database_file(config)) unless base
77
+ SqliteDoctor::Check.run(
78
+ config: settings,
79
+ migrations_paths: SqliteDoctor::Tasks.migrations_paths(config),
80
+ base: base,
81
+ schema_file: ActiveRecord::Tasks::DatabaseTasks.schema_dump_path(config, format),
82
+ schema_format: format,
83
+ root: Rails.root.to_s,
84
+ output: ENV["OUTPUT"],
85
+ name: config.name,
86
+ env_name: config.env_name
87
+ )
88
+ rescue SqliteDoctor::Check::Error, SqliteDoctor::Capture::Refused, ArgumentError => e
89
+ SqliteDoctor::Tasks.fail_with(e)
90
+ end
91
+ exit status unless status.zero?
92
+ end
93
+
94
+ desc "Run pending migrations on a copy of the SQLite database and write the SQL for sqlite-doctor"
95
+ task capture: "db:load_config" do
96
+ config = SqliteDoctor::Tasks.db_config
97
+ output = ENV.fetch("OUTPUT", "tmp/sqlite-doctor-capture.sql")
98
+ result = SqliteDoctor::Capture.capture(
99
+ config: config.configuration_hash.merge(database: SqliteDoctor::Tasks.database_file(config)),
100
+ migrations_paths: SqliteDoctor::Tasks.migrations_paths(config),
101
+ output: output,
102
+ root: Rails.root.to_s,
103
+ name: config.name,
104
+ env_name: config.env_name
105
+ )
106
+ puts "Wrote #{result[:statements]} statements to #{output}"
107
+ result[:shrunk_tables].each { |line| puts "Rows lost on the copy: #{line}" }
108
+ if result[:error]
109
+ SqliteDoctor::Tasks.fail_with(SqliteDoctor::Check::Error.new("the migration raised #{result[:error].class}; " \
110
+ "its message is in #{output}"))
111
+ end
112
+ rescue SqliteDoctor::Check::Error, SqliteDoctor::Capture::Refused, ArgumentError => e
113
+ SqliteDoctor::Tasks.fail_with(e)
114
+ end
115
+ end
metadata ADDED
@@ -0,0 +1,96 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: sqlite_doctor
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.4.0
5
+ platform: ruby
6
+ authors:
7
+ - Alex Kholodniak
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-11-28 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activerecord
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '7.1'
20
+ - - "<"
21
+ - !ruby/object:Gem::Version
22
+ version: '9'
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - ">="
28
+ - !ruby/object:Gem::Version
29
+ version: '7.1'
30
+ - - "<"
31
+ - !ruby/object:Gem::Version
32
+ version: '9'
33
+ - !ruby/object:Gem::Dependency
34
+ name: sqlite3
35
+ requirement: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '1.4'
40
+ - - "<"
41
+ - !ruby/object:Gem::Version
42
+ version: '3'
43
+ type: :runtime
44
+ prerelease: false
45
+ version_requirements: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: '1.4'
50
+ - - "<"
51
+ - !ruby/object:Gem::Version
52
+ version: '3'
53
+ description: Runs pending migrations on a copy of the SQLite database, records the
54
+ SQL ActiveRecord ran, and scans it with the sqlite-doctor binary. Adds bin/rails
55
+ sqlite_doctor:check.
56
+ email:
57
+ executables: []
58
+ extensions: []
59
+ extra_rdoc_files: []
60
+ files:
61
+ - LICENSE
62
+ - README.md
63
+ - contrib/rails/lib/sqlite_doctor.rb
64
+ - contrib/rails/lib/sqlite_doctor/capture.rb
65
+ - contrib/rails/lib/sqlite_doctor/check.rb
66
+ - contrib/rails/lib/sqlite_doctor/railtie.rb
67
+ - contrib/rails/lib/sqlite_doctor/version.rb
68
+ - contrib/rails/lib/tasks/sqlite_doctor.rake
69
+ homepage: https://github.com/kholdrex/sqlite-doctor
70
+ licenses:
71
+ - MIT
72
+ metadata:
73
+ source_code_uri: https://github.com/kholdrex/sqlite-doctor
74
+ changelog_uri: https://github.com/kholdrex/sqlite-doctor/blob/main/CHANGELOG.md
75
+ rubygems_mfa_required: 'true'
76
+ post_install_message:
77
+ rdoc_options: []
78
+ require_paths:
79
+ - contrib/rails/lib
80
+ required_ruby_version: !ruby/object:Gem::Requirement
81
+ requirements:
82
+ - - ">="
83
+ - !ruby/object:Gem::Version
84
+ version: '3.1'
85
+ required_rubygems_version: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ requirements: []
91
+ rubygems_version: 3.5.9
92
+ signing_key:
93
+ specification_version: 4
94
+ summary: Checks pending ActiveRecord migrations for SQLite table rebuilds that delete
95
+ or change rows
96
+ test_files: []