Skip to content

fix(v18): throw SqlError from fingerprint, normalize, and scan - #204

Closed
pyramation wants to merge 2 commits into
mainfrom
feat/pg18-structured-sql-errors
Closed

pyramation wants to merge 2 commits into
mainfrom
feat/pg18-structured-sql-errors

Conversation

@pyramation

@pyramation pyramation commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

PG18 fingerprint, normalize, and scan now read structured WASM results, so PostgreSQL failures throw SqlError with the original message, zero-based cursor, and source details. Previously, grammar errors without a recognized prefix could pass as results, and scanner lexer errors could surface as JSON SyntaxError.

Regression tests cover sync and async calls for all three operations. WASM allocation failures still use the existing OOM path; successful results are unchanged. This replaces the typed-error portion of #183; scanner JSON escaping is separate.


libpg-query and parser opened this PR for Dan
Implemented in session Throw typed SqlError from fingerprint, normalize and scan
Review with Devin · Open in Devin Desktop


Summary by CodeRabbit

  • New Features
    • Added synchronous and asynchronous SQL scanning, returning structured scan results.
  • Bug Fixes
    • Fingerprinting, normalization, and scanning now report structured SQL errors with available source and cursor details.
    • Improved handling of WebAssembly memory failures during these operations.
  • Documentation
    • Clarified error details available for parsing, fingerprinting, normalization, and scanning.

@devin-ai-integration

Copy link
Copy Markdown
Contributor

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@luxor-code-review

luxor-code-review Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Review complete. No blocking issues — approved ✅; 1 nitpick below.

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Document new WASM ABI and error contract for fingerprint/normalize/scan (wasm_wrapper.c:231) — The raw WASM exports _wasm_fingerprint, _wasm_normalize_query, and _wasm_scan changed return type from char* to WasmDetailedResult*, and their JS wrappers now throw SqlError (with sqlDetails) for any backend error instead of prefix-matched plain Error (templates/full/index.ts:299).

This PR ports the parse layer to PostgreSQL 18 and replaces the string-based error path with a structured FFI contract: new C wrapper entry points return a PgQueryError-bearing result struct that the TypeScript side maps into typed SqlError objects (message, cursor position, line number, context). | Files | Change | | --- | --- | | versions/18/src/wasm_wrapper.c, templates/full/wasm_wrapper.c | Add wasm_fingerprint, wasm_normalize, and wasm_scan wrappers with structured error results and explicit memory-ownership transfers. | | versions/18/src/index.ts, templates/full/index.ts | Bind the new exports, read result/error structs at fixed offsets, map error fields to SqlError, and handle the OOM sentinel. | | versions/18/src/libpg-query.d.ts, templates/full/libpg-query.d.ts | Update type declarations for the new entry points and error payload. | | versions/18/README_ERROR_HANDLING.md | Document the new error contract, error fields, and caller obligations. | | versions/18/test/pg18.test.js | Update tests to the new error shape and message expectations. | Review verified the struct-offset mapping, free-on-error ownership paths, and error-message parity against the old behavior; only one low-severity documentation-consistency point remains.

Reviewed commit: 19ebada

@coderabbitai

coderabbitai Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The full template and PostgreSQL 18 implementation now use detailed WASM results for fingerprinting, normalization, and scanning. Their asynchronous and synchronous APIs expose structured SQL errors, and PostgreSQL 18 adds synchronous scanning.

Changes: Structured WASM results and TypeScript APIs

Layer / File(s) Summary
Detailed WASM result wrappers
templates/full/wasm_wrapper.c, versions/18/src/wasm_wrapper.c, templates/full/libpg-query.d.ts, versions/18/src/libpg-query.d.ts
Fingerprint, normalize, and scan wrappers now return detailed results with output data or error details. Scan JSON allocation failures return NULL instead of an error string or empty-token JSON fallback.
TypeScript APIs and error validation
templates/full/index.ts, versions/18/src/index.ts, versions/18/test/pg18.test.js, versions/18/README_ERROR_HANDLING.md
Fingerprint and normalize APIs use a shared detailed-result path. The APIs convert reported errors to SqlError and add asynchronous and synchronous scan methods. PostgreSQL 18 tests cover structured errors, and its documentation describes sqlDetails.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant scan
  participant callDetailed
  participant wasm_scan
  Caller->>scan: query
  scan->>callDetailed: invoke _wasm_scan
  callDetailed->>wasm_scan: query pointer
  wasm_scan-->>callDetailed: detailed result
  callDetailed-->>scan: result data or SqlError
  scan->>Caller: parsed ScanResult or rejection
Loading

Possibly related PRs

Merge Risk: Minimal · up to 348ee

This change makes fingerprint, normalize and scan throw structured SQL errors that keep the original message and cursor position, and adds scan APIs for PostgreSQL 18. The review found no concrete defects, and allocation failures still take the existing out-of-memory path, so it looks ready to merge.

Architecture risk: Medium · up to 348ee

The change affects 2 systems.

Changed systems: versions, templates

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — versions (service) was modified; 5 changed files map to changed impact.
  • observed — templates (service) was modified; 3 changed files map to changed impact.

Before / after behavior

  • observed — Modified behavior in templates/full/index.ts: WasmModule adds the _wasm_free_detailed_result function declaration.
  • observed — Modified behavior in templates/full/index.ts: Removed throwIfErrorString, which previously converted selected error-string prefixes—including syntax, deparse, general, and stack-depth errors—into plain Error instances and handled the exact out of memory string.
  • observed — Modified behavior in templates/full/index.ts: Adds callDetailed for fingerprinting, normalization, and scanning. It reads detailed WASM results, turns reported errors into SqlError with available source and position metadata, converts out-of-memory results into stale-instance handling, and frees allocations only when no WASM call failure occurred.
  • observed — Modified behavior in templates/full/index.ts: Async fingerprint and normalize replace separate raw-string WASM calls, error-string checks, and cleanup with calls to callDetailed.

Reliability and maintainability

  • inferred — Risk-relevant change factors for versions: blast_radius_1; direct_dependents_1
  • inferred — Risk-relevant change factors for templates: blast_radius_1; direct_dependents_1
Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: fingerprint, normalize, and scan in v18 now throw SqlError. The raw summary shows the shared callDetailed path, the WASM detailed-result API, and new sync/async tests …
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: fingerprint, normalize, and scan in v18 now throw SqlError. The raw summary shows the shared callDetailed path, the WASM detailed-result API, and new sync/async tests for SqlError in the v18 files, which match this title. The title uses the conventional type(scope) prefix and is concise. The title does not mention the detailed WASM result change or the scan JSON construction change, but it does not need to cover every detail.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 19ebada and 348eea6.

Files selected for processing: 2

  • templates/full/wasm_wrapper.c
  • versions/18/src/wasm_wrapper.c

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@devin-ai-integration devin-ai-integration Bot left a comment

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.

Devin Review found 1 finding. It is left for you to triage below.

View findings in Devin Review · Follow Devin's work

Devin Review

Comment thread 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.

…sql-errors

# Conflicts:
#	templates/full/wasm_wrapper.c
#	versions/18/src/wasm_wrapper.c
@devin-ai-integration

Copy link
Copy Markdown
Contributor

Superseded by #207, which combines the PG18 typed SQL errors and WASM recovery fixes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant