Skip to content
Merged
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
2 changes: 1 addition & 1 deletion parser/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ const parser = new Parser(options?: { version?: 13 | 14 | 15 | 16 | 17 });

#### Properties
- `version`: The PostgreSQL version used by this parser instance
- `ready`: A promise that resolves when the parser is fully loaded
- `ready`: A promise that resolves when the parser is fully loaded or rejects if loading fails. After a failure, the next load attempt replaces it with a new promise.

#### Methods

Expand Down
27 changes: 20 additions & 7 deletions parser/templates/index.cjs.template
Original file line number Diff line number Diff line change
Expand Up @@ -15,30 +15,43 @@ class Parser {
this.parser = null;
this._loadPromise = null;

// Create the ready promise
this.ready = new Promise((resolve) => {
this._resetReady();
}

_resetReady() {
this.ready = new Promise((resolve, reject) => {
this._resolveReady = resolve;
this._rejectReady = reject;
});
// Callers may await loadParser() or parse() without observing ready.
this.ready.catch(() => {});
}

async loadParser() {
if (this.parser) return;

// Ensure we only load once
// Share the current attempt, but allow a failed attempt to be retried.
if (!this._loadPromise) {
this._loadPromise = this._doLoad();
if (!this._rejectReady) this._resetReady();
this._loadPromise = this._doLoad().catch((error) => {
this._loadPromise = null;
this._rejectReady(error);
this._rejectReady = null;
throw error;
});
}

return this._loadPromise;
}

async _doLoad() {
// Dynamic require for CommonJS
this.parser = require(`./v${this.version}/index.cjs`);
const module = require(`./v${this.version}/index.cjs`);

if (this.parser.loadModule) {
await this.parser.loadModule();
if (module.loadModule) {
await module.loadModule();
}
this.parser = module;

// Resolve the ready promise
this._resolveReady();
Expand Down
26 changes: 19 additions & 7 deletions parser/templates/index.js.template
Original file line number Diff line number Diff line change
Expand Up @@ -15,30 +15,42 @@ export class Parser {
this.parser = null;
this._loadPromise = null;

// Create the ready promise
this.ready = new Promise((resolve) => {
this._resetReady();
}

_resetReady() {
this.ready = new Promise((resolve, reject) => {
this._resolveReady = resolve;
this._rejectReady = reject;
});
// Callers may await loadParser() or parse() without observing ready.
this.ready.catch(() => {});
}

async loadParser() {
if (this.parser) return;

// Ensure we only load once
// Share the current attempt, but allow a failed attempt to be retried.
if (!this._loadPromise) {
this._loadPromise = this._doLoad();
if (!this._rejectReady) this._resetReady();
this._loadPromise = this._doLoad().catch((error) => {
this._loadPromise = null;
this._rejectReady(error);
this._rejectReady = null;
throw error;
});
}

return this._loadPromise;
}

async _doLoad() {
const module = await import(`./v${this.version}/index.js`);
this.parser = module;

if (this.parser.loadModule) {
await this.parser.loadModule();
if (module.loadModule) {
await module.loadModule();
}
this.parser = module;

// Resolve the ready promise
this._resolveReady();
Expand Down
43 changes: 42 additions & 1 deletion parser/test/esm.test.mjs
Original file line number Diff line number Diff line change
@@ -1,9 +1,50 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';

const { versions } = JSON.parse(readFileSync(new URL('../wasm/build-info.json', import.meta.url), 'utf8'));

describe('Parser load retries', () => {
for (const [format, extension] of [['ESM', 'js'], ['CommonJS', 'cjs']]) {
it(`retries failed ${format} loads and settles ready for each attempt`, async (t) => {
const dir = mkdtempSync(join(tmpdir(), 'pgsql-parser-'));
t.after(() => rmSync(dir, { recursive: true, force: true }));
const entry = `index.${extension}`;
copyFileSync(new URL(`../wasm/${entry}`, import.meta.url), join(dir, entry));

for (const version of versions) {
const versionDir = join(dir, `v${version}`);
mkdirSync(versionDir);
writeFileSync(join(versionDir, entry), version === '18' ? `
let attempts = 0;
async function loadModule() {
if (++attempts === 1) throw new Error('temporary load failure');
}
function parse(query) { return { query, attempts }; }
${format === 'ESM' ? 'export { loadModule, parse };' : 'module.exports = { loadModule, parse };'}
` : '');
}

const mod = await import(pathToFileURL(join(dir, entry)));
const Parser = format === 'ESM' ? mod.Parser : mod.default.Parser;
const parser = new Parser({ version: 18 });
await Promise.all([
assert.rejects(parser.ready, /temporary load failure/),
assert.rejects(parser.parse('SELECT 1'), /temporary load failure/),
assert.rejects(parser.parse('SELECT 2'), /temporary load failure/),
]);
assert.throws(() => parser.parseSync('SELECT 1'), /Parser not loaded/);

const retry = parser.parse('SELECT 1');
assert.deepEqual(await retry, { query: 'SELECT 1', attempts: 2 });
await parser.ready;
});
}
});

describe('ESM entry points', () => {
it('imports the root entry and parses with every bundled version', async () => {
const { Parser } = await import('@pgsql/parser');
Expand Down
Loading