Repository navigation
Build the SQL parser standalone: cut abseil, cctz, re2, boost, locale and the settings schema - #111986
Build the SQL parser standalone: cut abseil, cctz, re2, boost, locale and the settings schema#111986alexey-milovidov wants to merge 22 commits into
Conversation
…ncies Groundwork for building `src/Parsers` on its own (the WebAssembly experiment in `utils/wasm-parser` that follows). Everything here stands on its own as a fix or a build-time improvement; nothing is WebAssembly-specific except the platform guards. Dependencies the parser did not need: * `DumpASTNode.h` included `Poco/Util/Application.h` and never used it. That header reaches `Poco::ThreadPool` and `Poco::SignalHandler`, and `DumpASTNode.h` is pulled in by `InDepthNodeVisitor.h`, so over 60 translation units paid for it. * `ExpressionListParsers.cpp` included `AggregateFunctions/AggregateFunctionFactory.h` and never used it either, dragging `IAggregateFunction` and all of `Columns` into one of the heaviest translation units in the tree. * `ParserSystemQuery.cpp` included the whole Keeper client for three path-string helpers. Those move to a new `Common/ZooKeeper/ZooKeeperPathUtils.h`; `ZooKeeper.h` includes it, so every existing user is unaffected. `ASTSQLSecurity::formatImpl` was defined identically in both `ASTSQLSecurity.cpp` and `ASTCreateQuery.cpp`. Static-library linking never pulls both objects in, so the ODR violation stayed latent; it becomes a duplicate-symbol error as soon as the objects are linked directly. Removed the copy in `ASTCreateQuery.cpp`. `CommonParsers.cpp` built the keyword table at startup: 645 inlined `resize`/`std::string` assign/`unordered_set::emplace` sequences, which compiled to a 57 KB constructor - the single largest function in the parser - plus 645 string allocations and a hash-set build in every process. It is a `constexpr std::array<std::string_view, N>` now, indexed directly by `Keyword`; the two consistency checks the constructor performed became `static_assert`s, so they now also run in release builds. `getAllKeyWords` and `getKeyWordSet` only feed system tables and query obfuscation, so they materialize on first use. 32-bit correctness, all of which were latent: * `ASTs` asked Boost for a `uint32_t` stored size, which Boost rejects unless the type is strictly smaller than `size_t`. Pick `size_t` when there is nothing to shrink. * `DEFAULT_NATIVE_BINARY_MAX_NUM_ROWS` was a `uz` literal that does not fit in a 32-bit `size_t`, and is compared against a `UInt64` read off the wire. * `ProfileEvents::Count` was `size_t` while `Increment` was `Int64`, tripping the `static_assert` that the two match. * `itoa` and `iota` guarded their `long`/`size_t` overloads on `OS_DARWIN`. The real condition is that `long` is a type of its own, which is also true on any 32-bit platform, so the guard is now `!defined(__LP64__)` as well. * `CLOCK_MONOTONIC_COARSE` is a Linux extension; `base/time.h` listed the platforms that need a substitute one by one and now falls back generically. `base/defines.h` and Poco's `Platform.h` learn about `__wasm__` so that headers naming the platform stop erroring out. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Three visitors in `src/Databases` were relying on `DumpASTNode.h` to give them `Poco/Util/AbstractConfiguration.h` transitively; they include it themselves now.
An experiment in how small `src/Parsers` gets on its own. The Web UI currently ships only
the lexer (`Lexer.cpp` builds to a 6 KB `.wasm` with no dependencies); a real parser would
give exact syntax errors with positions and query pretty-printing in the browser.
`utils/wasm-parser/build.sh` compiles 500 translation units with wasi-sdk and links a
2.7 MB module (789 KB gzipped) exporting a five-function C interface. `test.mjs` drives it
through `SELECT`, `CREATE TABLE`, window functions, recursive CTEs, `ALTER`, `INSERT`,
`SYSTEM`, `CREATE USER`, `GRANT`, and two deliberate syntax errors.
`-fwasm-exceptions` is required rather than optional: the parser reports errors by
throwing, and the wasi-sdk headers refuse `setjmp.h` without it.
`wasm_runtime.cpp` substitutes no-ops for the pieces a browser has no use for, each of
which would otherwise dominate the bundle. Stack traces are the sharpest case:
`Common/Exception.cpp` cannot compile against stock libc++ at all, because it
`static_assert`s on `STD_EXCEPTION_HAS_STACK_TRACE` from ClickHouse's patched libc++.
`Core/Settings.cpp` is left out because `ParserSetQuery` calls `Settings::castValueUtil`
once - only to ask whether a bare `SET x` names a `Bool` setting - and that single call
pulls in every `SettingField*Traits` specialization, more code than the parser itself.
The timezone database that `contrib/cctz-cmake` generates into the binary is left out
too, as is query masking.
`shim/` holds the POSIX headers wasi-libc omits (`netdb.h`, `ucontext.h`, `sched.h`,
`pwd.h`, `fenv.h` rounding modes, `sun_path`, `__u6_addr`). Nothing calls into them; they
exist so headers that name those types in signatures still compile.
The README records where the size goes. The largest remaining cut is access-entity DDL:
`CREATE USER`/`ROLE`/`QUOTA`/`ROW POLICY` and `GRANT` account for 334 KB of parser and
`Access` code, roughly a third of the bundle once the re2 and abseil they share with
`COLUMNS('regexp')` matchers is counted.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…confine re2
Continues cutting what `src/Parsers` drags in. Measured on the standalone WebAssembly build
(`utils/wasm-parser`), which links only the parser's transitive closure.
abseil is gone. `IParser.h` used `absl::InlinedVector` for the list of expected tokens, which
is a short append-only list that must not allocate - `Parsers/InlineVector.h` does that in
80 lines. `LiteralTokenMap` used `absl::flat_hash_map`; it is only populated when a caller asks
for literal positions, so `std::unordered_map` is enough.
cctz and the timezone database are gone. They entered through one line: `SYSTEM ... SET FAKE
TIME '...'` was parsed into a timestamp with `readDateTimeText` and formatted back with
`LocalDateTime`, both of which resolve against the server timezone via `DateLUT`. Which
timezone applies is a property of the running server, not of the query text, so the AST now
keeps the literal and `InterpreterSystemQuery` resolves it. As a side effect the formatter
echoes the literal instead of renormalizing it.
re2 was reachable from three places, and is now needed only by access-entity DDL:
* `maskURIPassword` and the Azure connection-string masking in `AzureQueue_fwd.h` were regular
expressions doing what a string scan does. `Common/maskURIPassword.h` scans instead. This is
masking of secrets, so `gtest_mask_uri_password.cpp` checks the new code against the regular
expression it replaces - the two also agree on 200000 random strings over `ab:@/.` plus
newline, which is how the edge cases around leftmost-match were settled.
* `IASTColumnsTransformer::transform` compiled `EXCEPT('regexp')` patterns. Applying a
transformer needs the expanded column list, so it is name resolution rather than parsing;
it moves to `Interpreters/applyColumnsTransformer.cpp`, and the AST nodes go back to being
syntax. Every caller was already in `Interpreters` or `Analyzer`.
* `parseAccessRightsElements.cpp` validates a `GRANT ... ON ...(regexp)` pattern while parsing.
Left alone: dropping the check would silently accept a grant that can never match. re2 and
abseil are therefore now exactly the cost of access-entity DDL.
`Core/Settings.h` is gone from the parser. `ParserSetQuery` consulted the settings schema for
one thing: whether a bare `SET x` names a Bool setting, since the shorthand means `= true`. The
parser now records that the value was omitted and `BaseSettings::applyChange` checks the type,
which is where the schema is known. `SET max_threads` reports TYPE_MISMATCH instead of a syntax
error - 03623 is updated - and, importantly, does not silently become `max_threads = 1`, which
is what deferring without the marker would have done. The two `Settings`-taking overloads of
`parseIdentifiersOrStringLiterals` had no caller inside the parser and move to `Interpreters`.
Two more dead includes: `Core/ServerSettings.h` in `ASTAlterQuery.cpp`, and the `<ranges>` and
`Poco/Util/AbstractConfiguration.h` that other files had been getting transitively through the
includes removed here.
Parser bundle: 2759909 -> 2589773 bytes; cctz 30 KB -> 0, abseil and re2 now attributable
entirely to `GRANT`.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`parseAccessRightsElements` compiled the pattern of `GRANT READ ON S3('...')` with re2 while
parsing, purely to reject one that does not compile. That is semantics, and it was the last
thing keeping a regex engine in `src/Parsers`.
The check moves to `InterpreterGrantQuery::execute`, next to the existing validation of TABLE
ENGINE parameter names. It cannot simply be dropped: the pattern is matched with
`RE2::FullMatch` when access is checked, and a pattern that does not compile never matches, so
the grant would be accepted and then silently grant nothing.
An invalid pattern now reports CANNOT_COMPILE_REGEXP from the server instead of a syntax error
from the client.
With this, re2 and abseil leave the parser entirely, and `utils/wasm-parser` stops building
them: 500 translation units down to 320, and 2759909 -> 2292544 bytes (788548 -> 622764
gzipped) since this series started.
Also records in `LiteralTokenInfo.h` why that map is no longer an `absl::flat_hash_map`, and
what to do instead if it ever matters: the flat map really is about twice as fast for the
create/insert/destroy pattern used there, so the note should not be lost.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`LiteralTokenMap` was an `absl::flat_hash_map`, and it was that for a reason: it is built from
scratch for every column expression the `Values` format has to parse and for every query the
client highlights, so construction and destruction dominate, and the flat map was measurably
faster than `std::unordered_map` there. Swapping it for `std::unordered_map` to shed abseil
was a regression.
Rather than take abseil back for one map, this is a table that serves only what the parser asks
of it. Nothing erases, so there are no tombstones and probing stops at the first empty slot;
nothing iterates; keys are `ASTLiteral` addresses and never null, so a null key marks an empty
slot. The first eight entries live inside the object, which is what actually matters here - the
common case stops allocating entirely.
It is faster than what it replaces at every size, on the construct/insert/look-up/destroy
pattern the parser uses (nanoseconds per cycle, aarch64):
entries unordered_map flat_hash_map LiteralTokenMap
1 29 12 5
3 121 54 10
8 322 150 57
64 3673 1124 497
512 32404 7015 3516
`find` returns a pointer rather than an iterator, which is what the three call sites wanted
anyway. `gtest_literal_token_map.cpp` covers overwriting, growth past the inline storage, and
agreement with `std::unordered_map` over 500 randomised rounds including absent keys.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Two related cleanups. `boost::algorithm::string` is gone from `src/Parsers`. What it was used for was case-insensitive comparison, ASCII case conversion, splitting, joining and trimming, so `Common/StringUtils.h` grows a string overload of `equalsCaseInsensitive` and ASCII `toLowerASCII`/`toUpperASCII` beside the per-character helpers it already had, and the rest became a few lines at the call site. The comparisons are ASCII now rather than locale-driven, which is what SQL keywords, identifiers and function names want anyway. Four of the includes turned out to be unused. The parser also used exceptions to decide between alternatives, which is the wrong mechanism for it - the "failure" is an ordinary parse outcome, and it forces the whole exception machinery into a component that otherwise would not need it. All four sites are gone: * a malformed string literal went through `readQuotedStringWithSQLStyle` and was caught to report a syntax error. `tryReadQuotedStringWithSQLStyle` already existed. * `tryGetLiteralBool` let `FieldVisitorConvertToNumber` throw for anything that is not a number. It now asks the field what it holds. * checking whether a word names an access type constructed `AccessFlags` and caught the failure. `AccessFlags::tryFromKeyword` reports it instead; the throwing constructor is unchanged and now shares the lookup. * `ASTSetQuery` ran the value of `format_avro_schema_registry_url` through `Poco::URI` to find embedded credentials, catching `Poco::SyntaxException`. Locating credentials in a URI is not the parser's job and `Common/maskURIPassword.h` already does exactly this, so it just calls that. A URI that `Poco::URI` would have rejected is now masked rather than printed, which is the safer direction; a `user@host` with no password is no longer rewritten to `user:[HIDDEN]@host`, since there is nothing there to hide. `src/Parsers` now contains no `catch` at all. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Now that `src/Parsers` has no `catch`, keep it that way: an alternative that does not match is an ordinary parse outcome and a parser says so by returning false, and routing that through throw/catch also drags the exception machinery into a component that otherwise does not need it. The check exempts the harnesses under `tests/`, `examples/` and `fuzzers/`, which are expected to catch, and `Kusto/`, which is the one part of the parser still using exceptions this way - it falls back between a number and a timespan, and turns a failed cast into NULL. The exemption is named in the comment rather than left implicit so it reads as remaining work. Verified both directions: the check is silent on the tree as it stands, and fires when a `catch` is put back into `parseQuery.cpp`. The word "catch" in the `obfuscateQueries` word list is not a false positive, since the pattern requires the opening parenthesis. Also fixes what running the whole of `check_cpp.sh` turned up in the preceding commits: two error codes left declared but unused once their throws moved out (`ZooKeeper.cpp`, `parseIdentifierOrStringLiteral.cpp`), and blank lines left behind by a removed try/catch. The headers under `utils/wasm-parser/shim/` are exempted from the source heuristics - they deliberately imitate wasi-libc's own headers, down to the include guards, so `#pragma once` and the indentation rules do not apply to them. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`src/Parsers` has no `catch`, and a syntax error is reported by `tryParseQuery` returning null,
not by throwing. So in a standalone build an exception can only mean a bug or a resource limit,
and there is nothing to unwind to - the exception machinery is pure overhead.
The build now passes `-fignore-exceptions`, which compiles `throw`, `try` and `catch` but emits no
landing pads and no unwind tables. This needs no source changes at all - in particular no macro
over the `throw` keyword, which would have been undefined behaviour and would have mangled the
`throw()` exception specifications in Poco. What is left is a call to `__cxa_throw`, and defining
that in the WebAssembly runtime keeps libc++abi out of the bundle entirely: the exception object
is constructed, its message printed, and the module stops.
`CLICKHOUSE_PARSER_MINIMAL_BUILD` now has a job: `Common/StackTrace.h` is included by
`Common/Exception.h` and so by most of the tree, and it needs `<csetjmp>`, `<csignal>` and
`<ucontext.h>`, none of which exist without exception handling on WebAssembly. The parts that
need them are guarded out rather than making the header unavailable. Poco's `SignalHandler` is
guarded the same way, and `Thread_POSIX` stops referring to it.
Measured, `-Os`, stripped:
2278794 -> 2016304 bytes, 618187 -> 569362 gzipped
and the module no longer needs an engine implementing the exception-handling proposal - it now
loads on stock Node 20 with no flags, where before it required `--experimental-wasm-exnref`.
Separately, and because they are an obsolete C++ feature in a library we own: every `throw()`
exception specification in `base/poco` is now `noexcept`. There were nineteen, plus two written
`throw ()`. None of them were dynamic specifications, so this is a straight rename.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Three findings from breaking down where the 2.0 MB bundle actually goes. None of them is parser
code; together they are 203 KB, about 10%.
`abi::__cxa_demangle` was 132 KB - a complete C++ name parser, more than `src/IO` and `src/Core`
put together. The only thing reaching it is a type name inside an exception message, from
`FieldVisitorConvertToNumber`, `typeid_cast` and `makeASTForLogicalFunction`. In a build with no
exception handling that message is never displayed, so `demangle` returns the mangled name, which
is what it already does when demangling fails.
`ErrorCodes::values` was 150 KB of data - 86% of the whole DATA section. It is one
`ErrorPairHolder` per error code, each holding the last message, format string, query id and
captured stack trace, twice over for local and remote, plus a mutex. That is what backs
`system.errors`; a parser needs the code-to-name table above it and nothing else.
Two tables in `Access` were built at startup by expanding a macro list at every call site, the
same pattern already fixed for the SQL keywords: `makeNodes` compiled to 35 KB and the access-type
name converter to 11 KB, because each of the 258 entries materialized its own string views and
call. Both are driven from a `constexpr` table now. `makeNodes` still builds its tree at runtime -
it resolves parent groups by name - but from a loop rather than 258 inlined calls.
2016304 -> 1813657 bytes, 569362 -> 512278 gzipped
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…se conversion
libc++'s locale.cpp is over 150 KB and nothing in the parser wants a locale: keywords,
identifiers, access-type names and connection strings are all ASCII, and converting them
according to the C++ locale is wrong as well as expensive. Twelve objects were dragging it in,
none of them deliberately.
`boost::to_lower` and friends are locale-based, so `Access/Common` reached `std::locale` through
them - and `AccessType.h` reached it through `boost::algorithm::string/split.hpp`, which includes
`<ostream>`, so every translation unit that touched an access type paid for it. Those use the
ASCII helpers now, and `Common/StringUtils.h` gains `replaceAll` for the multi-character
replacements that `std::replace` cannot do.
The rest:
* fmt is built with `FMT_USE_LOCALE=0`; it only wanted a locale for thousands separators.
* Poco's `Bugcheck::what` built its message with an `ostringstream`. `Bugcheck.h` is reached from
`Poco/Foundation.h`, so that single `<sstream>` put the locale tables in front of nearly every
Poco translation unit - by itself it accounted for 181 KB of the bundle.
* `Poco/Net/IPAddress.h` included `<ostream>` for one `operator<<` declaration; `<iosfwd>` is
enough for a declaration.
1813657 -> 1603384 bytes, 512278 -> 462982 gzipped
Three referrers are left and locale.cpp stays linked until all of them go: Poco's `Format` and
`DigestStream`, which are stream-based by nature, and `double-conversion`, whose `ToLower` uses
`std::use_facet<std::ctype<char>>` to parse "infinity" and "nan" - that one is in the submodule
and needs a bump of the ClickHouse fork.
Check 20 forbids `boost::to_lower`/`to_upper` where the locale must not be linked. It covers
`src/Parsers`, `src/Access` and `base/poco`, which are now free of it; the rest of the tree still
has around ninety call sites, and the paths widen as those are converted.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
# Conflicts: # src/Common/ErrorCodes.cpp # src/Common/QueryFuzzer.cpp # src/Interpreters/InterpreterSystemQuery.cpp # src/Parsers/ASTAlterQuery.cpp # src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp
`programs/keeper-bench/Generator.cpp` uses `std::views::keys` while relying on `<ranges>` arriving transitively. The build defines `_LIBCPP_REMOVE_TRANSITIVE_INCLUDES`, so trimming includes elsewhere is enough to break it, which merging master into this branch did.
The README described the module as it was in the first commit of this series: 2.7 MB with abseil, re2 and cctz in it, requiring an engine that implements the WebAssembly exception-handling proposal, and shimming `Settings::castValueUtil` to keep the settings schema out. None of that is true any more - it is 1.6 MB, needs no flags, and the settings schema left the parser's closure for good rather than being shimmed away. Also: * `build.sh` no longer swallows compilation failures. It piped the compilers' output through `grep error: | head -20 || true`, so a translation unit that failed to compile was printed and then ignored, and the link picked up whichever objects a previous run had left in place. Each object is now removed before its compiler runs, and a failure stops the build. * `wasm_runtime.cpp` no longer defines `Settings::castValueUtil`. Nothing references it since `ParserSetQuery` stopped consulting the settings schema.
Deferring the "is this a Bool setting?" question from the parser to `BaseSettings::applyChange`
left the check unreachable for a query's own settings: `Context` applies them through
`Context::setSetting`, which takes a name and a value and never sees `SettingChange::shorthand`.
So `SET max_threads` silently became `max_threads = 1` - exactly the outcome the marker exists to
prevent - and `03623_setting_boolean_shorthand_err_test` failed on three of its four cases.
The check now runs wherever a whole `SettingChange` is available: `BaseSettings::applyChange` as
before, plus `Context::applySettingChange` and `Context::checkSettingsConstraints`. The constraint
check has to be covered too, because it converts the value to the setting's type first and would
otherwise report the type error as `BAD_GET` from a layer that cannot explain it - which is what
`SET default_database_engine` did.
The test gains the two cases that only the wrong-layer report would have hidden: that a rejected
shorthand leaves the setting at its previous value rather than at 1, and that `SETTINGS` in a
query is checked the same way. The latter uses `{ error ... }` rather than `{ serverError ... }`
because the client applies a query's `SETTINGS` to its own context and rejects it before sending.
|
Workflow [PR], commit [15c8d2b] Summary: ❌
AI ReviewSummaryThis PR substantially reduces the parser's dependency footprint and adds the standalone Findings
Tests
Final Verdict |
|
This supersedes #111971, but three fixes made there after its AI review are not, as far as I can see, in this branch — worth carrying over before #111971 is closed (commits on
Also in |
|
Superseded by #111994 (branch
The two open review findings here (the missing exception boundary around |
|
Update to the note above: the successor chain has moved on once more, so the branch that carries this work is now #112067 ( Re-verified today against the current heads ( The two unresolved
Leaving this open; which branch to keep and when to close the others is a human call. No rework or push done on |
# Conflicts: # src/Parsers/ASTColumnsTransformers.cpp # src/Parsers/ASTCreateQuery.cpp # src/Parsers/ASTSetQuery.cpp # src/Parsers/FunctionSecretArgumentsFinder.h
`cert-msc32-c`/`cert-msc51-cpp` on the deliberately deterministic seed, and `cppcoreguidelines-init-variables` on a pointer assigned on both branches below. Same fix as on the superseding branch, where `Build (arm_tidy)` verified it. Co-Authored-By: Claude Fable 5 <[email protected]>
…d out of a subquery `QueryTreeBuilder::buildSelectExpression` reads `limit` and `offset` out of a nested `SETTINGS` clause with `safeGet<UInt64>`, and `Field(true)` is stored as `UInt64`, so `SELECT * FROM (SELECT number FROM numbers(10) SETTINGS limit)` silently returned one row instead of rejecting the shorthand. Validate the changes against the settings schema first, as on the superseding branch. Co-Authored-By: Claude Fable 5 <[email protected]>
…orthand The storage `SETTINGS` clause is parsed with the shorthand enabled, and `Field(true)` is stored as `UInt64`, so `ENGINE = Join(...) SETTINGS max_rows_in_join` silently became `1` in `registerStorageJoin`, and the raw `String` readers (`getDiskName` of the Log family, `keeper_path` of the queue storages) gave `BAD_GET` instead of pointing at the shorthand. Reject the shorthand where the reader has no settings schema at hand, make `shorthand` part of a change's identity, and apply `SET` through `applySettingChange` so the flag survives the context-move path. Same change as on the superseding branch, with tests `04663` and `04664`. Co-Authored-By: Claude Fable 5 <[email protected]>
…access rights The filter is matched with `RE2::FullMatch` when access is checked, so a pattern that does not compile would grant nothing, silently. Validating it only in `InterpreterGrantQuery::execute` left `users.xml` grants, the `ATTACH USER`/`ATTACH ROLE` replay of `AccessEntityIO`, and `CHECK GRANT` unchecked. Move the check to `AccessRightsElement::throwIfFilterIsNotCompilable` and call it from all four paths, as on the superseding branch. Test `04661`; `03595` now expects `CANNOT_COMPILE_REGEXP` instead of a syntax error, which is this branch's deliberate behavior change. Addresses the unresolved review thread on the PR. Co-Authored-By: Claude Fable 5 <[email protected]>
…orting A few checks in the parser still report an invalid query by throwing - `Frame start cannot be UNBOUNDED FOLLOWING`, for one - so with `-fignore-exceptions` a mistyped query killed the module instance. `ch_format` now arms a `setjmp` boundary and `__cxa_throw` returns to it with the message, as a parse failure; recovery is gated on the thrown type being exactly `DB::Exception`, anything else still stops the module. Ported from the `parser-standalone-build` branch, where it costs 570 bytes. Addresses the unresolved review thread on the PR. Co-Authored-By: Claude Fable 5 <[email protected]>
On this branch `SYSTEM ... SET FAKE TIME` keeps its literal as text - which timezone applies belongs to the server, not to the query - so the JSON (de)serialization added on master has to write it as a string, not an integer. Semantic follow-up to the master merge. Co-Authored-By: Claude Fable 5 <[email protected]>
Master added AST JSON (de)serialization to `src/Parsers`, and the `writeJSON` / `readJSON` virtuals are referenced from every AST vtable even though nothing in the standalone module calls them, so the link needs the symbols. (The superseding branch strips them instead with full LTO and `-fvirtual-function-elimination`, which this branch does not use.) Co-Authored-By: Claude Fable 5 <[email protected]>
|
Brought the branch up to date with master (2249 commits, resolved the
Also carried over from the superseding branch, since the defects are in this branch's changes too: the schema check for the valueless Verified locally: Related: #112067 |
| { | ||
| hash_state.update(change.name.size()); | ||
| hash_state.update(change.name); | ||
| hash_state.update(change.shorthand); |
There was a problem hiding this comment.
shorthand is now part of ASTSetQuery semantics (updateTreeHashImpl, the formatter, and the setting-validation paths all consult it), but writeJSON / readJSON still drop it. That breaks the parseQueryToJSON / clickhouse_json round trip for valueless settings: SET max_threads serializes as a plain Bool(true) change, deserializes with shorthand = false, and is then applied as an explicit true/1 instead of being rejected as the valueless form. The new bit needs to be serialized and restored with each change.
| const auto maybe_uri = tryParseURI(change.value.safeGet<String>()); | ||
| if (maybe_uri && !maybe_uri->getUserInfo().empty()) | ||
| /// Secret only if there is actually a password embedded in it. | ||
| String uri_string = change.value.safeGet<String>(); |
There was a problem hiding this comment.
This runs before shorthand validation on the logging / query-normalization path (executeQuery.cpp calls hasSecretParts() on the parsed AST before InterpreterSetQuery ever checks the setting). For SET format_avro_schema_registry_url or SELECT 1 SETTINGS format_avro_schema_registry_url, change.value is the parser's placeholder Bool(true), so safeGet<String>() throws BAD_GET here and the user sees the wrong error from the secret-detection path instead of the intended TYPE_MISMATCH. hasSecretParts() needs the same if (change.shorthand) continue; guard that formatImpl() already has.
Supersedes #111971 and
#111952 — both are contained here and can be closed.
How small does
src/Parsersget when built on its own?utils/wasm-parseranswers it: a buildscript, a five-function C entry point and a test, producing a 1.6 MB WebAssembly module (463 KB
gzipped) that parses, pretty-prints and reports syntax errors with positions. It runs on any
engine — no flags, no exception-handling proposal. The motivating use case is
programs/server/play.html, which today ships only the lexer.Most of the value is in what had to be cut to get there, and almost none of it is parser code.
Everything below stands on its own.
Dependencies the parser did not need
abseil, cctz, re2,
boost::algorithm::stringandCore/Settings.hare all gone from the parser'stransitive closure.
SYSTEM ... SET FAKE TIMEwas parsedand formatted through
DateLUT. Which timezone applies belongs to the server, not to the querytext, so the AST keeps the literal and the interpreter resolves it.
(
maskURIPassword, Azure connection strings). The third compiledCOLUMNS('regexp')patternsinside
IASTColumnsTransformer::transform— applying a transformer needs the expanded columnlist, so it is name resolution, and it moves to
Interpreters/applyColumnsTransformer.cpp.Validating a
GRANT ... ON S3('...')pattern moves toInterpreterGrantQuery.IParser.hwanting a short non-allocating list andLiteralTokenMapwanting a flat map. The latter gets a purpose-built open-addressing tablewhich is faster than abseil's at every size, because nothing erases and the first entries live
inside the object.
ParserSetQueryconsulted the settings schema for one thing — whether a bareSET xnames aBool setting. It records that the value was omitted and
BaseSettings::applyChangechecks thetype, which is where the schema is known.
Exceptions
The parser used throw/catch to choose between alternatives, which is the wrong mechanism — the
failure is an ordinary parse outcome, and one of the four sites fired on any malformed string
literal. All four are gone,
src/Parserscontains nocatch, and a style check keeps it thatway. That lets the standalone build use
-fignore-exceptions, which dropped 262 KB and the needfor an engine implementing the exception-handling proposal.
Locale
Nothing wants a locale — keywords, identifiers and access-type names are ASCII — but twelve
objects were pulling
<locale>in.boost::to_lowerand friends are locale-based, andAccessType.hreached<ostream>throughboost/algorithm/string/split.hpp. Poco'sBugcheck::whatbuilt one message with anostringstream, and sinceBugcheck.hcomes in viaPoco/Foundation.h, that single include cost 181 KB. A second style check forbidsboost::to_lower/to_upperwhere the locale must not be linked.Costs that were not the parser
abi::__cxa_demanglewas 132 KB, reached only to put a type name in an exception message.ErrorCodes::valueswas 150 KB of data — the per-code error statistics behindsystem.errors,which a parser has no use for. Two
Accesstables were built at startup by expanding a macro listat each of 258 call sites; they are
constexpr-driven now.Latent bugs found on the way
ASTSQLSecurity::formatImplwas defined identically in two translation units. Static-librarylinking never pulls both objects in, so the ODR violation stayed invisible.
Poco/Util/Application.hinDumpASTNode.h, which reachesPoco::ThreadPooland is pulled in byInDepthNodeVisitor.h—over sixty translation units were paying for it.
uzliteral that does not fit a 32-bitsize_t, aProfileEventscounter/increment size mismatch, a Booststored_sizeconstraint inASTs, anditoa/iotaguarding theirlongoverloads onOS_DARWINwhen the real condition is thatlongis a distinct type.For every build, not just the standalone one
The SQL keyword table was built at startup by 645 inlined
resize/string-assign/emplacesequences, compiling to a 57 KB constructor — the largest function in the parser — and costing 645
string allocations per process. It is a
constexpr std::arraynow, and the two consistency checksthe constructor performed became
static_asserts, so they also run in release builds. Everythrow()exception specification inbase/pocois nownoexcept.Testing
No behaviour change is intended except where listed, so coverage is existing tests plus two unit
tests where hand-written code replaced a library:
gtest_mask_uri_password.cppchecks the string scan against the regular expression it replaces;they also agree on 200000 random strings over
ab:@/.and newline. This is masking of secrets,so "close enough" is not good enough.
gtest_literal_token_map.cppcovers overwriting, growth past the inline storage, and agreementwith
std::unordered_mapover 500 randomised rounds.User-visible changes, all deliberate:
SET max_threadsreports TYPE_MISMATCH from the server rather than a syntax error from theclient (03623 updated). It does not silently become
max_threads = 1, which is whatdeferring the check without a marker would have done.
GRANT ... ON S3('[')pattern reports CANNOT_COMPILE_REGEXP instead of a syntaxerror. It cannot simply be dropped: the pattern is matched with
RE2::FullMatch, so one thatdoes not compile would grant nothing, silently.
SYSTEM ... SET FAKE TIMEechoes its literal instead of renormalising it when formatted.user@hostwith nopassword is no longer rewritten to
user:[HIDDEN]@host, since there is nothing to hide.locale-driven.
Verified with a full
dbmsbuild, the whole ofcheck_cpp.sh, and the standalone build's testsuite at every step.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Reduced the dependencies and the code size of the SQL parser, which can now be built on its own — see
utils/wasm-parserfor a standalone WebAssembly build of it. The table of SQL keywords and the access-type tables are now built at compile time instead of on every server start.Documentation entry for user-facing changes