@skilldeck/migrate 0.1.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.
@@ -0,0 +1,335 @@
1
+ #!/usr/bin/env node
2
+ // migrate / upgrade-report.mjs
3
+ //
4
+ // Deterministic groundwork for dependency upgrades in JS/TS projects.
5
+ //
6
+ // node upgrade-report.mjs outdated [--dir D] [--offline] [--json] what is behind, ordered into upgrade steps
7
+ // node upgrade-report.mjs diff [--base REF] [--dir D] [--json] what the lockfile actually changed
8
+ // node upgrade-report.mjs usages <pkg> [--dir D] [--json] every import of <pkg> and the names used
9
+ //
10
+ // Zero dependencies. Node 20+. Needs git for `diff`, and npm or pnpm for `outdated`.
11
+
12
+ import fs from 'node:fs'
13
+ import path from 'node:path'
14
+ import { spawnSync } from 'node:child_process'
15
+ import { pathToFileURL } from 'node:url'
16
+
17
+ const HELP = `upgrade-report: groundwork for dependency upgrades
18
+
19
+ outdated [--dir D] [--offline] [--json]
20
+ Packages behind their latest version, classed patch/minor/major, with the
21
+ number of files importing each major and its release-notes URL.
22
+ diff [--base REF] [--dir D] [--json]
23
+ Direct dependencies whose resolved version changed between REF (default HEAD)
24
+ and the working tree. Reads package-lock.json or pnpm-lock.yaml; falls back
25
+ to package.json ranges.
26
+ usages <pkg> [--dir D] [--json]
27
+ Every file importing <pkg> (or a subpath), with the imported names, so you
28
+ can check each one against the changelog's breaking changes.
29
+ `
30
+
31
+ // ---------------------------------------------------------------------------
32
+ // Versions
33
+ // ---------------------------------------------------------------------------
34
+
35
+ export function parseVersion(v) {
36
+ const m = String(v ?? '').match(/(\d+)(?:\.(\d+))?(?:\.(\d+))?/)
37
+ return m ? [Number(m[1]), Number(m[2] ?? 0), Number(m[3] ?? 0)] : null
38
+ }
39
+
40
+ /** 'major' | 'minor' | 'patch' | 'none'. In 0.x, a minor bump is breaking under semver, so it counts as major. */
41
+ export function classifyJump(from, to) {
42
+ const a = parseVersion(from)
43
+ const b = parseVersion(to)
44
+ if (!a || !b) return 'unknown'
45
+ if (a[0] !== b[0]) return 'major'
46
+ if (a[1] !== b[1]) return a[0] === 0 ? 'major' : 'minor'
47
+ if (a[2] !== b[2]) return a[0] === 0 && a[1] === 0 ? 'major' : 'patch'
48
+ return 'none'
49
+ }
50
+
51
+ // ---------------------------------------------------------------------------
52
+ // Lockfiles
53
+ // ---------------------------------------------------------------------------
54
+
55
+ /** Direct dependency -> resolved version, from package-lock.json v2/v3 text. */
56
+ export function readNpmLock(text) {
57
+ const lock = JSON.parse(text)
58
+ const root = lock.packages?.[''] ?? {}
59
+ const direct = { ...root.dependencies, ...root.devDependencies, ...root.optionalDependencies }
60
+ const out = {}
61
+ for (const name of Object.keys(direct)) {
62
+ const v = lock.packages?.[`node_modules/${name}`]?.version ?? lock.dependencies?.[name]?.version
63
+ if (v) out[name] = v
64
+ }
65
+ return out
66
+ }
67
+
68
+ /** Direct dependency -> resolved version, from the root importer of pnpm-lock.yaml (v6-v9). */
69
+ export function readPnpmLock(text) {
70
+ const out = {}
71
+ const lines = text.split('\n')
72
+ let inImporters = false
73
+ let inRoot = false
74
+ let inDeps = false
75
+ let current = null
76
+ for (const line of lines) {
77
+ if (/^\S/.test(line)) { inImporters = line.startsWith('importers:'); inRoot = false; inDeps = false; continue }
78
+ if (!inImporters) continue
79
+ if (/^ {2}\S/.test(line)) { inRoot = /^ {2}['"]?\.['"]?:\s*$/.test(line); inDeps = false; continue }
80
+ if (!inRoot) continue
81
+ if (/^ {4}\S/.test(line)) { inDeps = /^ {4}(dependencies|devDependencies|optionalDependencies):/.test(line); continue }
82
+ if (!inDeps) continue
83
+ const name = line.match(/^ {6}['"]?([^'":]+(?::[^'":]+)?)['"]?:\s*$/)
84
+ if (name) { current = name[1]; continue }
85
+ const ver = line.match(/^ {8}version:\s*['"]?([^'"\s(]+)/)
86
+ if (ver && current) { out[current] = ver[1]; current = null }
87
+ }
88
+ return out
89
+ }
90
+
91
+ function readPackageJsonRanges(text) {
92
+ const pkg = JSON.parse(text)
93
+ return { ...pkg.dependencies, ...pkg.devDependencies, ...pkg.optionalDependencies }
94
+ }
95
+
96
+ function git(dir, args) {
97
+ const r = spawnSync('git', args, { cwd: dir, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 })
98
+ return r.status === 0 ? r.stdout : null
99
+ }
100
+
101
+ function lockSnapshot(dir, ref) {
102
+ const read = (file) => (ref ? git(dir, ['show', `${ref}:./${file}`]) : fs.existsSync(path.join(dir, file)) ? fs.readFileSync(path.join(dir, file), 'utf8') : null)
103
+ const npm = read('package-lock.json')
104
+ if (npm) return { source: 'package-lock.json', versions: readNpmLock(npm) }
105
+ const pnpm = read('pnpm-lock.yaml')
106
+ if (pnpm) return { source: 'pnpm-lock.yaml', versions: readPnpmLock(pnpm) }
107
+ const pkg = read('package.json')
108
+ if (pkg) return { source: 'package.json (ranges)', versions: readPackageJsonRanges(pkg) }
109
+ return null
110
+ }
111
+
112
+ export function diffVersions(before, after) {
113
+ const names = [...new Set([...Object.keys(before), ...Object.keys(after)])].sort()
114
+ const changes = []
115
+ for (const name of names) {
116
+ const from = before[name]
117
+ const to = after[name]
118
+ if (from === to) continue
119
+ changes.push({ name, from: from ?? null, to: to ?? null, jump: !from ? 'added' : !to ? 'removed' : classifyJump(from, to) })
120
+ }
121
+ return changes
122
+ }
123
+
124
+ // ---------------------------------------------------------------------------
125
+ // Usages
126
+ // ---------------------------------------------------------------------------
127
+
128
+ const SOURCE_EXT = /\.(m?[jt]sx?|cjs|cts|vue|svelte|astro|py)$/
129
+ const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', 'out', '.next', '.nuxt', '.svelte-kit', 'coverage', '.venv', 'venv', '__pycache__', '.turbo'])
130
+
131
+ function sourceFiles(dir) {
132
+ const files = []
133
+ const walk = (d) => {
134
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
135
+ if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name) && !e.name.startsWith('.')) walk(path.join(d, e.name)) }
136
+ else if (SOURCE_EXT.test(e.name)) files.push(path.join(d, e.name))
137
+ }
138
+ }
139
+ walk(dir)
140
+ return files.sort()
141
+ }
142
+
143
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')
144
+
145
+ /** Imports of `pkg` in one file's text: [{ line, spec, names }]. */
146
+ export function findImports(text, pkg, { python = false } = {}) {
147
+ const hits = []
148
+ const spec = `${esc(pkg)}(?:/[^'"\`]*)?`
149
+ const patterns = python
150
+ ? [new RegExp(String.raw`^\s*from\s+(${esc(pkg)}(?:\.[\w.]+)?)\s+import\s+\(?([^)\n]+)`, 'gm'), new RegExp(String.raw`^\s*import\s+(${esc(pkg)}(?:\.[\w.]+)?)(?:\s+as\s+(\w+))?`, 'gm')]
151
+ : [
152
+ new RegExp(String.raw`\bimport\s+(?:type\s+)?([\w*${'$'}\s{},]+?)\s+from\s+['"](${spec})['"]`, 'g'),
153
+ new RegExp(String.raw`\bexport\s+(?:type\s+)?([\w*${'$'}\s{},]+?)\s+from\s+['"](${spec})['"]`, 'g'),
154
+ new RegExp(String.raw`\bimport\s+['"](${spec})['"]`, 'g'),
155
+ new RegExp(String.raw`\b(?:require|import)\s*\(\s*['"](${spec})['"]\s*\)`, 'g'),
156
+ ]
157
+ for (const re of patterns) {
158
+ for (const m of text.matchAll(re)) {
159
+ const line = text.slice(0, m.index).split('\n').length
160
+ let names = []
161
+ let from
162
+ if (python) {
163
+ from = m[1]
164
+ names = /^\s*from\b/.test(m[0]) ? m[2].split(',').map((n) => n.trim().split(/\s+as\s+/)[0]).filter(Boolean) : [from]
165
+ } else if (m.length === 3) {
166
+ from = m[2]
167
+ names = parseClause(m[1])
168
+ } else {
169
+ from = m[1]
170
+ names = ['(side effect or dynamic)']
171
+ }
172
+ hits.push({ line, spec: from, names })
173
+ }
174
+ }
175
+ return hits.sort((a, b) => a.line - b.line)
176
+ }
177
+
178
+ function parseClause(clause) {
179
+ const names = []
180
+ const braces = clause.match(/\{([^}]*)\}/)
181
+ if (braces) {
182
+ for (const part of braces[1].split(',')) {
183
+ const n = part.trim().replace(/^type\s+/, '').split(/\s+as\s+/)[0]
184
+ if (n) names.push(n)
185
+ }
186
+ }
187
+ const outside = clause.replace(/\{[^}]*\}/, '').split(',').map((s) => s.trim()).filter(Boolean)
188
+ for (const o of outside) names.push(o.startsWith('*') ? '* (namespace)' : 'default')
189
+ return names
190
+ }
191
+
192
+ /** JS files are searched for `pkg`; Python files for its module name (dashes become underscores). */
193
+ export function usages(dir, pkg) {
194
+ const files = []
195
+ const symbols = {}
196
+ for (const file of sourceFiles(dir)) {
197
+ const python = file.endsWith('.py')
198
+ const name = python ? pkg.replace(/-/g, '_') : pkg
199
+ if (python && !/^[\w.]+$/.test(name)) continue
200
+ const text = fs.readFileSync(file, 'utf8')
201
+ if (!text.includes(name)) continue
202
+ const hits = findImports(text, name, { python })
203
+ if (!hits.length) continue
204
+ files.push({ file: path.relative(dir, file), hits })
205
+ for (const h of hits) for (const n of h.names) symbols[`${h.spec} :: ${n}`] = (symbols[`${h.spec} :: ${n}`] ?? 0) + 1
206
+ }
207
+ return { pkg, files, symbols: Object.entries(symbols).sort((a, b) => b[1] - a[1]).map(([k, count]) => ({ symbol: k, count })) }
208
+ }
209
+
210
+ // ---------------------------------------------------------------------------
211
+ // Outdated
212
+ // ---------------------------------------------------------------------------
213
+
214
+ function detectManager(dir) {
215
+ if (fs.existsSync(path.join(dir, 'pnpm-lock.yaml'))) return 'pnpm'
216
+ if (fs.existsSync(path.join(dir, 'package-lock.json'))) return 'npm'
217
+ if (fs.existsSync(path.join(dir, 'yarn.lock'))) return 'yarn'
218
+ if (fs.existsSync(path.join(dir, 'bun.lock')) || fs.existsSync(path.join(dir, 'bun.lockb'))) return 'bun'
219
+ return 'npm'
220
+ }
221
+
222
+ function runOutdated(dir, manager) {
223
+ const cmd = manager === 'pnpm' ? ['pnpm', ['outdated', '--format', 'json']] : ['npm', ['outdated', '--json', '--long']]
224
+ if (manager === 'yarn' || manager === 'bun') {
225
+ throw new Error(`${manager} has no stable JSON outdated output. Run \`${manager} outdated\` and read it directly, or use \`diff\` after upgrading.`)
226
+ }
227
+ // Both exit 1 when anything is outdated; that is not an error.
228
+ const r = spawnSync(cmd[0], cmd[1], { cwd: dir, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 })
229
+ if (r.error) throw new Error(`could not run ${cmd[0]}: ${r.error.message}`)
230
+ const text = r.stdout.trim()
231
+ if (!text) return {}
232
+ try { return JSON.parse(text) } catch { throw new Error(`${cmd[0]} outdated returned non-JSON:\n${(r.stderr || text).slice(0, 500)}`) }
233
+ }
234
+
235
+ function releaseNotesUrl(dir, name) {
236
+ const r = spawnSync('npm', ['view', name, 'repository.url', '--json'], { cwd: dir, encoding: 'utf8' })
237
+ if (r.status !== 0 || !r.stdout.trim()) return null
238
+ let url
239
+ try { url = JSON.parse(r.stdout) } catch { return null }
240
+ if (Array.isArray(url)) url = url[0]
241
+ const gh = String(url).match(/github\.com[/:]([^/]+)\/([^/#.]+)/)
242
+ return gh ? `https://github.com/${gh[1]}/${gh[2]}/releases` : `https://www.npmjs.com/package/${name}?activeTab=versions`
243
+ }
244
+
245
+ export function planOutdated(raw) {
246
+ const rows = Object.entries(raw).map(([name, info]) => {
247
+ const i = Array.isArray(info) ? info[0] : info
248
+ return { name, current: i.current ?? null, wanted: i.wanted ?? null, latest: i.latest ?? null, dev: (i.dependencyType ?? i.type) === 'devDependencies' }
249
+ })
250
+ for (const r of rows) r.jump = r.current ? classifyJump(r.current, r.latest) : 'not installed'
251
+ return rows.filter((r) => r.jump !== 'none')
252
+ }
253
+
254
+ // ---------------------------------------------------------------------------
255
+ // CLI
256
+ // ---------------------------------------------------------------------------
257
+
258
+ function main(argv) {
259
+ const opts = { dir: '.', base: 'HEAD', offline: false, json: false, positional: [] }
260
+ for (let i = 0; i < argv.length; i++) {
261
+ const a = argv[i]
262
+ if (a === '-h' || a === '--help') { process.stdout.write(HELP); return 0 }
263
+ else if (a === '--dir') opts.dir = argv[++i]
264
+ else if (a === '--base') opts.base = argv[++i]
265
+ else if (a === '--offline') opts.offline = true
266
+ else if (a === '--json') opts.json = true
267
+ else if (a.startsWith('--')) { process.stderr.write(`upgrade-report: unknown flag ${a}\n\n${HELP}`); return 2 }
268
+ else opts.positional.push(a)
269
+ }
270
+ const [cmd, arg] = opts.positional
271
+ const dir = path.resolve(opts.dir)
272
+ const print = (obj, text) => process.stdout.write(opts.json ? JSON.stringify(obj, null, 2) + '\n' : text)
273
+
274
+ try {
275
+ if (cmd === 'usages') {
276
+ if (!arg) throw new Error('usages needs a package name')
277
+ const u = usages(dir, arg)
278
+ let t = `${u.files.length} file(s) import ${arg}\n\nSymbols (most used first):\n`
279
+ t += u.symbols.map((s) => ` ${String(s.count).padStart(4)} ${s.symbol}`).join('\n') + '\n\nFiles:\n'
280
+ t += u.files.map((f) => f.hits.map((h) => ` ${f.file}:${h.line} ${h.spec} { ${h.names.join(', ')} }`).join('\n')).join('\n') + '\n'
281
+ print(u, t)
282
+ return 0
283
+ }
284
+
285
+ if (cmd === 'diff') {
286
+ const before = lockSnapshot(dir, opts.base)
287
+ const after = lockSnapshot(dir, null)
288
+ if (!after) throw new Error(`no package.json or lockfile in ${dir}`)
289
+ if (!before) throw new Error(`could not read a lockfile at ${opts.base} (is this a git repo, and did the file exist then?)`)
290
+ const changes = diffVersions(before.versions, after.versions)
291
+ const order = { major: 0, removed: 1, added: 2, minor: 3, patch: 4, unknown: 5 }
292
+ changes.sort((a, b) => order[a.jump] - order[b.jump] || a.name.localeCompare(b.name))
293
+ let t = `Direct dependency changes, ${opts.base} -> working tree (${after.source})\n\n`
294
+ t += changes.length ? changes.map((c) => ` ${c.jump.toUpperCase().padEnd(8)} ${c.name} ${c.from ?? '-'} -> ${c.to ?? '-'}`).join('\n') + '\n' : ' none\n'
295
+ const majors = changes.filter((c) => c.jump === 'major').length
296
+ if (majors) t += `\n${majors} major change(s): each needs its changelog read and \`usages\` checked.\n`
297
+ print({ base: opts.base, source: after.source, changes }, t)
298
+ return 0
299
+ }
300
+
301
+ if (cmd === 'outdated') {
302
+ const manager = detectManager(dir)
303
+ const rows = planOutdated(runOutdated(dir, manager))
304
+ const majors = rows.filter((r) => r.jump === 'major')
305
+ for (const m of majors) {
306
+ m.importingFiles = usages(dir, m.name).files.length
307
+ m.releaseNotes = opts.offline ? null : releaseNotesUrl(dir, m.name)
308
+ }
309
+ // Fewest importers first: small, well-contained majors build confidence and shrink the diff for the big ones.
310
+ majors.sort((a, b) => a.importingFiles - b.importingFiles || a.name.localeCompare(b.name))
311
+ const safe = rows.filter((r) => r.jump === 'minor' || r.jump === 'patch')
312
+ let t = `${manager}: ${rows.length} package(s) behind\n\n`
313
+ t += `Step 1 - one commit: ${safe.length} minor/patch update(s)\n`
314
+ t += safe.map((r) => ` ${r.name} ${r.current} -> ${r.latest}`).join('\n') + (safe.length ? '\n' : '')
315
+ majors.forEach((m, i) => {
316
+ t += `\nStep ${i + 2} - own commit: ${m.name} ${m.current} -> ${m.latest} (${m.importingFiles} importing file(s))${m.dev ? ' [dev]' : ''}\n`
317
+ if (m.releaseNotes) t += ` notes: ${m.releaseNotes}\n`
318
+ })
319
+ const other = rows.filter((r) => !['major', 'minor', 'patch'].includes(r.jump))
320
+ if (other.length) t += `\nUnclassified: ${other.map((r) => `${r.name} (${r.jump})`).join(', ')}\n`
321
+ print({ manager, safe, majors, other }, t)
322
+ return 0
323
+ }
324
+
325
+ process.stderr.write(HELP)
326
+ return 2
327
+ } catch (err) {
328
+ process.stderr.write(`upgrade-report: ${err.message}\n`)
329
+ return 1
330
+ }
331
+ }
332
+
333
+ if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
334
+ process.exitCode = main(process.argv.slice(2))
335
+ }
@@ -0,0 +1,121 @@
1
+ ---
2
+ name: schema-migration
3
+ description: Use when writing, generating, or reviewing a database migration or schema change (add, drop or rename a column or table, add an index or constraint, change a type, backfill data) for Postgres or MySQL through Prisma, Drizzle, Alembic, Django, Rails, Knex or raw SQL, especially when the table already holds production data.
4
+ ---
5
+
6
+ # Schema Migration
7
+
8
+ Most migration outages come from two causes: a lock that stalls every query on a hot table, or a schema change that the code still running in production can't handle. Both are predictable from the SQL alone, before anything runs.
9
+
10
+ Announce: "Using schema-migration to plan <change> safely."
11
+
12
+ **Script location.** The linter lives in `${CLAUDE_SKILL_DIR}/scripts/`. If `CLAUDE_SKILL_DIR` is not set, use the absolute path of the directory containing this SKILL.md. Below, `$S` stands for that folder. It needs only Node 20+.
13
+
14
+ ## The Rule
15
+
16
+ ```
17
+ Every migration must be safe to run while the old code and the new code are both live.
18
+ ```
19
+
20
+ Deploys aren't atomic. For minutes, old and new app instances share the database, and a rollback puts the old code back on the new schema. Any step that only one version can handle is an outage waiting to happen.
21
+
22
+ ## Checklist
23
+
24
+ Copy this into your reply and tick it off:
25
+
26
+ ```
27
+ - [ ] 1. Sized the change: tables touched, row counts, write traffic
28
+ - [ ] 2. Split into expand -> migrate code -> backfill -> contract
29
+ - [ ] 3. Wrote the migration(s) and got the actual SQL
30
+ - [ ] 4. lint-ddl.mjs passes (or each finding is justified in writing)
31
+ - [ ] 5. Backfill is batched, idempotent and runs outside the migration
32
+ - [ ] 6. Rollback path written, irreversible steps named
33
+ - [ ] 7. Ran it against a realistic copy and timed it
34
+ ```
35
+
36
+ ## 1. Size the change
37
+
38
+ - Find the tables touched and how big they are. On Postgres: `SELECT relname, reltuples::bigint FROM pg_class WHERE relname IN ('users');`. On MySQL: `SELECT table_name, table_rows FROM information_schema.tables WHERE table_schema = DATABASE();`.
39
+ - **Short path:** if every table is new in this migration, or is known to be tiny (under about 100k rows) with low write traffic, write one migration, run step 4 and stop. `lint-ddl` already skips tables created in the same file.
40
+ - If you can't find out the size, assume the table is big and busy.
41
+
42
+ ## 2. Split into expand and contract
43
+
44
+ Changes that break compatibility never ship in a single migration. Split them into releases:
45
+
46
+ | Phase | Schema | Code | Safe because |
47
+ |---|---|---|---|
48
+ | **Expand** | Only additive changes: nullable columns, new tables, `NOT VALID` constraints, indexes built `CONCURRENTLY` | Unchanged | Old code ignores what it doesn't know about |
49
+ | **Migrate code** | None | Writes to both old and new; reads the old | Either version can run |
50
+ | **Backfill** | Data only, in batches | Unchanged | Idempotent and resumable |
51
+ | **Switch** | Validate constraints, `SET NOT NULL` | Reads the new, still writes both | The old shape is still intact for rollback |
52
+ | **Contract** | Drop the old column or table | Stops writing the old | Nothing reads it any more |
53
+
54
+ Renames, type changes, splitting a column and making a column required all follow this pattern. See `references/postgres-locks.md` for the exact statements for each.
55
+
56
+ ## 3. Write the migration and get the SQL
57
+
58
+ Lint the SQL that will actually run, not the ORM call that produces it. `references/frameworks.md` shows how to get the SQL for each tool and how to turn off the transaction wrapper for `CONCURRENTLY`.
59
+
60
+ - Prisma: `prisma migrate dev --create-only`, then read or edit `migration.sql`
61
+ - Drizzle: `drizzle-kit generate` (never `push` against production)
62
+ - Alembic: `alembic upgrade <from>:<to> --sql`
63
+ - Django: `python manage.py sqlmigrate <app> <number>`
64
+ - Rails: use the `strong_migrations` gem (the linter needs SQL)
65
+
66
+ ## 4. Lint
67
+
68
+ ```bash
69
+ node $S/lint-ddl.mjs prisma/migrations/20260926_add_email/migration.sql
70
+ alembic upgrade head --sql | node $S/lint-ddl.mjs -
71
+ node $S/lint-ddl.mjs db/migrations --dialect mysql
72
+ ```
73
+
74
+ - It exits 1 on any error. Fix the SQL and lint again until it's clean.
75
+ - To keep a finding on purpose (say, a table you know has 200 rows), write down why in the migration file and in your reply. Never ignore a finding silently.
76
+ - The linter matches patterns; it is not a planner. A clean run still needs steps 5 to 7.
77
+
78
+ ## 5. Backfill outside the migration
79
+
80
+ - Update in batches keyed by primary key: `UPDATE t SET new = old WHERE id >= $1 AND id < $2 AND new IS NULL`, with 1k to 10k rows per transaction.
81
+ - Make it idempotent (the `new IS NULL` guard) so it can resume after a crash.
82
+ - Pause briefly between batches and watch replication lag.
83
+ - Run it as a script or job after the expand phase deploys. Never run it inside the schema migration.
84
+
85
+ ## 6. Rollback
86
+
87
+ - For each phase, write down how to undo it and whether undoing it loses data.
88
+ - Dropping a column, dropping a table, or converting a type with data loss can't be undone by a `down` migration. Take a backup or snapshot first, and say so plainly to the user.
89
+ - Expand phases should be undoable by simply redeploying the previous app version.
90
+
91
+ ## 7. Rehearse
92
+
93
+ - Run the migration against a copy of production or a seeded database of realistic size.
94
+ - Time each statement. In a second session, check `pg_locks` or `SHOW PROCESSLIST` while it runs.
95
+ - Report the timings. A migration you haven't timed is a guess.
96
+
97
+ ## Output
98
+
99
+ End with a plan the user can review:
100
+
101
+ ```
102
+ Change: <one line>
103
+ Tables: <name (rows, writes/s)>
104
+ Releases:
105
+ 1. expand - <migration file> lint: clean
106
+ 2. code - <what dual-writes>
107
+ 3. backfill - <script>, <batch size>, est <time>
108
+ 4. contract - <migration file, later release>
109
+ Rollback: <per phase>; irreversible: <list or none>
110
+ Rehearsed: <where, timings> | NOT YET
111
+ ```
112
+
113
+ ## Red flags
114
+
115
+ | Thought | Reality |
116
+ |---|---|
117
+ | "It's just adding an index." | Without `CONCURRENTLY`, writes to the table stop until the build finishes. |
118
+ | "The ORM generated it, so it's fine." | ORMs generate SQL that is correct, not SQL that is safe to run online. Read it. |
119
+ | "We'll rename it in one go and deploy quickly." | Old instances keep serving traffic during the deploy, and they fail on the new name. |
120
+ | "The backfill is one UPDATE." | One UPDATE on 50M rows is one transaction holding 50M row locks. |
121
+ | "Rollback is `migrate down`." | Not after a DROP. Name what can't be undone. |
@@ -0,0 +1,54 @@
1
+ # Getting the SQL, and escaping the transaction wrapper
2
+
3
+ `CREATE INDEX CONCURRENTLY` (and `DROP INDEX CONCURRENTLY`) can't run inside a transaction. Most migration tools wrap each migration in one, so every concurrent index needs its own migration with that wrapper turned off.
4
+
5
+ These tools change between versions, so check the one in the lockfile against its docs if something here doesn't match.
6
+
7
+ ## Prisma
8
+ - Generate without applying: `npx prisma migrate dev --create-only --name add_email`. Then edit `prisma/migrations/<ts>_add_email/migration.sql`.
9
+ - Lint it: `node lint-ddl.mjs prisma/migrations/<ts>_add_email/migration.sql`.
10
+ - Put `CREATE INDEX CONCURRENTLY` **alone** in its own migration. A multi-statement file runs as one implicit transaction.
11
+ - Production runs `prisma migrate deploy`. Never run `db push` against it.
12
+
13
+ ## Drizzle
14
+ - `npx drizzle-kit generate` writes SQL into the configured `out` folder. Lint that folder.
15
+ - `npx drizzle-kit generate --custom --name backfill` creates an empty migration for SQL you write by hand.
16
+ - The drizzle-orm migrator applies pending migrations inside a transaction. Run concurrent index statements separately, for example with a small script via `psql`, and record that they ran.
17
+ - Never use `drizzle-kit push` against production.
18
+
19
+ ## Alembic (SQLAlchemy)
20
+ - Offline SQL: `alembic upgrade <from_rev>:<to_rev> --sql | node lint-ddl.mjs -`
21
+ - Concurrent index:
22
+ ```python
23
+ def upgrade():
24
+ with op.get_context().autocommit_block():
25
+ op.create_index("ix_users_email", "users", ["email"], postgresql_concurrently=True)
26
+ ```
27
+
28
+ ## Django
29
+ - SQL for one migration: `python manage.py sqlmigrate <app> <number> | node lint-ddl.mjs -`
30
+ - Concurrent index: `from django.contrib.postgres.operations import AddIndexConcurrently`, and set `atomic = False` on the `Migration` class.
31
+ - To change the schema and the model state separately (for renames and expand/contract), use `migrations.SeparateDatabaseAndState`.
32
+ - The `django-pg-zero-downtime-migrations` backend enforces many of these rules automatically.
33
+
34
+ ## Rails (ActiveRecord)
35
+ - Rails has no offline SQL mode, so lint with the `strong_migrations` gem instead. It checks the same classes of problem.
36
+ - Concurrent index:
37
+ ```ruby
38
+ class AddIndexToUsersEmail < ActiveRecord::Migration[7.1]
39
+ disable_ddl_transaction!
40
+ def change
41
+ add_index :users, :email, algorithm: :concurrently
42
+ end
43
+ end
44
+ ```
45
+ - Before dropping a column, set `self.ignored_columns += ["old_col"]` on the model and deploy.
46
+
47
+ ## Knex
48
+ - Put `exports.config = { transaction: false }` in the migration file (ESM: `export const config = { transaction: false }`).
49
+ - To see the SQL, call `.toString()` on a schema builder, or run against a scratch database with `DEBUG=knex:query`.
50
+
51
+ ## Flyway / Liquibase / raw SQL files
52
+ - The files are the SQL, so lint them directly.
53
+ - Flyway: turn off the wrapper per script with a `V5__add_index.sql.conf` containing `executeInTransaction=false`.
54
+ - Liquibase: set `runInTransaction="false"` on the changeset.
@@ -0,0 +1,73 @@
1
+ # Postgres locks and safe recipes
2
+
3
+ Why each `lint-ddl` rule exists, and the safe sequence to use instead. MySQL notes are at the end.
4
+
5
+ ## Lock levels that matter
6
+
7
+ | Lock | Taken by | Blocks |
8
+ |---|---|---|
9
+ | `ACCESS EXCLUSIVE` | Most `ALTER TABLE` forms, `DROP`, `TRUNCATE`, `VACUUM FULL`, `CLUSTER`, `DROP INDEX` | **Everything**, including `SELECT` |
10
+ | `SHARE` | `CREATE INDEX` (not concurrent) | Writes: `INSERT`, `UPDATE`, `DELETE` |
11
+ | `SHARE ROW EXCLUSIVE` | `ADD FOREIGN KEY` (on both tables), `CREATE TRIGGER` | Writes |
12
+ | `SHARE UPDATE EXCLUSIVE` | `VALIDATE CONSTRAINT`, `CREATE INDEX CONCURRENTLY`, `ANALYZE` | Other DDL and vacuum only; reads and writes go on |
13
+
14
+ **The queue problem.** A statement waiting for a lock blocks every statement that queues behind it. So an `ALTER TABLE` that needs only milliseconds can still stall a table for as long as the slowest open transaction runs. Always start the migration with `SET lock_timeout = '5s'`, and retry if it times out.
15
+
16
+ ## Recipes
17
+
18
+ ### Add a required column
19
+ ```sql
20
+ ALTER TABLE users ADD COLUMN email text; -- instant
21
+ -- deploy code that writes email; backfill in batches
22
+ ALTER TABLE users ADD CONSTRAINT users_email_nn CHECK (email IS NOT NULL) NOT VALID;
23
+ ALTER TABLE users VALIDATE CONSTRAINT users_email_nn; -- no write block
24
+ ALTER TABLE users ALTER COLUMN email SET NOT NULL; -- PG12+: uses the check, no scan
25
+ ALTER TABLE users DROP CONSTRAINT users_email_nn;
26
+ ```
27
+ If a constant default is fine, use `ADD COLUMN email text NOT NULL DEFAULT ''`. On PG11+ it only updates the catalog.
28
+
29
+ ### Add an index
30
+ ```sql
31
+ CREATE INDEX CONCURRENTLY idx_users_email ON users (email);
32
+ ```
33
+ - It can't run inside a transaction, so give it its own migration with the wrapper turned off (see `frameworks.md`).
34
+ - If it fails, it leaves an `INVALID` index behind. Find it with `SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;`, drop it with `DROP INDEX CONCURRENTLY`, then retry.
35
+
36
+ ### Add a foreign key or check constraint
37
+ ```sql
38
+ ALTER TABLE orders ADD CONSTRAINT orders_user_fk FOREIGN KEY (user_id) REFERENCES users (id) NOT VALID;
39
+ ALTER TABLE orders VALIDATE CONSTRAINT orders_user_fk;
40
+ ```
41
+
42
+ ### Add a unique constraint or primary key
43
+ ```sql
44
+ CREATE UNIQUE INDEX CONCURRENTLY users_email_key ON users (email);
45
+ ALTER TABLE users ADD CONSTRAINT users_email_key UNIQUE USING INDEX users_email_key;
46
+ ```
47
+
48
+ ### Rename a column
49
+ 1. Add the new column.
50
+ 2. Deploy code that writes both columns.
51
+ 3. Backfill.
52
+ 4. Deploy code that reads the new column.
53
+ 5. Deploy code that stops writing the old one.
54
+ 6. Drop the old column.
55
+
56
+ Where a view layer is acceptable, you can instead rename the table and put a view with the old name in its place for one release.
57
+
58
+ ### Change a column type
59
+ Same steps as a rename, with a new column of the new type. These changes are safe in place: `varchar(n)` to a larger `n` or to `text`; `numeric(p,s)` to a larger precision with the same scale; dropping a `varchar` length limit.
60
+
61
+ ### Drop a column
62
+ 1. Remove it from the ORM model and deploy, so generated `SELECT` lists stop naming it. Rails: use `ignored_columns` first.
63
+ 2. `ALTER TABLE ... DROP COLUMN` in a later release. It only updates the catalog, but it takes a brief `ACCESS EXCLUSIVE` lock, so keep `lock_timeout` set.
64
+
65
+ ### Enum values
66
+ `ALTER TYPE ... ADD VALUE` is fast. Before PG12 it can't run inside a transaction block. Removing a value means creating a new type and migrating the column to it.
67
+
68
+ ## MySQL (InnoDB, 8.0+)
69
+
70
+ - Write `ALGORITHM=INSTANT` or `ALGORITHM=INPLACE, LOCK=NONE` on every `ALTER`. MySQL then raises an error instead of quietly falling back to a table copy.
71
+ - `INSTANT` covers adding a column (8.0.29+ for any position), dropping a column (8.0.29+), renaming a column, and setting or dropping a default.
72
+ - Changing a column type or charset needs `COPY`. For big tables, use `gh-ost` or `pt-online-schema-change`.
73
+ - Set `SET SESSION lock_wait_timeout = 5;`. The metadata-lock queue works like the Postgres one described above.