Skip to content

Add optional support for the official ClickHouse SQL lexer #1074

Closed

Description

@ccoltx

Summary

Add optional support for the official ClickHouse SQL lexer, @clickhouse/lexer, so the client can read user SQL the same way the server does. It would stay opt-in: no new runtime dependency, and no change in behavior unless a user turns it on. Separately, use it in this repository's tests to check our own SQL handling against the server's tokenizer.

Why

The client makes small edits to the user's SQL before sending it:

  • query(), command() and exec() strip trailing semicolons;
  • query() appends FORMAT <format>.

This is done with plain string handling, which can't tell whether a ; or a keyword is inside a comment, a string, a quoted identifier or a heredoc. That has produced a steady stream of bugs:

Each open fix adds its own small hand-written scanner. #1031 does this for #973, and #972 for #970. ClickHouse's lexer has many rules that are easy to miss: $ is allowed inside identifiers, // starts a comment, comments can nest, and more. Testing #1031 against a live server found two such cases that its unit tests didn't cover (details).

@clickhouse/lexer is ClickHouse's own src/Parsers/Lexer.cpp compiled to WebAssembly:

  • about 9 KB, Apache-2.0, no dependencies;
  • runs in Node.js and browsers;
  • published whenever the upstream lexer changes.

Using it removes the guesswork: the client splits the query exactly as the server will.

How it would stay optional

  • The client never imports the package. Users install it and pass the module in through a new sql_lexer option, the same pattern as the existing tracer option. This:
    • keeps @clickhouse/client and @clickhouse/client-web free of runtime dependencies;
    • avoids bundler errors for users who don't install the lexer;
    • avoids loading an ESM-only package from the clients' CommonJS build.
  • It's declared as an optional peerDependency, only to signal which versions are compatible.
  • Without sql_lexer, nothing changes. The query text sent to the server stays the same, byte for byte.
  • Safe fallback. If the lexer can't load, the client logs one warning (linking to a docs page) and keeps its built-in handling. This happens, for example, under a Content Security Policy without 'wasm-unsafe-eval', or on runtimes that don't allow compiling WebAssembly, such as Cloudflare Workers. A query the lexer can't tokenize, such as one with an unclosed quote, also uses the built-in handling and is left for the server to report.

How it would be used

import { createClient } from "@clickhouse/client"; // or "@clickhouse/client-web"
import * as lexer from "@clickhouse/lexer";

const client = createClient({ sql_lexer: lexer });

// Works: sent as `SELECT 1 -- note` followed by `FORMAT JSON`
await client.query({ query: "SELECT 1; -- note" });

// Sent as `SELECT 1 FORMAT JSON SETTINGS max_threads = 1`
await client.query({ query: "SELECT 1 SETTINGS max_threads = 1" });

With sql_lexer set:

  • query(), command() and exec() remove trailing semicolons using the lexer's tokens. Comments are kept, and ; inside strings, identifiers, heredocs and comments is left alone.
  • query() puts FORMAT before a trailing top-level SETTINGS clause. A SETTINGS clause in a subquery, a column named settings, or ... SETTINGS a = 1 UNION ALL SELECT 2 keeps today's behavior.

