Repository navigation
fix(db): apply guarded sql migrations before push and fail on push errors #96
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| #!/usr/bin/env node | ||
| // Apply the guarded SQL migrations before drizzle-kit push. Without a TTY, | ||
| // push cannot answer its prompts (e.g. a unique constraint on a non-empty | ||
| // table) and leaves the schema behind: once these files ran, the schema | ||
| // already matches and push has nothing left to ask. | ||
| // Files from FIRST_GUARDED on are idempotent (IF NOT EXISTS, duplicate_object | ||
| // handlers) and safe to rerun on every start; earlier ones are not, and push | ||
| // already brought every database past them. | ||
| // Usage: node scripts/apply-sql-migrations.mjs | ||
|
|
||
| import { readdir, readFile } from 'node:fs/promises'; | ||
| import { join } from 'node:path'; | ||
| import postgres from 'postgres'; | ||
|
|
||
| export const MIGRATIONS_DIR = 'server/db/migrations'; | ||
| export const FIRST_GUARDED = 13; | ||
|
|
||
| /** Guarded migration files, in the order they must run */ | ||
| export function guardedMigrations(names) { | ||
| return names | ||
| .filter((name) => /^\d{4}_.+\.sql$/.test(name)) | ||
| .filter((name) => Number(name.slice(0, 4)) >= FIRST_GUARDED) | ||
| .sort(); | ||
| } | ||
|
|
||
| async function main() { | ||
| const files = guardedMigrations(await readdir(MIGRATIONS_DIR)); | ||
| const sql = postgres(process.env.DATABASE_URL, { max: 1, onnotice: () => {} }); | ||
| try { | ||
| // Fresh database: these files alter tables push has not created yet. | ||
| // Push builds the whole schema from scratch, and on empty tables it has | ||
| // nothing to ask | ||
| const [{ ready }] = await sql`SELECT to_regclass('public.users') IS NOT NULL AS ready`; | ||
| if (!ready) { | ||
| console.log(' (fresh database: push creates the schema)'); | ||
| return; | ||
| } | ||
| for (const file of files) { | ||
| // No parameters: simple query protocol, several statements per file | ||
| await sql.unsafe(await readFile(join(MIGRATIONS_DIR, file), 'utf8')); | ||
| console.log(` ✓ ${file}`); | ||
| } | ||
| } finally { | ||
| await sql.end(); | ||
| } | ||
| } | ||
|
|
||
| if (import.meta.url === `file://${process.argv[1]}`) { | ||
| await main(); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| import { describe, it, expect } from 'vitest'; | ||
| import { readdirSync, readFileSync } from 'node:fs'; | ||
| import { join } from 'node:path'; | ||
| import { | ||
| guardedMigrations, | ||
| MIGRATIONS_DIR, | ||
| } from '../scripts/apply-sql-migrations.mjs'; | ||
|
|
||
| describe('guardedMigrations', () => { | ||
| it('keeps numbered .sql files from 0013 on, in order', () => { | ||
| expect( | ||
| guardedMigrations([ | ||
| '0019_b.sql', | ||
| '0012_old.sql', | ||
| 'meta', | ||
| '0013_a.sql', | ||
| 'notes.md', | ||
| ]) | ||
| ).toEqual(['0013_a.sql', '0019_b.sql']); | ||
| }); | ||
| }); | ||
|
|
||
| // They run on every start: a statement that fails the second time would | ||
| // stop the app from booting | ||
| describe('guarded migration files', () => { | ||
| const files = guardedMigrations(readdirSync(MIGRATIONS_DIR)); | ||
|
|
||
| it.each(files)('%s can run twice', (file) => { | ||
| const sql = readFileSync(join(MIGRATIONS_DIR, file), 'utf8'); | ||
| for (const m of sql.matchAll(/CREATE (UNIQUE )?(TABLE|INDEX)\b(?! IF NOT EXISTS)/g)) { | ||
| throw new Error(`${file}: unguarded "${m[0]}"`); | ||
| } | ||
| for (const m of sql.matchAll(/ADD COLUMN\b(?! IF NOT EXISTS)/g)) { | ||
| throw new Error(`${file}: unguarded "${m[0]}"`); | ||
| } | ||
| if (/ADD CONSTRAINT/.test(sql)) { | ||
| expect(sql).toMatch(/EXCEPTION WHEN duplicate_object/); | ||
| } | ||
| }); | ||
| }); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.