Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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]
```


Expand Down
94 changes: 94 additions & 0 deletions __tests__/currentFolderErrors.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
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"/);
});

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();
});
54 changes: 54 additions & 0 deletions __tests__/init.test.ts
Original file line number Diff line number Diff line change
@@ -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");
});
51 changes: 51 additions & 0 deletions __tests__/sqlSplitSourceMap.test.ts
Original file line number Diff line number Diff line change
@@ -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" },
]);
});
5 changes: 3 additions & 2 deletions src/commands/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,8 @@ export async function init(options: InitArgv = {}): Promise<void> {
});
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);
Expand Down Expand Up @@ -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,
Expand Down
7 changes: 7 additions & 0 deletions src/currentRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -70,6 +74,7 @@ export function makeCurrentMigrationRunner(
"current.sql",
undefined,
true,
runInstrumentation,
);
const previousBodyMinified = previousBody
? pgMinify(previousBody)
Expand Down Expand Up @@ -115,6 +120,8 @@ export function makeCurrentMigrationRunner(
body,
"current.sql",
undefined,
undefined,
runInstrumentation,
),
);
}
Expand Down
55 changes: 41 additions & 14 deletions src/instrumentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<T[] | undefined> {
>(
pgClient: Client,
body: string,
filename: string,
options?: RunQueryInstrumentationOptions,
): Promise<T[] | undefined> {
try {
const { rows } = await pgClient.query<T>({
text: body,
Expand All @@ -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),
Expand Down
Loading