Repository navigation
Description
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()andexec()strip trailing semicolons;query()appendsFORMAT <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:
- query(): trailing semicolon followed by a comment breaks FORMAT append (SYNTAX_ERROR 62) #973:
SELECT 1; -- notefails withMulti-statements are not allowed, because the;before the comment is kept and the appendedFORMATbecomes a second statement. - [backfill: ClickHouse/clickhouse-js] client.query() unconditionally appends FORMAT after user SETTINGS clause, producing invalid SQL on older ClickHouse servers #970:
FORMATis appended after a trailingSETTINGSclause, which older servers reject.
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_lexeroption, the same pattern as the existingtraceroption. This:- keeps
@clickhouse/clientand@clickhouse/client-webfree 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.
- keeps
- 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()andexec()remove trailing semicolons using the lexer's tokens. Comments are kept, and;inside strings, identifiers, heredocs and comments is left alone.query()putsFORMATbefore a trailing top-levelSETTINGSclause. ASETTINGSclause in a subquery, a column namedsettings, or... SETTINGS a = 1 UNION ALL SELECT 2keeps 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 main25 / 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-runnerscans 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:
- Characterization tests that pin the exact SQL
query(),command()andexec()send today. No behavior change. (test: pin the SQL that query(), command() and exec() send #1065) - Move today's logic, unchanged, behind an internal interface. (refactor: move SQL rewriting behind an internal SqlRewriter interface #1066)
- 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)
- The
sql_lexeroption, used bycommand()andexec(), with the load-failure fallback and a docs page. (feat: add the opt-in sql_lexer option, used by command() and exec() #1068) 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)- 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)
- 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)
- 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
selectandexec()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
- Should the hand-written fixes (fix: remove a trailing semicolon that is followed by a comment #1031, Fix query(): insert FORMAT before a trailing SETTINGS clause #972) be merged anyway, so users who don't opt in also get them? They don't conflict with this proposal.
- Is
sql_lexerthe right option name? - Lexer releases follow ClickHouse
master. Is a^1.0.0peer range right, or should the supported range be narrower?
Activity
ccoltx commentedon Oct 24, 2026
#1085 (closing #1079) changes
query()to send the SQL as written and pass the format as thedefault_formatsetting, so the client no longer edits the query text. That removes most of the reason for this issue:SELECT 1; -- note) and [backfill: ClickHouse/clickhouse-js] client.query() unconditionally appends FORMAT after user SETTINGS clause, producing invalid SQL on older ClickHouse servers #970 (FORMATafter a trailingSETTINGS) were both caused by the appendedFORMAT. With nothing appended, they are fixed for everyone, with no opt-in and no extra package. The shortSHOW ROW POLICIEScase (client.query() fails on SHOW ROW POLICIES when server has no policies (FORMAT clause causes SYNTAX_ERROR) #759) is fixed the same way.command()andexec()also send the SQL as written now. The only remaining client-side edit isexec()withvalues, where the server needs the statement to end without a;before the data. That is a plain end-of-string trim that doesn't need a lexer.sql_lexer, the rewriter and theFORMAT/SETTINGSplacement (steps 1-6 of the rollout, test: pin the SQL that query(), command() and exec() send #1065-fix: with sql_lexer, query() puts FORMAT before a trailing SETTINGS clause #1070) would have nothing left to do. The same goes for the hand-written scanners in fix: remove a trailing semicolon that is followed by a comment #1031 and Fix query(): insert FORMAT before a trailing SETTINGS clause #972.What may still be worth doing, separately from this issue:
@clickhouse/lexerin this repo's tests, e.g. for the SQL scanning intests/clickhouse-test-runner(split-queries.ts,backends/rowbinary.ts).insert()([backfill: ClickHouse/clickhouse-js] insert columns parameter does not backtick-quote identifiers with spaces/special chars #945, insert(): table parameter is concatenated raw into SQL — table names needing backtick quoting cannot be used #1004), if that still needs SQL-aware handling.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.ccoltx commentedon Oct 31, 2026
Closing: #1085 made the lexer unnecessary for the client.
query()sends the SQL as written and passes the format as thedefault_formatsetting, so none of the methods rewrite SQL any more (the one exception isexec()withvalues, 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 ininsert()(#945, #1004).