From 8d028f3405ea5f6fe288edb77791d40797c26432 Mon Sep 17 00:00:00 2001 From: hippi345 <13539685+hippi345@users.noreply.github.com> Date: Fri, 30 Oct 2026 15:43:46 +0000 Subject: [PATCH 1/3] Default graphile-migrate init to current/ folder Change the --folder flag default to true so new projects get a migrations/current/ directory instead of current.sql. Pass --no-folder to retain the previous single-file behavior. Add init tests and update README documentation. --- README.md | 12 ++++++---- __tests__/init.test.ts | 54 ++++++++++++++++++++++++++++++++++++++++++ src/commands/init.ts | 5 ++-- 3 files changed, 64 insertions(+), 7 deletions(-) create mode 100644 __tests__/init.test.ts diff --git a/README.md b/README.md index 4f3d4c5a..9da302f 100644 --- a/README.md +++ b/README.md @@ -153,10 +153,12 @@ graphile-migrate watch ### Committed and current migrations New migrations are composed within **"the current migration"**. You will see -this term used a lot. By default this is in the `migrations/current.sql` file, -but if you like you may delete that file and instead create a -`migrations/current/` folder into which you may place numbered SQL files which -together comprise "the current migration". +this term used a lot. When you run `graphile-migrate init`, the current +migration is created as a `migrations/current/` folder into which you may place +numbered SQL files which together comprise "the current migration". If you +prefer, you may instead use a single `migrations/current.sql` file (pass +`--no-folder` to `graphile-migrate init`, or delete the folder and create the +file manually). The current migration should be idempotent (this is your responsibility, see "Idempotency" below); i.e. it should be able to be ran multiple times and have @@ -252,7 +254,7 @@ Options: --help Show help [boolean] -c, --config Optional path to gmrc file [string] [default: .gmrc[.js|.cjs]] --folder Use a folder rather than a file for the current migration. - [boolean] [default: false] + [boolean] [default: true] ``` diff --git a/__tests__/init.test.ts b/__tests__/init.test.ts new file mode 100644 index 0000000..b37fc69 --- /dev/null +++ b/__tests__/init.test.ts @@ -0,0 +1,54 @@ +jest.unmock("pg"); + +import "mock-fs"; // MUST BE BEFORE EVERYTHING + +import * as fsp from "fs/promises"; +import mockFs from "mock-fs"; + +import { init } from "../src/commands/init"; +import { statOrNull } from "../src/lib"; + +beforeAll(() => { + // eslint-disable-next-line no-console + console.log("[mock-fs callsites hack]"); + mockFs({}); +}); +afterAll(() => { + mockFs.restore(); +}); + +beforeEach(() => { + mockFs({}); +}); +afterEach(() => { + mockFs.restore(); +}); + +it("creates a current/ folder by default", async () => { + await init({}); + + const dirStats = await statOrNull("migrations/current"); + expect(dirStats?.isDirectory()).toBe(true); + + const fileStats = await statOrNull("migrations/current.sql"); + expect(fileStats).toBeNull(); + + const content = await fsp.readFile( + "migrations/current/1-current.sql", + "utf8", + ); + expect(content).toEqual("-- Enter migration here\n"); +}); + +it("creates current.sql when folder is false", async () => { + await init({ folder: false }); + + const dirStats = await statOrNull("migrations/current"); + expect(dirStats).toBeNull(); + + const fileStats = await statOrNull("migrations/current.sql"); + expect(fileStats?.isFile()).toBe(true); + + const content = await fsp.readFile("migrations/current.sql", "utf8"); + expect(content).toEqual("-- Enter migration here\n"); +}); diff --git a/src/commands/init.ts b/src/commands/init.ts index 7df09b4..318c0f4 100644 --- a/src/commands/init.ts +++ b/src/commands/init.ts @@ -202,7 +202,8 @@ export async function init(options: InitArgv = {}): Promise { }); await fsp.mkdir(parsedSettings.migrationsFolder); await fsp.mkdir(parsedSettings.migrationsFolder + "/committed"); - if (options.folder) { + const useFolder = options.folder !== false; + if (useFolder) { await fsp.mkdir(parsedSettings.migrationsFolder + "/current"); } const currentLocation = await getCurrentMigrationLocation(parsedSettings); @@ -230,7 +231,7 @@ Initializes a graphile-migrate project by creating a \`.gmrc\` file and \`migrat folder: { type: "boolean", description: "Use a folder rather than a file for the current migration.", - default: false, + default: true, }, }, handler: init, From 41533b0940c1ab5273d3fe1b32a38598bf0849ae Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 9 Nov 2026 14:36:16 +0000 Subject: [PATCH 2/3] Fix SQL error reporting for current/ folder migrations When the current migration lives in a folder, assembled SQL is executed as one script with --! split markers. Map PostgreSQL error positions back to the underlying file and line (fixes graphile/migrate#127) and pass the current/ path from the watcher runner. Co-authored-by: Joel Shearon --- __tests__/currentFolderErrors.test.ts | 46 ++++++++++++ __tests__/sqlSplitSourceMap.test.ts | 51 +++++++++++++ src/currentRunner.ts | 7 ++ src/instrumentation.ts | 55 ++++++++++---- src/migration.ts | 13 +++- src/sqlSplitSourceMap.ts | 101 ++++++++++++++++++++++++++ 6 files changed, 257 insertions(+), 16 deletions(-) create mode 100644 __tests__/currentFolderErrors.test.ts create mode 100644 __tests__/sqlSplitSourceMap.test.ts create mode 100644 src/sqlSplitSourceMap.ts diff --git a/__tests__/currentFolderErrors.test.ts b/__tests__/currentFolderErrors.test.ts new file mode 100644 index 0000000..407a2e4 --- /dev/null +++ b/__tests__/currentFolderErrors.test.ts @@ -0,0 +1,46 @@ +import { + InstrumentationError, + runQueryWithErrorInstrumentation, +} from "../src/instrumentation"; +import { Client } from "../src/pg"; + +const folderSql = `\ +--! split: 100-first.sql +select 1; + +--! split: 200-second.sql +-- line 1 of second +-- line 2 of second +select 1/0; +`; + +function makePgClientThatErrorsAt(body: string, substring: string): Client { + const position = body.indexOf(substring) + 1; + return { + query: jest.fn().mockRejectedValue( + Object.assign(new Error("division by zero"), { + position: String(position), + code: "22012", + }), + ), + } as unknown as Client; +} + +it("reports SQL errors against the file in current/ rather than concatenated current.sql", async () => { + const pgClient = makePgClientThatErrorsAt(folderSql, "1/0"); + let err: InstrumentationError | undefined; + try { + await runQueryWithErrorInstrumentation(pgClient, folderSql, "current.sql", { + splitBasePath: "migrations/current", + }); + } catch (e) { + err = e as InstrumentationError; + } + + expect(err).toBeTruthy(); + expect(err!._gmMessageOverride).toMatch( + /migrations\/current\/200-second\.sql/, + ); + expect(err!._gmMessageOverride).toMatch(/line 3,/); + expect(err!._gmMessageOverride).not.toMatch(/of "current\.sql"/); +}); diff --git a/__tests__/sqlSplitSourceMap.test.ts b/__tests__/sqlSplitSourceMap.test.ts new file mode 100644 index 0000000..71bcab0 --- /dev/null +++ b/__tests__/sqlSplitSourceMap.test.ts @@ -0,0 +1,51 @@ +import { + buildSplitSourceSegments, + resolveSqlPosition, +} from "../src/sqlSplitSourceMap"; + +const folderBody = `\ +--! Message: test + +--! split: 100-first.sql +select 1; + +--! split: 200-second.sql +-- line 1 of second +-- line 2 of second +select 1/0; + +--! split: 300-third.sql +select 3; +`; + +it("maps positions before the first split to the default filename", () => { + const segments = buildSplitSourceSegments(folderBody, { + defaultFilename: "current.sql", + splitBasePath: "migrations/current", + }); + expect(segments[0]).toMatchObject({ + filename: "current.sql", + start: 0, + }); +}); + +it("maps positions in later split files with folder paths", () => { + const errorChar = folderBody.indexOf("1/0"); + const resolved = resolveSqlPosition(folderBody, errorChar + 1, { + defaultFilename: "current.sql", + splitBasePath: "migrations/current", + }); + expect(resolved.filename).toBe("migrations/current/200-second.sql"); + expect(resolved.line).toBe(3); + expect(resolved.column).toBe(8); +}); + +it("falls back to a single segment when there are no split markers", () => { + const body = "select 1;\nselect 2;\n"; + const segments = buildSplitSourceSegments(body, { + defaultFilename: "migrations/current.sql", + }); + expect(segments).toEqual([ + { start: 0, end: body.length, filename: "migrations/current.sql" }, + ]); +}); diff --git a/src/currentRunner.ts b/src/currentRunner.ts index d2d040a..d3a765c 100644 --- a/src/currentRunner.ts +++ b/src/currentRunner.ts @@ -23,6 +23,10 @@ export function makeCurrentMigrationRunner( parsedSettings, currentLocation, ); + const splitBasePath = currentLocation.isFile + ? undefined + : currentLocation.path; + const runInstrumentation = splitBasePath ? { splitBasePath } : undefined; let migrationsAreEquivalent = false; try { @@ -70,6 +74,7 @@ export function makeCurrentMigrationRunner( "current.sql", undefined, true, + runInstrumentation, ); const previousBodyMinified = previousBody ? pgMinify(previousBody) @@ -115,6 +120,8 @@ export function makeCurrentMigrationRunner( body, "current.sql", undefined, + undefined, + runInstrumentation, ), ); } diff --git a/src/instrumentation.ts b/src/instrumentation.ts index 67111be..377c40a 100644 --- a/src/instrumentation.ts +++ b/src/instrumentation.ts @@ -4,6 +4,7 @@ import { QueryResultRow } from "pg"; import indent from "./indent"; import { Client } from "./pg"; import { ParsedSettings } from "./settings"; +import { resolveSqlPosition } from "./sqlSplitSourceMap"; export interface InstrumentationError extends Error { severity?: string; @@ -14,9 +15,19 @@ export interface InstrumentationError extends Error { _gmMessageOverride?: string; } +export interface RunQueryInstrumentationOptions { + /** When the SQL was assembled from a `current/` folder, the path to that directory. */ + splitBasePath?: string; +} + export async function runQueryWithErrorInstrumentation< T extends QueryResultRow = QueryResultRow, ->(pgClient: Client, body: string, filename: string): Promise { +>( + pgClient: Client, + body: string, + filename: string, + options?: RunQueryInstrumentationOptions, +): Promise { try { const { rows } = await pgClient.query({ text: body, @@ -29,40 +40,56 @@ export async function runQueryWithErrorInstrumentation< (typeof e.position === "string" || typeof e.position === "number") ) { const p = parseInt(String(e.position), 10); + const hasSplits = /^--! split: /m.test(body); + const resolved = hasSplits + ? resolveSqlPosition(body, p, { + defaultFilename: filename, + splitBasePath: options?.splitBasePath, + }) + : null; + + const sourceBody = resolved + ? body.substring(resolved.segment.start, resolved.segment.end) + : body; + const position0 = resolved + ? resolved.position0 - resolved.segment.start + : p - 1; + let line = 1; let column = 0; let idx = 0; - while (idx < p) { + while (idx <= position0) { column++; - const char = body[idx]; + const char = sourceBody[idx]; if (char === "\n") { line++; column = 0; - } else { - // ... } idx++; } - const endOfLine = body.indexOf("\n", p); - const previousNewline = body.lastIndexOf("\n", p); + + const endOfLine = sourceBody.indexOf("\n", position0); + const end = endOfLine === -1 ? sourceBody.length : endOfLine; + const previousNewline = sourceBody.lastIndexOf("\n", position0); const previousNewline2 = - body.lastIndexOf("\n", previousNewline - 1) || previousNewline; + sourceBody.lastIndexOf("\n", previousNewline - 1) || previousNewline; const previousNewline3 = - body.lastIndexOf("\n", previousNewline2 - 1) || previousNewline2; + sourceBody.lastIndexOf("\n", previousNewline2 - 1) || previousNewline2; const previousNewline4 = - body.lastIndexOf("\n", previousNewline3 - 1) || previousNewline3; + sourceBody.lastIndexOf("\n", previousNewline3 - 1) || previousNewline3; const startOfLine = previousNewline + 1; - const positionWithinLine = p - startOfLine; - const snippet = body.substring(previousNewline4 + 1, endOfLine); + const positionWithinLine = position0 - startOfLine; + const snippet = sourceBody.substring(previousNewline4 + 1, end); + const displayFilename = resolved?.filename ?? filename; const indentString = chalk.red("| "); const codeIndent = 2; const lines = [ chalk.bold.red( - `🛑 Error occurred at line ${line}, column ${column} of "${filename}":`, + `🛑 Error occurred at line ${line}, column ${column} of "${displayFilename}":`, ), chalk.reset(indent(indent(snippet, codeIndent), indentString)), indentString + - chalk.red("-".repeat(positionWithinLine - 1 + codeIndent) + "^"), + chalk.red("-".repeat(positionWithinLine + codeIndent) + "^"), indentString + chalk.red.bold((e as InstrumentationError).code) + chalk.red(": " + e.message), diff --git a/src/migration.ts b/src/migration.ts index 38f8a1c..c0b4b64 100644 --- a/src/migration.ts +++ b/src/migration.ts @@ -3,7 +3,10 @@ import { relative } from "path"; import { calculateHash } from "./hash"; import { isNoTransactionDefined } from "./header"; -import { runQueryWithErrorInstrumentation } from "./instrumentation"; +import { + RunQueryInstrumentationOptions, + runQueryWithErrorInstrumentation, +} from "./instrumentation"; import { mergeWithoutClobbering, realpathOrNull } from "./lib"; import memoize from "./memoize"; import { migrationFilenameMatches } from "./migrationFilename"; @@ -567,6 +570,7 @@ export async function runStringMigration( filename: string, committedMigration?: FileMigration, dryRun?: boolean, + instrumentation?: RunQueryInstrumentationOptions, ): Promise<{ sql: string; transaction: boolean }> { const placeholderReplacement = generatePlaceholderReplacement( parsedSettings, @@ -582,7 +586,12 @@ export async function runStringMigration( await pgClient.query("begin"); } try { - await runQueryWithErrorInstrumentation(pgClient, sql, filename); + await runQueryWithErrorInstrumentation( + pgClient, + sql, + filename, + instrumentation, + ); if (committedMigration) { const { hash, previousHash, filename } = committedMigration; await pgClient.query({ diff --git a/src/sqlSplitSourceMap.ts b/src/sqlSplitSourceMap.ts new file mode 100644 index 0000000..147234f --- /dev/null +++ b/src/sqlSplitSourceMap.ts @@ -0,0 +1,101 @@ +const SPLIT_LINE_REGEX = /^--! split: ([0-9]+(?:-[-_a-zA-Z0-9]+)?\.sql)$/gm; + +export interface SqlSourceSegment { + start: number; + end: number; + filename: string; +} + +export interface ResolvedSqlPosition { + filename: string; + line: number; + column: number; + /** 0-based offset into `body` */ + position0: number; + segment: SqlSourceSegment; +} + +export function buildSplitSourceSegments( + body: string, + options: { defaultFilename: string; splitBasePath?: string }, +): SqlSourceSegment[] { + const segments: SqlSourceSegment[] = []; + let currentFilename = options.defaultFilename; + let contentStart = 0; + + const splitPoints: Array<{ index: number; splitEnd: number; file: string }> = + []; + for (const match of body.matchAll(SPLIT_LINE_REGEX)) { + const index = match.index; + if (index === undefined) { + continue; + } + splitPoints.push({ + index, + splitEnd: index + match[0].length, + file: match[1], + }); + } + + if (splitPoints.length === 0) { + return [{ start: 0, end: body.length, filename: currentFilename }]; + } + + for (const sp of splitPoints) { + if (sp.index > contentStart) { + segments.push({ + start: contentStart, + end: sp.index, + filename: currentFilename, + }); + } + let nextStart = sp.splitEnd; + if (body[nextStart] === "\n") { + nextStart++; + } + currentFilename = options.splitBasePath + ? `${options.splitBasePath}/${sp.file}` + : sp.file; + contentStart = nextStart; + } + + if (contentStart < body.length) { + segments.push({ + start: contentStart, + end: body.length, + filename: currentFilename, + }); + } + + return segments; +} + +export function resolveSqlPosition( + body: string, + position1Based: number, + options: { defaultFilename: string; splitBasePath?: string }, +): ResolvedSqlPosition { + const position0 = position1Based - 1; + const segments = buildSplitSourceSegments(body, options); + const segment = + segments.find((s) => position0 >= s.start && position0 < s.end) ?? + segments[segments.length - 1]; + + let line = 1; + let column = 0; + for (let idx = segment.start; idx <= position0 && idx < segment.end; idx++) { + column++; + if (body[idx] === "\n") { + line++; + column = 0; + } + } + + return { + filename: segment.filename, + line, + column, + position0, + segment, + }; +} From 51809792cb3590b0e81cf7c46c4081dc637953cf Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 9 Nov 2026 14:38:54 +0000 Subject: [PATCH 3/3] Add folder error edge-case tests for single file and no position Cover the default init layout (one file in current/) and errors without a PostgreSQL position so diagnostics stay unchanged. Co-authored-by: Joel Shearon --- __tests__/currentFolderErrors.test.ts | 48 +++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/__tests__/currentFolderErrors.test.ts b/__tests__/currentFolderErrors.test.ts index 407a2e4..e233fa3 100644 --- a/__tests__/currentFolderErrors.test.ts +++ b/__tests__/currentFolderErrors.test.ts @@ -44,3 +44,51 @@ it("reports SQL errors against the file in current/ rather than concatenated cur expect(err!._gmMessageOverride).toMatch(/line 3,/); expect(err!._gmMessageOverride).not.toMatch(/of "current\.sql"/); }); + +it("reports errors against the sole file when current/ has only one migration", async () => { + const singleFileSql = `\ +--! split: 1-current.sql +select 1/0; +`; + const pgClient = makePgClientThatErrorsAt(singleFileSql, "1/0"); + let err: InstrumentationError | undefined; + try { + await runQueryWithErrorInstrumentation( + pgClient, + singleFileSql, + "current.sql", + { + splitBasePath: "migrations/current", + }, + ); + } catch (e) { + err = e as InstrumentationError; + } + + expect(err).toBeTruthy(); + expect(err!._gmMessageOverride).toMatch( + /migrations\/current\/1-current\.sql/, + ); + expect(err!._gmMessageOverride).toMatch(/line 1,/); +}); + +it("does not fabricate line/column diagnostics when the error has no position", async () => { + const pgClient = { + query: jest + .fn() + .mockRejectedValue( + Object.assign(new Error("could not connect"), { code: "08006" }), + ), + } as unknown as Client; + let err: InstrumentationError | undefined; + try { + await runQueryWithErrorInstrumentation(pgClient, folderSql, "current.sql", { + splitBasePath: "migrations/current", + }); + } catch (e) { + err = e as InstrumentationError; + } + + expect(err).toBeTruthy(); + expect(err!._gmMessageOverride).toBeUndefined(); +});