v1.18.0 — Performance Overhaul, Fingerprint v2 & Parser Fixes
Covers everything merged since v1.17.0, mostly the November 2026 performance
overhaul: an allocation-light tokenizer, parser and AST, pooled linting and
scanning, a single-pass dialect detector, a token-stream query fingerprint
(version 2) and a CI perf gate that measures every change across randomized
code layouts. It also fixes parser gaps users hit in real queries: INSERT
target aliases, locking clauses before LIMIT, CREATE OR REPLACE FUNCTION
without a dialect, and table functions and <-> in the dialect-free parser.
Measured against v1.17.0 on the same machine (Apple M4, Go 1.27, 5 interleaved
rounds, 290 benchmarks common to both releases), time per operation is 24%
lower on geometric mean and no benchmark is more than 5% slower. Highlights:
parsing 21-28% faster on the baseline queries, gosqlx.Lint 58-62% faster
with 73-77% fewer allocations, ScanSQL 80% faster, and fingerprinting a
join query 58% faster with 1 allocation instead of 84.
The release is source-compatible: exported Go signatures are unchanged apart
from additions. Three contracts change (fingerprint format, pool statistics,
linter rule resource lifetime) and the Claude Code plugin drops its
GOSQLX_MCP_URL override, so read Breaking Changes, Behavior changes
and docs/MIGRATION.md before upgrading.
Breaking Changes
- Claude Code plugin (
plugins/gosqlx): theGOSQLX_MCP_URLenvironment override is removed; the plugin always points athttps://mcp.gosqlx.dev/mcp, as Anthropic's plugin directory requires literal server URLs.- Migration: to use a local or self-hosted server, add
gosqlx-mcpas its own MCP server in your Claude Code configuration (see the plugin README) instead of settingGOSQLX_MCP_URL.
- Migration: to use a local or self-hosted server, add
- Pool statistics [W1-07]: Get/Put operations are counted only while metrics are enabled. While disabled,
metrics.GetPoolStatsreturns zero values for the three standard pools and omits custom pools. Counts collected earlier remain available when metrics are enabled again. Thegosqlx statscommand never enables metrics, so a fresh process prints zeros (as it effectively did before); callmetrics.Enable()before the work you want counted.- Migration: Call
metrics.Enable()before the workload to be measured, for example at process start. Tests asserting pool balance throughGetPoolStatsdeltas should enable metrics first and restore the previous state in cleanup. Counts are not retroactive.
- Migration: Call
- Version-2 query normalisation [W5-08]:
fingerprint.Normalize,fingerprint.Fingerprint,gosqlx.Normalizeandgosqlx.Fingerprintnow use the token-stream normal form. Fingerprints are"v2:"plus 64 lowercase hex characters (67 bytes); storage limited toCHAR(64)must be widened. Normalized text upper-cases keywords, drops aliasAS, joinINNER/OUTERand defaultASC, redacts LIMIT/OFFSET, FETCH/TOP, typed literals and utility-statement literals, and collapses repeated normalized IN-list elements and VALUES rows, including question-mark placeholders. Keyword name parts next to a dot retain their source case, includingASC; otherASCtokens are dropped. WithOptions.Dialectset tomysql,mariadborbigquery, double-quoted tokens follow the string-literal rules, including redaction and existing literal-alias exceptions. This deliberately coarsens MySQL/MariaDBANSI_QUOTESidentifiers. Default andpostgresqldialects retain double-quoted identifier handling; legacy mode is unchanged. Session variables retain their spelling:@@versionand@@session.sql_moderender without a space after@@. Tokenizable SQL with invalid syntax is accepted; callgosqlx.Validatefirst when syntax validation is required. Normalized text is a grouping key, not guaranteed to be parseable SQL. Parser limitations include implicit aliases withoutASin RETURNING, projections, subqueries and view queries, redactedSRID ?values and transaction batches without statement separators.ASis retained in XMLATTRIBUTES and XMLFOREST. Grouping also differs for cast spelling,IS TRUEversusIS FALSE, quoted keyword names, clause order, redundant parentheses and content omitted by the legacy formatter. Version 2 also preserves the source case of bare identifier tokens in contextual grammar positions that the legacy formatter upper-cases:SHOW server_versionandSHOW SERVER_VERSION, for example, produce different version-2 fingerprints but the same legacy fingerprint.- Migration: widen fingerprint columns to at least 67 bytes. Reproduce
stored v1.17 fingerprints exactly with
fingerprint.FingerprintWithOptions(sql, fingerprint.Options{Mode: fingerprint.ModeLegacy})and usefingerprint.VersionOfto tell versions apart. Recompute stored values, or key on both versions while migrating.
- Migration: widen fingerprint columns to at least 67 bytes. Reproduce
stored v1.17 fingerprints exactly with
- Linter rule resource lifetime:
LintStringand all convenience wrappers now release the parsed AST and recycle token storage after checking every rule set, including custom, configured, subset and empty sets. AST nodes,Context.Nodes()slices/elements, token slices/elements andWordpointers are borrowed only during eachRule.Check. Retaining them through a saved context, visitor, closure, background goroutine or state later used byFixis no longer supported; Go signatures and violation outputs are unchanged.- Migration: materialize strings such as
tok.Token.Valueortok.Token.Word.Value(after a nil check), scalars and value locations duringCheck, or make independently owned deep copies. Shallow token or slice copies can retain pooled pointers. Join all goroutines using borrowed resources beforeCheckreturns. HaveFixuse its SQL argument and materialized violations instead of references saved byCheck.
- Migration: materialize strings such as
Added
pkg/formatter: width-scaling regression guard forBenchmarkRenderScale/wide(exact output, time ratio and bytes per output byte over compact/lower/readable/semicolon/postgresql modes); test-only, no behaviour change (#958, W5-13).- Benchmark and perf-gate infrastructure (performance overhaul, wave 0):
pull requests are now judged by interleaved A/B measurements instead of
absolute numbers. No library behaviour changes apart from #901 (see Fixed). The pieces, by PR:
- Corpus and behaviour guards: the benchmark corpus manifest and
internal/benchcorpusloader (#895); behaviour goldens (token, parse, format, lint, scan and transpile hashes) over every corpus and dialect (#915); wall-clock test assertions replaced with ratio and count checks (#899); ClickHouse/Snowflake lambda bodies andU&in dialects without&fixed so the goldens could be pinned (#901). - Benchmark matrix: tokenizer and parse stages (#913), server shapes with
AllocsPerRunbudgets, a stack-depth test and a frame-size script (#909), high-level, render and transform (#911), transpile with a prefilter differential test (#912), interop benchmarks and a binary-size budget (#908), and lint, security and LSP (#910). - Competitor harness: new pure-Go peers (dolthub/vitess, rqlite/sql, AfterShip/clickhouse-sql-parser, auxten/postgresql-parser), ORM-style queries, lexer, render, normalize, fresh-goroutine, parallel and per-dialect cells with checked-in common-accept sets, and a schema v2 results file that keeps every v1 field (#914).
- Gate: an interleaved A/B workflow in shadow mode (
GOGC=off,-cpu 1, ABBA rounds, benchstat at alpha 0.01, A/A noise control;allocs/op,B/opand instruction-count gates) withtask bench:abandtask bench:gate(#916). - Baselines and docs (#917): per-architecture
benchmarks/baselines/{amd64,arm64}.jsonholding trend-only ns/op and gated B/op and allocs/op, checked or regenerated withtask bench:baselineandtask bench:baseline:update(local-only until W0-13 wires the check intoperf-gate.yml; CI currently gates allocs/op and B/op relatively via the A/B gate); newtask bench:matrixandtask pgo:refresh;docs/PERFORMANCE_METHODOLOGY.md(method, how to run an A/B, how the gate decides, claims policy).performance_baselines.jsonandTestPerformanceRegressionare now documented as a smoke test only, and its never-enforcedTokenizationThroughputandEndToEndSustainedentries are removed. - Gate: code-layout randomization. Each arm is now 20 test binaries linked
with
-ldflags=-randlayout=<seed>(base and head share seeds), one per round, and time is judged by an exact Mann-Whitney U over the per-layout medians with Benjamini-Hochberg false-discovery control at 0.01 across the suite. Changes that only move code (padding a struct, one extra linker-emitted function) no longer read as regressions on some runner CPUs. The A/A control is now A/A': the base revision under a disjoint seed set, which measures the layout variance. The report names the runner CPU and each benchmark's layout spread. Defaults are now 20 rounds of 100ms (-k/LAYOUTSsets the layout count,-k 0turns it off). A noisy A/A' re-links every arm with fresh seeds before its one re-run. The report lists the benchmarks with under 80% estimated power to catch a lone +5% slowdown, and warns when the layout count cannot reach the Benjamini-Hochberg level at all (matrix mode). Gate timeouts were raised to 35 minutes for the step (40 after W0-16, below) and 45 for the job (worst case measured at 21.7 minutes on an EPYC 7763).
- Corpus and behaviour guards: the benchmark corpus manifest and
- Parser: the PostgreSQL distance operator
<->now parses when no dialect is set, in every clause position (WHERE a <-> b,ORDER BY a <-> b, the select list,GROUP BY). PostgreSQL already accepted it; the named dialects, includinggeneric, still reject it. - Parser: with no dialect,
genericorpostgresql, SELECT now accepts a limit clause after the locking clause, the PostgreSQL orderSELECT ... ORDER BY x FOR UPDATE SKIP LOCKED LIMIT n. AfterFOR UPDATEeach ofLIMIT/OFFSET/FETCH FIRSTmay appear at most once, in any order;OFFSETcombines with either, butLIMITandFETCHare mutually exclusive, and a limit-clause token on both sides of the locking clause is invalid — all verified against libpg_query. The SQL-standard orderLIMIT ... FOR UPDATEwas already accepted; The other named dialects keep rejectingFOR UPDATE ... LIMIT: MySQL and MariaDB putLIMITfirst, and SQLite, Snowflake, ClickHouse, SQL Server, Oracle, BigQuery and Redshift are unchanged.SQL()renders the clauses in canonical order, soSELECT ... FOR UPDATE OFFSET 5 LIMIT 10comes back asLIMIT 10 OFFSET 5 FOR UPDATE— valid and equivalent PostgreSQL. - Parser/AST: INSERT now accepts the PostgreSQL target-table alias
INSERT INTO t AS u [(cols)] .... The alias is stored inInsertStatement.Extras.TableAlias(withTableAliasQuotefor delimited identifiers, mirroringTableNameQuote) and rendered back bySQL()asINSERT INTO t AS u. Only theASform is accepted — a bare alias withoutASis invalid SQL for an INSERT target (real PostgreSQL rejectsINSERT INTO t u), soASin that position stays unambiguous across dialects. The MySQL row alias (VALUES (...) AS r) and theINSERT ... SELECT ... FROM s AS xsource alias are unaffected. Verified against libpg_query:INSERT INTO t AS u (a) VALUES (1)parses,INSERT INTO t u (a) VALUES (1)does not. - Parser: table-valued function calls in FROM (
SELECT * FROM generate_series(1, 3) AS t(x)) now parse when no dialect is set or thegenericdialect is selected. The other named dialects already accepted them. Malformed calls are still rejected in every dialect. - Perf gate: adaptive layout counts size each benchmark to 80% estimated power
for a lone +5% slowdown, using empirical-AUC Noether power instead of
the MAD normal model.
-Bsets the extension budget,-Ethe deadline, and-Kthe per-arm cap;-Gspends up to 600 seconds more by default. Raw files carrysuite-line:labels; reports add K/power columns and list remaining Low power benchmarks with reasons, separate planned extensions from line warm-ups, show configured power targets and unknown estimates, and say when adaptive layouts were skipped because timings were not judged. Only primary time uses extra layouts; all other rules use stage-1 data. The perf step timeout rises from 35 to 40 minutes; the job cap stays at 45 minutes. Library behaviour is unchanged. [W0-16] - Fingerprint modes and dialect options [W5-08]:
fingerprint.Options,Mode,NormalizeWithOptionsandFingerprintWithOptionssupport token-stream and legacy normalisation with dialect selection in both modes;VersionOf,Version,VersionPrefixandErrEmptyexpose the version and empty-input contract. Thegosqlxpackage adds no options entry points; importpkg/fingerprintforModeLegacy(the v1.17 output and syntax-error contract) and dialect selection. gosqlxParse(sql, dialect, version)accepts version 1 for AST JSON v1 (version,node_type, zero-valued fields omitted); omitted versions keep the legacy indented output, which the gosqlx.dev playground still uses; the playground switches to version 1 in a later release. [W8-04]
Changed
-
Release process: add a post-tag benchmark refresh task and require claims to match the release tag.
-
Perf measurement methodology (W0-15; benchmark tooling only, no library behaviour change):
- Every
GOGC=offmeasurement now also setsGOMEMLIMIT(default64MiB; override withPERF_GOMEMLIMITor thegomemlimitdispatch input,offunsets it):scripts/perf/ab.sh(sotask bench:abandtask bench:gate),scripts/perf/profile.shand the competitor harness'scmd/publish(-gomemlimit, recorded asconfigs[].gomemlimitin the results JSON).task bench:matrixalways uses a fixedGOMEMLIMIT=64MiB. An invalid value is refused up front instead of making every benchmark binary panic. Without a limit a GC-off heap only grows, so allocations land on fresh pages whose first-touch faults were timed and profiled; the first benchmark of each test binary absorbed most of them. GOGC=off timings are therefore not comparable with runs made before this change; base and head of one run always use the same setting. The limit lets the collector run, so timings and instructions/op (perfdriver, cachegrind) are no longer pure mutator work but include a small GC share (about 0.25% of Ir/op forjoin), and the pool drains it causes make allocs/op vary for large-input and low-iteration benchmarks (not in the gated suite, where it stays exact). scripts/perf/baselinedeliberately keepsGOGC=offwith noGOMEMLIMIT(and drops an inherited one): it gates absolute allocs/op and B/op only, which are exact only when no collection drains the pools.docs/PERFORMANCE_METHODOLOGY.mddocuments the whole method.perf-gate.yml(new in this release) andbench-compare.ymlbuild with one pinned Go release,PERF_GO_VERSION1.26.9 (the toolchain of the recorded baselines), not thego 1.26.1line of the rootgo.mod.perf-gate.ymlprofile mode adds cachegrind cache simulation (32 KiB 8-way L1i, the Zen 3/4/5 geometry) of the gap queries: instructions, L1i and L1d misses per operation and the functions with the most L1i misses.- New
matrixdispatch mode inperf-gate.yml: the interleaved A/B over the full benchmark matrix (scripts/perf/matrix-suite.sh), report only: the job is named "Matrix A/B (report only)" and the report heading is "Matrix A/B: VERDICT (report only, not a gate verdict)" (ab.sh -T,gate -report-only -title). - Every perf artifact and report names the runner CPU model, and the reports
compare by in-job ratio only: the gate report says so, and the competitor
harness summary leads with GoSQLX/peer time ratios (
cmd/publish -ratios) instead of absolute ns/op. - The LSP benchmark server (
setupTestServer) discards its output, so benchmarks that publish diagnostics no longer time a growing buffer.
- Every
-
Token classification moved to
internal/tokclass(W3-03a1; internal refactor, no behaviour change): the compound-keyword split tables, the identifier/keyword → specific-type remaps, the COUNT..MAX → identifier rule and the backtick-width rule applied by the parser's preprocess pass now live in one internal package that the tokenizer's planned parser-ready mode (W3-03b) will share. Tokens, spans, ASTs, errors and every behaviour golden are unchanged. A differential test checks the new pass, field for field, against a frozen copy of the old one over the benchmark corpus, the SQL fixtures and a generated compound-keyword, Unicode-fold, odd-identifier and tokenizer-error matrix in all 11 dialects. -
Use per-PR changelog fragments in
changelog.d/to avoid merge conflicts; collect them intoCHANGELOG.mdwhen preparing a release. -
Claude Code plugin (
plugins/gosqlx): prepared for Anthropic's plugin directory. Added a listing icon andprivacyPolicyUrl, and the MCP server URL is now the literalhttps://mcp.gosqlx.dev/mcpas the directory requires. The README now states everything the plugin runs and sends. -
VS Code extension: add a CI workflow that compiles, lints and runs the unit tests, and fix the lint errors and stale unit tests it surfaced.
Performance
- Figures in the entries below were measured when each change landed, against the commit before it, and later changes moved several of them further. The release summary at the top of this section compares v1.17.0 with v1.18.0 directly.
- Semantic tokens: pooled highlighting scratch and shared case folding cut 30 KB semantic-token allocs/op by 98.9–99.0% (2,039 to 20, 1,863 to 21, 1,953 to 21 when W6-11 landed; 13/14/14 in this release), B/op by 26.0–26.8% and sec/op by 13.3–14.3% (amd64 layout-randomized gate); the new highlight golden pins output. No behaviour change. [W6-11]
- Linter: the lint pipeline uses the pooled parser and pooled dialect tokenizer; behavior is unchanged. [W6-06ab]
- Linter: aliasing consistency and four visitor-based rules now reuse the cached preorder AST node list. Violations are unchanged; there is no API or behavior change. [W6-05b]
- Linter: rule L007 (keyword case consistency) scans words without allocating (substring words, ASCII upper-casing into a stack buffer before the keyword lookup). Output is unchanged. On the canonical benchmarks (Apple M4, local),
BenchmarkLintRule/L007allocates about 98% fewer objects (72565 to 1194 allocs/op) and about 97% fewer bytes, andBenchmarkLintRWallocates about 12.5% fewer objects. [W6-03] - gosqlx: errors returned by
Parse,Validate,Lintand the tree helpers now wrap the sentinel and the underlying error in an unexportedwrapErrthat builds its message lazily, instead offmt.Errorf("%w: %w", ...)on every failure. Error text,errors.Isanderrors.Asbehaviour are unchanged; only the unexported concrete error type differs. The saving applies to callers that only checkerrors.Is/errors.Asor drop the message: when the message is built (err.Error(), as the LSP and CLI do) the gain is about 2 allocs/op and 3-4% B/op per error (syntax_mid 21 -> 19 allocs). Because the message is now built on demand,Error()reflects any later mutation of the inner*errors.Errorreached througherrors.As; previously the text was fixed at creation. [W1-03] - Linter L010: scans bytes in a single pass instead of rebuilding
substrings and running a regular expression;
BenchmarkLintRule/L010is 67.5% faster on the amd64 CI gate and allocates nothing (was 20,758 allocs/op); LintRW allocs/op drop 2.3-3.2% across all dialects. - Parser joins slice sized from a JOIN lookahead [W4-03]: when the first JOIN of a FROM clause is appended,
parseJoinClausescounts the JOIN tokens that follow at the same paren depth (within 256 tokens, stopping at;, UNION/EXCEPT/INTERSECT or the closing)) and allocates the slice with capacity 1 + that count (max 8) instead of a fixed 2. Join-free statements pay nothing.ParseE2E/joinandcomplexB/op drop about 20%; no API or AST change. A full slice handed in by a parenthesized join group or a comma table is grown by the same hint. Known edge cost: shapes the lookahead cannot see ((a JOIN b) JOIN c,a JOIN b, c) incur one extra allocation per statement; the gated suite is unaffected. ast.ReleaseASTis O(1) for parser-built trees that hold no pooled nodes: the parser counts the nodes it draws from the AST pools and tellsReleaseASTthrough an internal hook (pkg/sql/internal/astrelease). When the count is zero, which covers ordinary SELECT/INSERT/UPDATE/DELETE without tuples or arrays, the release walk is skipped. Trees with pooled draws and all hand-built trees keep the full walk. No exported API or output changes. [W4-01]- Linter:
linter.Contextgains an additiveNodes()method returning every AST node inast.Inspectpreorder, built once perContextand cached (reset byWithAST). The 13 AST rules that each walked the tree withast.Inspectnow iterate that shared list; violations are unchanged (none of those walks pruned a subtree);Nodes()is safe for concurrent callers (lock-free atomic per-Contextsnapshot, no process-wide lock), so rules may stillCheckone sharedContextin parallel. [W6-05a] - Security:
Scanner.ScanSQLnow skips the dollar-quote stripping lexer, the identifier-tautology regex and the ClickHouse table-function regex on inputs that provably cannot match them, using linear-time necessary-condition guards (hasDollarOpener,hasEqualIdentPair,hasTableFnCandidate). The regexes still confirm every finding, so results are byte-identical (guarded by a guards-on/off equivalence test over the real-world corpus and 200k random inputs); no API or behaviour change. [W6-01] - Security:
Scanner.ScanSQLchecks every pattern's required literals with a single Aho-Corasick pass over the input, folding case inline instead of searching once per literal per pattern. Alternation-, optional- and assertion-aware filters include the ClickHouse table-function names, stacked-query verbs and UNION system schemas, so fewer regexes run. The case-folded input copy and its pool are removed. Findings remain byte-identical, guarded by presence-exactness differential tests, generated-match soundness tests and the existing prefilter on/off and guards equivalence sweeps. No API or behaviour change. [W6-08] - Tokenizer:
time.Now/time.Sinceare now read only when metrics are enabled (previously twice per tokenization even when disabled). If metrics are toggled on mid-call the call is not recorded. No API or token-output change [W1-02]. - Tokenizer: keyword and compound-keyword-start lookup now uses a single fused-hash open-addressed table (one FNV-1a hash computed while upper-casing, one probe) instead of two Go map lookups per identifier. The table is filled in a fixed order (hot keywords first, then sorted) so its probe layout is deterministic across processes. No behaviour change; token output is identical [W2-01].
- Tokenizer: token Start/End locations are now computed from a cached current-line window (a range check and a subtraction) instead of two calls to the non-inlinable position lookup per token; out-of-window offsets take the existing lookup. Token positions are identical, including after a UTF-8 BOM and across pooled-tokenizer reuse (guarded by an oracle test). [W2-02]
- Tokenizer:
@paramand SQL Server@@vartoken values are now slices of the input instead of"@"+nameconcatenations, removing one string allocation per parameter (SQL Server real-world allocs/op -90% to -100%, MariaDB/MySQL/Snowflake -50% to -67% on the large cells). Names thatreadIdentifiertreats specially (U&escapes, a single letter before a quote, compound-keyword starts such as@group by, non-ASCII names) keep the previous path, so token types, values and spans are identical (pinned by a golden over 9 dialects). [W2-03] - Tokenizer: tokens are now built in place. The scanner and its token readers write each token's fields directly into its slot of the output slice instead of returning a 40-byte
models.Tokenby value that was then copied into a 72-bytemodels.TokenWithSpanand appended. On amd64 those copies reloaded just-spilled structs with 16-byte loads that cannot be store-forwarded. Token output, spans and errors are identical (token goldens unchanged); no API or behaviour change. [W2-10] - Pools: the tokenizer, parser and AST pools now count Get/Put through precreated, cache-line padded atomic counters (
internal/poolstats) instead of an RWMutex-guarded map keyed by pool name, removing a lock, map lookup and string hash from every pool operation. Named custom pools keep the map path; counting is gated onmetrics.Enable()since W1-07 (see Breaking Changes). [W1-01] - Parser: token preprocessing now takes a type-gated fast path. Only identifier, keyword, aggregate and compound tokens take the normalisation path; every other token is appended with a single copy. Output is identical (guarded by an old-versus-new differential test); no API or behaviour change.
- Parser: the parser's current token is now a pointer into its token slice (with a per-parser zero EOF sentinel) instead of a 72-byte copy made on every
advance, andpeekTokenreturns a pointer, which removes most GC write-barrier work and struct copying from the parse loop. Parse results, errors and positions are byte-identical (behaviour goldens plus a recovery-path differential); no API change. A zero-value&Parser{}keeps working. [W3-02] - Fingerprint, formatter, transform:
fingerprint.Normalize/Fingerprint,Formatter.Formatandtransform.ParseSQL/ParseSQLWithDialecttokenize through the internal pooled token scratch instead of the publicTokenizeString.Normalizeallocates 42-70% fewer bytes/op andtransform.ParseSQL49-78% fewer, with 2-3 fewer allocs/op and no output change. [W5-01] - Formatter: compact formatting (
ast.CompactStyle(), no clause newlines, no semicolon, no line width, no target dialect, preserve or upper keyword case) now renders SELECT, INSERT, UPDATE and DELETE through each statement'sSQL()instead of the visitor renderer, and a single compact statement skips the parts slice and join.Render/compact/*is 27-49% faster with 1 alloc/op (was 4-42) and 60-82% fewer bytes/op;NormalizeandFingerprintare 6-13% faster with 15-39% fewer allocs. Output is byte-identical (differential test over every corpus statement in 9 dialects and all option combinations); lowercase keywords, target-dialect rewrites, set operations and ALTER TABLE keep the visitor path. [W5-02] - Parse stack reservation: every tokenize-then-parse path reserves goroutine stack once, before tokenizing, through the internal
internal/stackgrowpackage (no public API). It covers the gosqlx, parser, formatter, fingerprint, transform, linter and LSP pipelines, plus a backstop in the parser core for low-level callers. A parse on a fresh goroutine now copies its stack once, while its frames are shallow, instead of 2-3 times during the parse;BenchmarkParseFreshon the amd64 layout-randomized perf gate: simple_select -58%, join -44% (borderline: -39.7% to -43.9% across six runs, -43.86% in the latest, meets the -40% target in five of six), complex -25% (target missed, -22.7% to -26.1% across six runs, -24.60% in the latest), insert -57%, update -59%, delete -66%; suite geomean -7.95% in the latest run. Results, allocs/op and B/op are unchanged. Memory: a goroutine that parses keeps a stack of at least 16 KiB until it exits or a GC shrinks it (before: 4-16 KiB depending on the statement; Windows lands at 32 KiB); long-lived worker goroutines see no change after their first parse. [W1-04] - Pools [W1-07]: Skip the atomic pool Get/Put counter updates while metrics are disabled, so the default (metrics off) path pays one predictable branch instead of one locked add per pool Get and per Put (six per Parse). Allocations and bytes per operation are unchanged. Microbenchmark results for
PoolGetPut/serialare CPU-dependent: Intel Xeon 6975P-C -38.7% to -39.9%, AMD Zen5 (EPYC 9V45) -31.5% to -34.9%, AMD Zen4 (EPYC 9V74) about -5%, and AMD Zen3 (EPYC 7763) +2.9% to +5.4% (a microbenchmark loss). No significant end-to-end change (Zen3 ParseE2E/ParseRW and suite geomean +0.30%, p=0.114; allocs/op and B/op unchanged); see the pull request for the amd64 gate numbers. - Keywords: case-insensitive lookups avoid allocations for pure-ASCII words up to 64 bytes. No behaviour change. [W2-07]
- Parser: function arguments, the SELECT list, GROUP BY and ORDER BY are now collected on parser-owned scratch stacks and copied once into exact-size slices (previously grown with
appendfrom a fixed capacity). AFunctionCallwith up to three arguments shares one allocation with its argument array, and aSelectStatementshares one with its singleFromentry and, for up to four columns, itsColumnsarray. Parse allocations drop 28% onaggregate(18 to 13) and 12% oncomplex(50 to 44), and allocs/op fall on every SELECT-shaped parse row (INSERT, UPDATE, DELETE, tokenizer-error paths and the pool and tokenizer-only benchmarks are unchanged, as they never reach the list builders). In the layout-randomized amd64 CI perf gate (20 layouts per arm, AMD EPYC 7763) the suite geomean moved -0.79% (p=0.004), the parse aggregate -3.24% (p=0.005, not significant after Benjamini-Hochberg correction, low power) andcomplex-1.35% (not significant); instructions/op fell 3.48% on the aggregate and 1.13% oncomplex, and allocs/op on the end-to-end parse fell from 18 to 13 (aggregate) and from 49 to 43 (complex). No gated benchmark regressed in time. Slice capacity and lifetime changes are listed under Behavior changes. No exported API change. [W4-04] - Identifier quoting: checks names byte by byte with a class table, falling back to the rune loop for non-ASCII names; reserved-name lookup uses a first-letter/length index derived from the word list instead of a map lookup.
AST.SQL()and formatter output are byte-identical.BenchmarkRenderis about 10% to 17% faster onsqland 4% to 10% onreadableon the amd64 CI runner, with unchanged allocs/op and B/op (see the PR for the measurement method and its limits). - Token-stream Normalize and Fingerprint [W5-08]: defaults tokenize once,
normalize into a pooled byte buffer and hash its bytes directly for
fingerprints. The authoritative final-head layout-randomized amd64 CI run
(perf-gate run 43274969051, head 528b38c9, AMD EPYC 9V74, 20 layouts per
arm, A/A' 0/52, base 1f828000) reports
Normalizechanges of -67.80% (simple_select, 0.32x of baseline), -53.85% (join, 0.46x) and -53.87% (complex, 0.46x); allocs/op fall from 5/21/62 (at that base, after W5-01/W5-02; 12/42/113 in v1.17.0) to 1 and B/op by 95.92%, 94.22% and 93.73%; the suite geomean is -5.05% (p<0.001) with no gated regression. No target met the PLAN threshold (<= 0.30x) on the final head. Earlier runs on other runners (AMD EPYC 7763: 0.35x/0.46x/0.44x; AMD EPYC 9V45: 0.26x/0.39x/0.375x) are not comparable across CPUs;simple_selectmet the PLAN threshold only on the 9V45 run, andjoinandcomplexmissed it on every run. A CPU profile ofNormalize/complexon arm64 splits the time roughly 37% tokenize, 37%appendNormalV2and under 5% hashing and pooling, so the remaining cost is the shared tokenizer plus the normal-form writer, not allocation. The legacy mode (ModeLegacy) is unchanged within noise (geomean -1.4% vs origin/main, local arm64, indicative). - Security:
Scanner.Scanwalks the AST with a pooled struct visitor instead of a per-call closure and ancestor slice. On the amd64 layout-randomized perf gate (20 layouts per arm),BenchmarkScanASTRWB/op is -53.27% to -58.31% on all eight dialects (target -45% met), allocs/op about -29% to -33%, and time -12.3% to -17.9% (all p<0.001, none worse). Findings are byte-identical (differential test against the previous implementation over the corpus); no API or behaviour change. [W6-02] LintStringand wrappers tokenize into pooled scratch storage and release the parsed AST after the rules run:LintRWB/op -40% to -45% and allocs/op -6% to -7% across all eight dialects,LintParallel/lintB/op -41%.- Security: Replace the stacked-query regex scans with a single matcher per SQL view, preserving finding order and match text, behind the same keyword prefilter as before. On amd64 (layout-randomized CI gate)
ScanSQLStackedScriptis 70-78% faster (1 MiB: -78%) andScanSQLParams/ScanSQLRWare 2-4% faster;ScanSQLLargeis unchanged within noise. No API or behavior change. [W6-09] - Transpiler:
Transpileskips operator retargeting when the source cannot contain a retargetable construct; it runsast.RetargetOperatorsonly when the source contains^ | & # ~ @ ? ! { $,<<,>>or->(plus the conservative pairs<-,=>,:=;U&is caught by&). These are detected in the same single byte pass as the existing prefilters. Plain comparisons, arithmetic, joins and DML skip the reflective walk. Output and error text are unchanged, enforced byTestPrefilterEquivalence,TestTranspileDifferentialand new per-construct and skip-invariant tests. No API change. amd64 CI matrix A/B (20 randomized layouts per arm, 17 complete):BenchmarkTranspileRWcross pairs about -14% to -19%, small cross-dialect shapes about -31% to -37%. [W7-01] - Dialect detection [W7-09]:
DetectDialectuses a lazily built, compact single-pass matcher with no per-call allocations (1 to 0 allocs/op, 48-80 B/op to 0; 72 KiB to 0 on a 64 KiB input). On the amd64 perf gate (run 43207955894, AMD EPYC 9V45, 20 layouts per arm) every non-empty case is significantly faster (p<0.001), about 3.1x to 5.5x: PostgreSQL 5.5x, MariaDB 4.7x, Snowflake 4.7x, MySQL 4.65x, generic 4.6x, SQL Server 4.8x, Oracle 4.4x, mixed 4.1x, 64 KiB 3.1x. The 2 nsemptycase moves by layout noise between gate runs (-24.9% here, +0.7% in another) and is not claimed (0 allocs before and after). The 4x PLAN target is met for every case except the 64 KiB input (3.1x), which misses it; earlier runs on other runner CPUs also missed it for generic, MySQL, Oracle and mixed. All rows are reported in the PR body from the CI gate. - C binding [W8-01]: pooled JSON and result scratch, AST release, typed extraction results, and a bounded linter cache reduce parse allocations by 6/op (about 620–670 B/op), lint by 14/op (about 1.2–1.6 KB/op), metadata extraction by 3/op (about 620–1,420 B/op), and table extraction by 8/op (about 630–690 B/op) in the small/medium/large benchmarks. The C ABI and JSON bytes are unchanged.
- Playground: parse returns compact typed AST JSON v1 on request. amd64 layout-randomized perf gate (20 layouts, p<0.001): parse -76.4/-74.8/-85.6% sec/op and lint -34.5/-26.8/-29.3% sec/op for small/medium/large inputs, with allocs/op and B/op down. Payload bytes -75.7/-73.2/-91.6% (local, deterministic). Playground lint removes a second parse. [W8-04]
Behavior changes
- Validate blank input:
parser.Validateandparser.ValidateByteshave always returned E2005 for empty or ASCII-whitespace-only input. Comment-only input (-- c,/* x */,;,-- c\n;) has always returned E2005 through all parser entry points andgosqlx.Validate/Parse. The parser behavior change is limited toparser.ValidateWithDialectandparser.ValidateBytesWithDialect, which now return E2005 for blank input instead of nil.gosqlx.Validatenow wraps E2005 or E2004 inErrSyntaxfor empty or whitespace-only input, replacing the unstructured “empty input” error;errors.Asnow finds the structured error. C bindinggosqlx_validate_dialecthas the same error change.
Migration: onlyparser.ValidateWithDialect,parser.ValidateBytesWithDialectpreviously accepted blank input; comment-only input was never accepted.gosqlx.Validateand C/Python callers should match witherrors.Is(err, gosqlx.ErrSyntax)or the error code, rather than the “empty input” text. - Linter L010 (redundant whitespace): violation columns are byte positions on lines with invalid UTF-8. They were shifted before because invalid bytes were replaced with U+FFFD (3 bytes) while scanning. Valid UTF-8 is unaffected.
- LSP documentSymbol outline ranges now use exact parser statement spans; see Fixed. Clients see different (correct) ranges; positions remain byte columns.
- Goroutine stack after a parse: a goroutine that has parsed keeps a stack of at least 16 KiB (32 KiB on Windows, 16-32 KiB under
-race) until it exits or the GC shrinks it; before it was 4-16 KiB depending on the statement. The internal stack reservation each parse entry point makes (internal/stackgrow.Reserve), when made deep inside an already-large stack (for example an LSP or JSON-RPC handler) can land the goroutine at 32 KiB, since the frame is added on top of the stack in use. Results are unchanged. [W1-04] - Compound keyword parts now have precise per-word spans across source-aware parser and model-token entry points and LSP diagnostics.
INSERT INTO t (group by) VALUES (1)reportsexpected ), got BYat 1:22 instead of 1:16;UPDATE t SET order by = 1reportsexpected =, got BYat 1:20 instead of 1:14. Error codes, messages and hints are unchanged for these INSERT/UPDATE examples. - General rule: any error reported at the second word of a merged compound keyword (BY of GROUP BY/ORDER BY, JOIN of INNER/LEFT/RIGHT/OUTER/FULL/CROSS JOIN, SETS of GROUPING SETS) now points at that word instead of the first, with the message unchanged. For example, in postgresql and generic,
REVOKE ALL ON t FROM order\n bynow reportsexpected semicolon or end of statement, got BYat 2:2 instead of 1:22. parser.ParseBytesWithTokensreturns per-part spans for reconstructable two-word compounds, including multiline separators. Public tokenizer output remains unchanged.- Utility grammar changes because the second word of a single-line compound is no longer mistaken for a delimited (quoted) identifier: they now behave like the multiline
GROUP\n byandorder\n byforms already did. Quoted grantee names retain their quoting. Specifically:GRANT SELECT ON t TO GROUP byandREVOKE ALL ON t FROM GROUP byare now accepted in generic, postgresql, mysql, mariadb, oracle, snowflake, bigquery, redshift and clickhouse; previously they failed withexpected grantee, got GROUPat 1:22.- In sqlserver,
GRANT SELECT ON t TO GROUP by,REVOKE ALL ON t FROM GROUP byandREVOKE ALL ON t FROM order bywere accepted and are now rejected withexpected operand after BY, got EOFat 1:30. BY and GROUP are reserved in T-SQL. - In the other non-SQLite dialects listed above,
REVOKE ALL ON t FROM order bychanges its error fromexpected grantee, got ORDERat 1:22 toexpected semicolon or end of statement, got BYat 1:28. - SQLite continues to reject all three statements with
expected statement, got IDENTIFIERat 1:1.
- Parser AST slices [W4-04]:
Columns,GroupBy,OrderByandFunctionCall.Argumentsnow havelen == cap(they used to carry spare capacity), so a caller that appends to them reallocates instead of writing into spare space; trees are otherwise identical (guarded by the behaviour goldens). Lifetime trade-off: because the blocks are co-allocated, retaining onlyColumns,FromorArgumentsof a released tree keeps the whole block (up to 600 B) alive. - Dialect detection [W7-09]: Tied positive scores now resolve in a fixed order: Oracle, Snowflake, PostgreSQL, MySQL, SQL Server, MariaDB, SQLite; previously the result depended on map iteration order. Input with only
NVLnow always returns Oracle (previously about 87% Oracle, otherwise Snowflake), andTOPwith a backtick now always returns MySQL (previously about 87% SQL Server). - Playground (
gosqlxLint): with any explicit dialect, includinggeneric, a tokenizer error is now reported asgosqlx: tokenize error: Error E1002 ...(what the no-dialect path and gosqlx.Lint already report) instead ofgosqlx: syntax error: Error E2004 ... tokenization error: ....parse_error_spanis unchanged (it already resolved to the innermost positioned error). Librarygosqlx.Lint/LintWithDialectare unchanged. [W8-04] - Playground (
gosqlxLint): SQL with no statements (blank, whitespace or comment-only) gets noparse_error, matchinggosqlx.Lint(the linter treats it as "nothing to lint", not a syntax error). Noparse_erroron comment-only input is a maintainer-confirmed behaviour change. Librarygosqlx.Lint/LintWithDialectare unchanged. The AST and Analyze tabs still report the parse error. [W8-04]
Fixed
- Claims checks now verify that published benchmark results were measured at the latest release tag commit.
- AST:
AlterTableStatement.SQL()now separates multiple ALTER TABLE actions with commas, matching the compact formatter and preserving action boundaries when re-parsed. - Playground: the GoSQLX WebAssembly module now runs in a Web Worker, so
loading the parser and every parse, format, lint, analyze, highlight and
transpile call no longer block the page. The playground computes only the
open tab (plus lint, which marks errors in the editor) and the rest when a
tab is opened. Total Blocking Time on
/playground/dropped from ~490 ms to ~80 ms in local Lighthouse runs at CI-equivalent CPU throttling, which ends the Lighthouse CI performance failures on slower GitHub runners. - ClickHouse and Snowflake lambdas keep their body (#897):
->in these dialects is now parsed as the lambda operator, soarrayMap(x -> x * 2, a)isx -> (x * 2). It used to parse as the JSON arrow,(x -> x) * 2, and formatting or transpiling for ClickHouse or Snowflake, including identity transpiles, emittedarrayMap((x -> x) * 2, a). The newBinaryExpression.Lambdafield marks these nodes. Transpiling a ClickHouse or Snowflake lambda to the generic dialect now parenthesizes its body,arrayMap(x -> (x * 2), a), because the generic parser reads->as the tight-binding JSON arrow; it used to emitarrayMap(x -> x * 2, a), which reads back as(x -> x) * 2. Transpiling a lambda to a dialect without lambdas (PostgreSQL, MySQL, MariaDB, SQLite, SQL Server, Oracle) now returns an error: written as that dialect's->it would mean JSON extraction or regroup as(x -> x) * 2. In the other direction, a JSON->or->>transpiled to ClickHouse or Snowflake now returns an error, because there->is the lambda operator (and->>Snowflake's flow operator) and the output would be read back as a lambda. Parsing->>with the ClickHouse or Snowflake dialect is now an E4001 unsupported-feature error (the ->> operator is not supported in ...); it used to parse as a JSON node, which formatted unchanged. U&'...'in Oracle, Snowflake and ClickHouse is an error (#898): these dialects have neither Unicode-escape literals nor an&operator. The literal was read asU & '...', and formatting or transpiling then emittedBITAND(U, '...')orbitAnd(U, '...'). TokenizingU&'...'orU&"..."in these dialects now returns an E4001 unsupported-feature error. A spacedU & '...'and all other dialects are unchanged: in MySQL, MariaDB, SQL Server and SQLiteU&'x'is stillU & 'x', and PostgreSQL still reads it as a Unicode-escape literal.- Parser:
CREATE OR REPLACE FUNCTIONwith anAS $$ ... $$body now parses when no dialect is set. The generic end-of-statement scan, which the default parser and the MySQL, MariaDB and SQLite dialects use, treated theREPLACEof the header as a MySQL-familyREPLACEstatement and ended theCREATEthere; a word followingORis now always part of the current statement (OR REPLACE/OR ALTERheaders, and nothing valid ends an expression with a bareOR). As a result,CREATE OR REPLACE <object>headers are no longer split atREPLACEin those dialects either (for exampleCREATE OR REPLACE FUNCTION ... AS $$ ... $$undermariadb, which earlier failed with E2002 atREPLACE; MySQL and SQLite now also acceptCREATE OR REPLACEheaders for objects they do not define, such as Snowflake streams);REPLACE INTOstill parses as a statement in the MySQL dialect. - LSP documentSymbol ranges now come from the parser's statement spans. Statements without positioned children (DROP, TRUNCATE, CREATE TABLE, ALTER TABLE, CREATE INDEX) no longer report the range from 0:0 to the first
;, and MERGE ranges no longer start partway through the statement at its first positioned child. A statement no longer extends over the statements that follow it on the same line. Range construction no longer rescans the document per statement (O(N²) → O(N) for GO-separated or long-prefix scripts). Behaviour change for LSP clients: outline ranges differ, and are now exact. Positions are still byte columns. gosqlxValidatenow honours its dialect argument. [W8-04]
Security
- Update website and VS Code extension npm dependencies to fix Dependabot alerts: Next.js 16.4.6 (use-cache disclosure),
@azure/msal-node7.2 via@azure/identity4.14,glob14 andminimatch11.