-
Notifications
You must be signed in to change notification settings - Fork 115
fix(sync-engine): replace pg-node-migrations with custom runner #234
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
Open
cescox
wants to merge
5
commits into
stripe:main
Choose a base branch
from
cescox:fix/custom-migration-runner
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
48220b7
feat(sync-engine): replace pg-node-migrations with custom runner
cescox b22b8c4
refactor(sync-engine): use object param for getMigrations
cescox fb97429
fix(sync-engine): rename tableName to migrationsTableName
cescox 12ef251
refactor(sync-engine): move hash column removal to migration file
cescox b6ca82f
chore: merge main into fix/custom-migration-runner
cescox 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 |
|---|---|---|
| @@ -1,66 +1,139 @@ | ||
| import { Client } from 'pg' | ||
| import { migrate } from 'pg-node-migrations' | ||
| import fs from 'node:fs' | ||
| import pino from 'pino' | ||
| import path from 'node:path' | ||
| import type { Logger } from 'pino' | ||
| import type { ConnectionOptions } from 'node:tls' | ||
|
|
||
| type MigrationConfig = { | ||
| schema: string | ||
| databaseUrl: string | ||
| ssl?: ConnectionOptions | ||
| logger?: pino.Logger | ||
| logger?: Logger | ||
| } | ||
|
|
||
| async function connectAndMigrate( | ||
| client: Client, | ||
| migrationsDirectory: string, | ||
| config: MigrationConfig, | ||
| logOnError = false | ||
| ) { | ||
| if (!fs.existsSync(migrationsDirectory)) { | ||
| config.logger?.info(`Migrations directory ${migrationsDirectory} not found, skipping`) | ||
| return | ||
| } | ||
| const MIGRATION_LOCK_ID = 72987329 | ||
| const MIGRATIONS_DIR = path.join(__dirname, 'migrations') | ||
|
|
||
| const optionalConfig = { | ||
| schemaName: config.schema, | ||
| tableName: 'migrations', | ||
| } | ||
| function parseFileName(fileName: string): { id: number; name: string } | null { | ||
| const match = /^(\d+)[-_](.*)\.sql$/i.exec(fileName) | ||
| if (!match) return null | ||
| return { id: parseInt(match[1], 10), name: match[2] } | ||
| } | ||
|
|
||
| export type Migration = { id: number; name: string; sql: string } | ||
|
|
||
| /** | ||
| * Returns all migrations with schema placeholders replaced. | ||
| * Useful for inspecting migrations or running them manually with psql. | ||
| */ | ||
| export function getMigrations(config: { schema?: string } = {}): Migration[] { | ||
| const schema = config.schema ?? 'stripe' | ||
|
|
||
| if (!fs.existsSync(MIGRATIONS_DIR)) return [] | ||
|
|
||
| return fs | ||
| .readdirSync(MIGRATIONS_DIR) | ||
| .filter((f) => f.endsWith('.sql')) | ||
| .sort() | ||
| .map((fileName) => { | ||
| const parsed = parseFileName(fileName) | ||
| if (!parsed) return null | ||
|
|
||
| const raw = fs.readFileSync(path.join(MIGRATIONS_DIR, fileName), 'utf8') | ||
| const sql = raw.replace(/\{\{schema\}\}/g, schema) | ||
|
|
||
| return { id: parsed.id, name: parsed.name, sql } | ||
| }) | ||
| .filter((m): m is Migration => m !== null) | ||
| } | ||
|
|
||
| /** | ||
| * Applies a single migration file within a transaction. | ||
| * Supports disabling transactions via `-- postgres-migrations disable-transaction` comment. | ||
| */ | ||
| async function applyMigration( | ||
| client: Client, | ||
| tableName: string, | ||
| migration: { id: number; name: string; sql: string } | ||
| ): Promise<void> { | ||
| const useTransaction = !migration.sql.includes('-- postgres-migrations disable-transaction') | ||
|
|
||
| try { | ||
| await migrate({ client }, migrationsDirectory, optionalConfig) | ||
| } catch (error) { | ||
| if (logOnError && error instanceof Error) { | ||
| config.logger?.error(error, 'Migration error:') | ||
| } else { | ||
| throw error | ||
| if (useTransaction) await client.query('START TRANSACTION') | ||
| await client.query(migration.sql) | ||
| await client.query(`INSERT INTO ${tableName} (id, name) VALUES ($1, $2)`, [ | ||
| migration.id, | ||
| migration.name, | ||
| ]) | ||
| if (useTransaction) await client.query('COMMIT') | ||
| } catch (err) { | ||
| if (useTransaction) { | ||
| try { | ||
| await client.query('ROLLBACK') | ||
| } catch { | ||
| // Connection may already be broken | ||
| } | ||
| } | ||
| throw new Error( | ||
| `Migration ${migration.id} (${migration.name}) failed: ${err instanceof Error ? err.message : String(err)}` | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| export async function runMigrations(config: MigrationConfig): Promise<void> { | ||
| // Init DB | ||
| const client = new Client({ | ||
| connectionString: config.databaseUrl, | ||
| ssl: config.ssl, | ||
| connectionTimeoutMillis: 10_000, | ||
| }) | ||
|
|
||
| const tableName = `"${config.schema}"."migrations"` | ||
| const migrations = getMigrations({ schema: config.schema }) | ||
|
|
||
| try { | ||
| // Run migrations | ||
| await client.connect() | ||
|
|
||
| // Ensure schema exists, not doing it via migration to not break current migration checksums | ||
| await client.query(`CREATE SCHEMA IF NOT EXISTS ${config.schema};`) | ||
| if (migrations.length === 0) { | ||
| config.logger?.info(`No migrations found, skipping`) | ||
| return | ||
| } | ||
|
|
||
| config.logger?.info('Running migrations') | ||
|
|
||
| await connectAndMigrate(client, path.resolve(__dirname, './migrations'), config) | ||
| await client.query(`SELECT pg_advisory_lock(${MIGRATION_LOCK_ID})`) | ||
|
|
||
| try { | ||
| await client.query(`CREATE SCHEMA IF NOT EXISTS "${config.schema}"`) | ||
|
|
||
| await client.query(` | ||
| CREATE TABLE IF NOT EXISTS ${tableName} ( | ||
| id integer PRIMARY KEY, | ||
| name varchar(100) UNIQUE NOT NULL, | ||
| executed_at timestamp DEFAULT current_timestamp | ||
| ) | ||
| `) | ||
|
|
||
| // Remove legacy hash column from pg-node-migrations (checksums no longer validated) | ||
| await client.query(`ALTER TABLE ${tableName} DROP COLUMN IF EXISTS hash`) | ||
|
kevcodez marked this conversation as resolved.
Outdated
|
||
|
|
||
| const { rows: applied } = await client.query<{ id: number }>(`SELECT id FROM ${tableName}`) | ||
| const appliedIds = new Set(applied.map((r) => r.id)) | ||
|
|
||
| for (const migration of migrations) { | ||
| if (appliedIds.has(migration.id)) continue | ||
|
|
||
| config.logger?.info(`Applying migration ${migration.id}: ${migration.name}`) | ||
| await applyMigration(client, tableName, migration) | ||
| } | ||
| } finally { | ||
| await client.query(`SELECT pg_advisory_unlock(${MIGRATION_LOCK_ID})`) | ||
| } | ||
|
|
||
| config.logger?.info('Finished migrations') | ||
| } catch (err) { | ||
| config.logger?.error(err, 'Error running migrations') | ||
| throw err | ||
| } finally { | ||
| await client.end() | ||
| config.logger?.info('Finished migrations') | ||
| } | ||
| } | ||
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
2 changes: 1 addition & 1 deletion
2
packages/sync-engine/src/database/migrations/0002_customers.sql
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
25 changes: 16 additions & 9 deletions
25
packages/sync-engine/src/database/migrations/0003_prices.sql
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 |
|---|---|---|
| @@ -1,34 +1,41 @@ | ||
| DO $$ | ||
| BEGIN | ||
| IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'pricing_type') THEN | ||
| create type "stripe"."pricing_type" as enum ('one_time', 'recurring'); | ||
| IF NOT EXISTS ( | ||
| SELECT 1 FROM pg_type t | ||
| JOIN pg_namespace n ON t.typnamespace = n.oid | ||
| WHERE t.typname = 'pricing_type' AND n.nspname = '{{schema}}' | ||
| ) THEN | ||
| create type "{{schema}}"."pricing_type" as enum ('one_time', 'recurring'); | ||
| END IF; | ||
| IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'pricing_tiers') THEN | ||
| create type "stripe"."pricing_tiers" as enum ('graduated', 'volume'); | ||
| IF NOT EXISTS ( | ||
| SELECT 1 FROM pg_type t | ||
| JOIN pg_namespace n ON t.typnamespace = n.oid | ||
| WHERE t.typname = 'pricing_tiers' AND n.nspname = '{{schema}}' | ||
| ) THEN | ||
| create type "{{schema}}"."pricing_tiers" as enum ('graduated', 'volume'); | ||
| END IF; | ||
| --more types here... | ||
| END | ||
| $$; | ||
|
|
||
|
|
||
| create table if not exists "stripe"."prices" ( | ||
| create table if not exists "{{schema}}"."prices" ( | ||
| "id" text primary key, | ||
| "object" text, | ||
| "active" boolean, | ||
| "currency" text, | ||
| "metadata" jsonb, | ||
| "nickname" text, | ||
| "recurring" jsonb, | ||
| "type" stripe.pricing_type, | ||
| "type" "{{schema}}"."pricing_type", | ||
| "unit_amount" integer, | ||
| "billing_scheme" text, | ||
| "created" integer, | ||
| "livemode" boolean, | ||
| "lookup_key" text, | ||
| "tiers_mode" stripe.pricing_tiers, | ||
| "tiers_mode" "{{schema}}"."pricing_tiers", | ||
| "transform_quantity" jsonb, | ||
| "unit_amount_decimal" text, | ||
|
|
||
| "product" text references stripe.products | ||
| "product" text references "{{schema}}"."products" | ||
| ); | ||
|
|
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
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
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
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
Oops, something went wrong.
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.