Possible later uses: safer quoting of identifiers in insert() (#945, #1004), and a safe SQL builder.

How it helps testing

This part is useful on its own, even before any user opts in. The lexer would only be a dev dependency here.

  • Checking hand-written fixes against the server's tokenizer. We send a query unchanged (with ?default_format=...) and as the client would rewrite it, then compare the server's answers. On a 44-query corpus:

    Implementation Same answer as the server
    main 25 / 44
    PR fix: remove a trailing semicolon that is followed by a comment #1031 42 / 44
    official lexer 44 / 44

    The same corpus can check Fix query(): insert FORMAT before a trailing SETTINGS clause #972 and any future fix that touches SQL text. Step 8 of the rollout below makes this a permanent test. When PR fix: remove a trailing semicolon that is followed by a comment #1031's scanner was swapped in, the unit test reported the 16 cases it fixes and the 2 it still misses within seconds.

  • The repo's own SQL scanners. The upstream test runner in tests/clickhouse-test-runner scans SQL by hand to split statements (split-queries.ts) and to detect statement kinds (backends/rowbinary.ts). These could use the lexer, or at least be tested against it.

  • Generating test cases. Expected splits and token boundaries can come from the server's own lexer instead of being written by hand.

Proposed rollout

An implementation is open as a stack of small draft PRs, each building on the one before it:

  1. Characterization tests that pin the exact SQL query(), command() and exec() send today. No behavior change. (test: pin the SQL that query(), command() and exec() send #1065)
  2. Move today's logic, unchanged, behind an internal interface. (refactor: move SQL rewriting behind an internal SqlRewriter interface #1066)
  3. Internal lexer-based rewriter, not used yet. The lexer is a dev dependency, and a lint rule blocks importing it from client source. (feat: add an internal lexer-based SQL rewriter #1067)
  4. The sql_lexer option, used by command() and exec(), with the load-failure fallback and a docs page. (feat: add the opt-in sql_lexer option, used by command() and exec() #1068)
  5. query() uses it, which fixes query(): trailing semicolon followed by a comment breaks FORMAT append (SYNTAX_ERROR 62) #973 when opted in. (fix: with sql_lexer, query() strips a semicolon before a comment #1069)
  6. FORMAT goes before a trailing SETTINGS clause, which fixes [backfill: ClickHouse/clickhouse-js] client.query() unconditionally appends FORMAT after user SETTINGS clause, producing invalid SQL on older ClickHouse servers #970 when opted in. (fix: with sql_lexer, query() puts FORMAT before a trailing SETTINGS clause #1070)
  7. README, docs and troubleshooting-skill updates. "Zero external dependencies" becomes "no runtime dependencies", with a pointer to the optional lexer. (docs: describe the optional sql_lexer in the READMEs and troubleshooting skill #1071)
  8. Tests that compare the built-in handling with the official lexer. These use a shared corpus of tricky queries, run as a fast unit test with no server and as a server-judged integration test. An explicit list of known differences fails both when a new difference appears and when a listed one disappears. The existing select and exec() tests also run in both modes. (test: compare the built-in SQL handling with the official lexer #1072)

A future major version could make the lexer a regular dependency of the Node.js client and turn it on by default. That needs a require() of an ES module, so Node.js ^20.19 || >=22.12. The Web client would keep the opt-in model because of the CSP and Workers limits above.

Open questions

Activity

  1. added
    enhancement
    on Oct 21, 2026
  2. self-assigned this
    on Oct 21, 2026
  3. ccoltx commented on Oct 24, 2026

    @ccoltx
    ContributorAuthor

    #1085 (closing #1079) changes query() to send the SQL as written and pass the format as the default_format setting, so the client no longer edits the query text. That removes most of the reason for this issue:

    What may still be worth doing, separately from this issue:

    Suggest closing this issue and the draft PRs once #1085 merges. If the test-runner or insert() ideas are worth keeping, they can go into new, smaller issues.

  4. ccoltx commented on Oct 31, 2026

    @ccoltx
    ContributorAuthor

    Closing: #1085 made the lexer unnecessary for the client. query() sends the SQL as written and passes the format as the default_format setting, so none of the methods rewrite SQL any more (the one exception is exec() with values, which removes semicolons at the very end of the statement before the insert data). #973 and #970 are fixed for every user without an opt-in, verified on both clients against 26.11.

    The implementation stack (#1065 to #1072) is closed and stays available as a reference. Two ideas from this issue are independent of the fix and can get their own issues if we pursue them: using the lexer in the test runner (tests/clickhouse-test-runner, which still splits statements and detects statement kinds by hand), and identifier quoting in insert() (#945, #1004).

  5. added
    queries
    on Nov 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancementqueries

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions