Skip to content
Closed
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
185 changes: 54 additions & 131 deletions templates/full/index.ts

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 SQL error offsets drift after emoji

When an SQL error follows an emoji, callDetailed reports an offset too early for the JavaScript query string. PostgreSQL counts the emoji once, but formatSqlError uses the position as a JavaScript string index.

Devin left this for you to triage: The new methods intentionally match parseSync’s PostgreSQL character offset: for SELECT '😀', 'abc all four report 12, while JavaScript substring indexing locates the quote at 13. Fix the existing formatSqlError indexing separately so this PR preserves the parse contract and stays limited to typed errors.

(Refers to this code)

Learn more

PostgreSQL reports the cursor as a one-based count of Unicode characters. JavaScript indexes strings by UTF-16 code units, so a supplementary character such as an emoji occupies two index positions instead of one. The new structured-error path only changes the base from one to zero. The built-in formatSqlError then uses that offset to position the caret and to truncate the query.

Example: In SELECT '😀', 'abc, PostgreSQL reports position 13 for the unclosed quote. Subtracting one yields 12, which indexes the preceding space in JavaScript; the quote is at index 13.

Recommended fix: In the full template, convert positive PostgreSQL cursor positions to UTF-16 offsets by advancing through the original query by Unicode code point and accumulating each point’s code-unit width. Regenerate the v18 source and add a supplementary-character regression case for the three operations and their sync variants.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ interface WasmModule {
_malloc: (size: number) => number;
_free: (ptr: number) => void;
_wasm_free_string: (ptr: number) => void;
_wasm_free_detailed_result: (ptr: number) => void;
_wasm_parse_query: (queryPtr: number) => number;
_wasm_parse_query_raw: (queryPtr: number) => number;
_wasm_free_parse_result: (ptr: number) => void;
Expand Down Expand Up @@ -220,13 +221,6 @@ function outOfMemoryError(): Error {
return new Error('libpg_query ran out of WASM memory (heap limit is WASM_MAXIMUM_MEMORY, 1 GiB); parse large inputs in smaller pieces');
}

function throwIfErrorString(resultStr: string): void {
if (resultStr === 'out of memory') throw outOfMemoryError();
if (resultStr.startsWith('syntax error') || resultStr.startsWith('deparse error') || resultStr.startsWith('ERROR') || resultStr.startsWith('stack depth limit exceeded')) {
throw new Error(resultStr);
}
}

function ensureLoaded() {
if (!wasmModule) throw new Error("WASM module not initialized. Call `loadModule()` first.");
}
Expand Down Expand Up @@ -300,6 +294,52 @@ function ptrToString(ptr: number): string {
return wasmModule.UTF8ToString(ptr);
}

type DetailedOperation = '_wasm_fingerprint' | '_wasm_normalize_query' | '_wasm_scan';

function callDetailed(query: string, operation: DetailedOperation): string {
if (!wasmModule) {
throw new Error('WASM module not initialized. Call loadModule() first.');
}
const queryPtr = stringToPtr(query);
const failuresBefore = failures;
let resultPtr = 0;

try {
resultPtr = callWasm(() => wasmModule[operation](queryPtr));
if (!resultPtr) throw outOfMemoryError();

// WasmDetailedResult uses 32-bit fields and pointers.
if (wasmModule.getValue(resultPtr, 'i32')) {
const readString = (offset: number) => {
const ptr = wasmModule.getValue(resultPtr + offset, 'i32');
return ptr ? wasmModule.UTF8ToString(ptr) : undefined;
};
const message = readString(4) ?? 'Unknown error';
if (message === 'out of memory') throw outOfMemoryError();

const lineno = wasmModule.getValue(resultPtr + 16, 'i32');
const cursorpos = wasmModule.getValue(resultPtr + 20, 'i32');
const context = readString(24);
throw new SqlError(message, {
message,
cursorPosition: cursorpos > 0 ? cursorpos - 1 : 0,
fileName: readString(12),
functionName: readString(8),
lineNumber: lineno > 0 ? lineno : undefined,
...(context !== undefined ? { context } : {})
});
}
return wasmModule.UTF8ToString(wasmModule.getValue(resultPtr + 28, 'i32'));
} finally {
if (failures === failuresBefore) {
wasmModule._free(queryPtr);
if (resultPtr) {
wasmModule._wasm_free_detailed_result(resultPtr);
}
}
}
}

export const parse = awaitInit(async (query: string): Promise<ParseResult> => {
// Input validation
if (query === null || query === undefined) {
Expand Down Expand Up @@ -390,47 +430,11 @@ export const parsePlPgSQL = awaitInit(async (query: string): Promise<ParseResult
});

export const fingerprint = awaitInit(async (query: string): Promise<string> => {
const queryPtr = stringToPtr(query);
const failuresBefore = failures;
let resultPtr = 0;

try {
resultPtr = callWasm(() => wasmModule._wasm_fingerprint(queryPtr));
const resultStr = ptrToString(resultPtr);

throwIfErrorString(resultStr);

return resultStr;
} finally {
if (failures === failuresBefore) {
wasmModule._free(queryPtr);
if (resultPtr) {
wasmModule._wasm_free_string(resultPtr);
}
}
}
return callDetailed(query, '_wasm_fingerprint');
});

export const normalize = awaitInit(async (query: string): Promise<string> => {
const queryPtr = stringToPtr(query);
const failuresBefore = failures;
let resultPtr = 0;

try {
resultPtr = callWasm(() => wasmModule._wasm_normalize_query(queryPtr));
const resultStr = ptrToString(resultPtr);

throwIfErrorString(resultStr);

return resultStr;
} finally {
if (failures === failuresBefore) {
wasmModule._free(queryPtr);
if (resultPtr) {
wasmModule._wasm_free_string(resultPtr);
}
}
}
return callDetailed(query, '_wasm_normalize_query');
});

// Sync versions
Expand Down Expand Up @@ -531,98 +535,17 @@ export function parsePlPgSQLSync(query: string): ParseResult {
}

export function fingerprintSync(query: string): string {
if (!wasmModule) {
throw new Error('WASM module not initialized. Call loadModule() first.');
}
const queryPtr = stringToPtr(query);
const failuresBefore = failures;
let resultPtr = 0;

try {
resultPtr = callWasm(() => wasmModule._wasm_fingerprint(queryPtr));
const resultStr = ptrToString(resultPtr);

throwIfErrorString(resultStr);

return resultStr;
} finally {
if (failures === failuresBefore) {
wasmModule._free(queryPtr);
if (resultPtr) {
wasmModule._wasm_free_string(resultPtr);
}
}
}
return callDetailed(query, '_wasm_fingerprint');
}

export function normalizeSync(query: string): string {
if (!wasmModule) {
throw new Error('WASM module not initialized. Call loadModule() first.');
}
const queryPtr = stringToPtr(query);
const failuresBefore = failures;
let resultPtr = 0;

try {
resultPtr = callWasm(() => wasmModule._wasm_normalize_query(queryPtr));
const resultStr = ptrToString(resultPtr);

throwIfErrorString(resultStr);

return resultStr;
} finally {
if (failures === failuresBefore) {
wasmModule._free(queryPtr);
if (resultPtr) {
wasmModule._wasm_free_string(resultPtr);
}
}
}
return callDetailed(query, '_wasm_normalize_query');
}

export const scan = awaitInit(async (query: string): Promise<ScanResult> => {
const queryPtr = stringToPtr(query);
const failuresBefore = failures;
let resultPtr = 0;

try {
resultPtr = callWasm(() => wasmModule._wasm_scan(queryPtr));
const resultStr = ptrToString(resultPtr);

throwIfErrorString(resultStr);

return JSON.parse(resultStr);
} finally {
if (failures === failuresBefore) {
wasmModule._free(queryPtr);
if (resultPtr) {
wasmModule._wasm_free_string(resultPtr);
}
}
}
return JSON.parse(callDetailed(query, '_wasm_scan'));
});

export function scanSync(query: string): ScanResult {
if (!wasmModule) {
throw new Error('WASM module not initialized. Call loadModule() first.');
}
const queryPtr = stringToPtr(query);
const failuresBefore = failures;
let resultPtr = 0;

try {
resultPtr = callWasm(() => wasmModule._wasm_scan(queryPtr));
const resultStr = ptrToString(resultPtr);

throwIfErrorString(resultStr);

return JSON.parse(resultStr);
} finally {
if (failures === failuresBefore) {
wasmModule._free(queryPtr);
if (resultPtr) {
wasmModule._wasm_free_string(resultPtr);
}
}
}
}
return JSON.parse(callDetailed(query, '_wasm_scan'));
}
2 changes: 2 additions & 0 deletions templates/full/libpg-query.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ declare module './libpg-query.js' {
_malloc: (size: number) => number;
_free: (ptr: number) => void;
_wasm_free_string: (ptr: number) => void;
_wasm_free_detailed_result: (ptr: number) => void;
_wasm_parse_query: (queryPtr: number) => number;
_wasm_parse_plpgsql: (queryPtr: number) => number;
_wasm_fingerprint: (queryPtr: number) => number;
_wasm_normalize_query: (queryPtr: number) => number;
_wasm_scan: (queryPtr: number) => number;
lengthBytesUTF8: (str: string) => number;
stringToUTF8: (str: string, ptr: number, len: number) => void;
UTF8ToString: (ptr: number) => string;
Expand Down
Loading
Loading