Skip to content

Support the short ATTACH syntax for views - #115351

Open
groeneai wants to merge 23 commits into
ClickHouse:masterfrom
groeneai:attach-view-short-syntax
Open

groeneai wants to merge 23 commits into
ClickHouse:masterfrom
groeneai:attach-view-short-syntax

Conversation

@groeneai

@groeneai groeneai commented Aug 18, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #115259

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

ATTACH VIEW <name> and ATTACH MATERIALIZED VIEW <name> now re-attach a previously detached view from its stored metadata, like ATTACH TABLE and ATTACH DICTIONARY already did. Previously only DETACH VIEW was accepted and the matching ATTACH was a syntax error. The definition is read on the node that runs the query, so these spellings are not supported for ON CLUSTER queries or in Replicated databases; use ATTACH TABLE there. Closes #115259.

Description

Requested by @ PedroTadim (ack).

VIEW was the only object kind where DETACH X <name> had no matching ATTACH X <name>:
ParserCreateTableQuery has a short-attach shortcut (ParserCreateQuery.cpp:858) but
ParserCreateViewQuery required the body. Added the same shortcut, keeping the view flags for routing.

Five interpreter changes follow, each proved on a build carrying only the earlier ones:

createTable synthesized an empty sql_security for any AST whose supportSQLSecurity() is true, which
the new branch sets, so has_dropped_clauses threw BAD_ARGUMENTS about a clause nobody wrote; now
suppressed for this shape.

Three are access checks, because getRequiredAccess() authorizes from the typed keyword before metadata
is read and CREATE TABLE implies CREATE VIEW. A CREATE VIEW-only user could attach a detached
ordinary table, re-attach a stored DEFINER view without SET DEFINER, and re-attach a
MATERIALIZED VIEW ... TO dst without the dst grant (all measured). So a view-spelled ATTACH whose
stored metadata is not a view is rejected, and the loaded SQL SECURITY clause (a stored CURRENT_USER definer is not re-resolved to the caller) and targets are authorized.
View spelling only; an IF NOT EXISTS no-op needs no such grant.

The fifth keeps the view spellings local. ON CLUSTER and Replicated databases enqueue before the
metadata load and the worker has no user, hence full access, so none of those checks can run: measured
there, a CREATE VIEW-only user re-attached both carriers and read privileged data, where no spelling
previously gave a route. ATTACH TABLE still works. The ON CLUSTER check also sits in execute(), since
distributed_ddl_entry_format_version below 3 dispatches before createTable; authorizing before
enqueueing is #111561's question.

Validation: seven new stateless tests plus a converted arm of 01600_detach_permanently, each verified
to fail without its change; these and four existing tests pass.

Sibling and edge-case matrix
statement before after
ATTACH VIEW v SYNTAX_ERROR re-attaches
ATTACH MATERIALIZED VIEW mv SYNTAX_ERROR re-attaches
ATTACH VIEW IF NOT EXISTS v SYNTAX_ERROR re-attaches, idempotent
ATTACH VIEW v ON CLUSTER c SYNTAX_ERROR INCORRECT_QUERY, use ATTACH TABLE
ATTACH VIEW db.v SYNTAX_ERROR re-attaches
ATTACH VIEW v UUID '...' SYNTAX_ERROR BAD_ARGUMENTS, as ATTACH TABLE t UUID '...'
ATTACH TEMPORARY VIEW v SYNTAX_ERROR (parser) SYNTAX_ERROR (interpreter), as ATTACH TEMPORARY TABLE
ATTACH VIEW <a table> n/a INCORRECT_QUERY, "it is a Table"
ATTACH VIEW v with stored DEFINER/NONE, caller lacking the grant n/a ACCESS_DENIED
ATTACH OR REPLACE VIEW v SYNTAX_ERROR unchanged
ATTACH SQL SECURITY INVOKER VIEW v SYNTAX_ERROR unchanged
ATTACH DEFINER = u VIEW v SYNTAX_ERROR unchanged
DETACH MATERIALIZED VIEW mv SYNTAX_ERROR unchanged, out of scope
ATTACH VIEW v in a Replicated database SYNTAX_ERROR INCORRECT_QUERY, use ATTACH TABLE
ATTACH TABLE <a detached view> works works
ATTACH TABLE/DICTIONARY/DATABASE, incl. ON CLUSTER works works

Workflow [PR]
Sync PR [sync-upstream/pr/115351]

groeneai and others added 3 commits August 18, 2026 14:57
VIEW was the only object kind where DETACH X <name> had no matching
ATTACH X <name>: ParserCreateTableQuery has an explicit short-attach
shortcut and ParserCreateDictionaryQuery skips its body clauses when
attaching, but ParserCreateViewQuery required the view body
unconditionally and died at the mandatory AS. ParserCreateTableQuery
needs the literal TABLE keyword, so the VIEW spelling could not reach
its shortcut either. Closes ClickHouse#115259.

Add the same shortcut to ParserCreateViewQuery, keeping the view flags
on the resulting ASTCreateQuery so the interpreter routes it as a view.
OR REPLACE and a user-typed SQL SECURITY clause are excluded, so those
spellings keep the syntax error they have today rather than silently
dropping a clause the stored metadata owns.

Two interpreter changes follow from the new parser path.

First, createTable synthesized an empty sql_security for any AST whose
supportSQLSecurity() is true, which is exactly what the new branch sets,
and the has_dropped_clauses guard then rejected the statement with
BAD_ARGUMENTS pointing at ALTER TABLE MODIFY SETTING. Suppress the
synthesis for the body-less ATTACH shape instead of reordering the
defaulting: reordering would apply creation-time defaults to an existing
stored view on every re-attach, and would newly demand SET DEFINER
permissions from the already-working ATTACH TABLE spelling. Only visible
when ignore_empty_sql_security_in_create_view_query is false, or when
refresh_strategy is set.

Second, getRequiredAccess authorizes from the typed keyword before the
stored metadata is read, and CREATE TABLE implies CREATE VIEW, so a user
holding only CREATE VIEW could have attached a detached ordinary table
via ATTACH VIEW t. Reject a VIEW-spelled short ATTACH whose stored
metadata is not a view. The TABLE spelling stays permissive: it requires
the stronger CREATE TABLE, so it grants nothing extra, and ATTACH TABLE
on a detached view is the workaround the issue documents.

ATTACH WINDOW VIEW has the same parser gap and is deliberately left
alone while the removal of WINDOW VIEW is in flight in ClickHouse#114747.

Co-Authored-By: Claude Fable 5 <[email protected]>
The suppression of the synthesized sql_security clause is invisible at
default server settings: refresh_strategy is parsed after the new
short-attach branch so it is always null there, and
ignore_empty_sql_security_in_create_view_query defaults to true, which
makes the remaining conjunct false. Reverting the guard therefore left
every test green. Nothing under tests/ sets that setting.

Add 04926_attach_view_short_syntax_sql_security.sh, which drives
clickhouse-local with a persistent path and passes the server setting
after a bare separator, covering both view kinds because
supportSQLSecurity() accepts ordinary and materialized views alike. It
carries a default-setting control arm and prints the effective setting
value, so an override that failed to take effect fails the diff instead
of passing for the wrong reason. Verified to redden with BAD_ARGUMENTS on
a build carrying only the parser change.

The docs listed only VIEW while the parser also accepts the optional
MATERIALIZED keyword, and removing the stale note about the short syntax
also removed the still-true statement that ATTACH TABLE reattaches a
detached view. Spell the optional keyword in both grammar blocks, add
views to the list of entities DETACH says can be reattached, and restore
the ATTACH TABLE fact on its own.

Each test now drops the objects it creates.

Co-Authored-By: Claude Fable 5 <[email protected]>
Review round 2 follow-up. No source change: the parser branch, the
is_short_attach suppression and the stored-kind check are untouched.

Docs: ATTACH TABLE does not accept a detached dictionary, so drop the claim
that it reattaches an entity of unknown kind, and name views in the attach.mdx
prose that the grammar block above it already lists.

Tests: the parser branch is guarded by !replace_view and !sql_security, and
neither field is copied into the resulting query, so dropping either conjunct
silently discards a clause the user typed. Three clientError arms pin them.
Two formatQuery arms pin the is_materialized_view and cluster copies; dropping
the former also makes the stored-kind check unreachable for the MATERIALIZED
spelling, so the access test now runs that spelling against a restricted user.

01600_detach_permanently used ATTACH TABLE for two materialized views because
the short form did not parse. It does now, so the test uses it and becomes the
only coverage of short ATTACH across a fresh process against a persistent path.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Before opening this PR I ran an independent cold review plus a second-model review pass over the diff, and adjudicated every finding against the code. Recorded for transparency; nothing below is an open question.

Round 3 (final). One finding, a re-raise of the diagnostics nit below. No source change was requested in this round, and the source diff has been byte-identical since round 1.

Round 2. 5 findings, all agreed and fixed. The first two were raised independently by both the cold review and the second model.

Finding Verdict
❌ The documentation edit claimed ATTACH TABLE is the way to reattach an entity whose kind you do not know. That is false: it rejects a detached dictionary (InterpreterCreateQuery.cpp:1807), and is_dictionary is set only by the DICTIONARY spelling, so the claim fails on the very list of kinds printed two lines above it. AGREED, corrected to the narrower true statement; views also added to the attach.mdx prose, which still omitted them.
❌ The new parser guard has three conjuncts and only one was covered by a test. !sql_security is access-relevant: the branch copies the clause nowhere, so deleting the conjunct would let ATTACH SQL SECURITY NONE VIEW v parse and silently drop the clause, and the existing has_dropped_clauses check cannot catch that because it tests a field the branch never sets. AGREED. Three negative arms added, each verified to redden under a mutation that deletes exactly its conjunct.
❌ The is_materialized_view and cluster copies were unpinned. Deleting the former leaves both view flags false, which drops authorization from CREATE VIEW to CREATE TABLE and also makes the new stored-kind check dead code for the MATERIALIZED spelling; deleting the latter executes an ON CLUSTER statement locally and silently. AGREED. Pinned with formatQuery() assertions, which parse and format without touching the catalog or resolving a cluster, plus a restricted-user materialized-view arm. Both verified to redden under mutation.
❌ 01600_detach_permanently.sh still used ATTACH TABLE with a comment asserting that short ATTACH MATERIALIZED VIEW does not work, so the tree contradicted the change, and the permanent-detach-across-restart lifecycle stayed uncovered for the new syntax. AGREED, converted. Its existing insert-and-count assertions already verify the view was reattached and resubscribed, and the edited test fails on the base binary.
⚠️ ATTACH VIEW <a dictionary> reports "Cannot ATTACH TABLE ..., it is a Dictionary", naming a statement the user did not type, because the pre-existing dictionary check runs first and hardcodes the word. AGREED and left for a separate change, noted here rather than folded in. Diagnostics only: the error code is right, the statement is refused and nothing is attached. Reordering the checks does not fix it (it would then say "it is a Table" about a stored dictionary), and the sibling message at :1812 is reached with a stored view too, so a correct message set needs both a typed-kind and a stored-kind stringifier across three pre-existing call sites. No test or doc asserts either string, so the tree is self-consistent as it stands.

Round 1 found the same class of problem on the other interpreter change: the !is_short_attach guard was invisible at default server settings, so reverting it left every committed test green. refresh_strategy is parsed after the new branch and is always null there, so the guard only bites when ignore_empty_sql_security_in_create_view_query is false, which nothing in tests/ set. Now covered by 04926_attach_view_short_syntax_sql_security.sh, verified to redden on a build carrying only the parser change, with a default-setting control arm that passes on both builds so the test isolates the guard rather than the parser. Also in round 1: the docs regression above was first raised as documenting less about ATTACH MATERIALIZED VIEW than before; the serverError INCORRECT_QUERY arm was recorded as justified against the fixed build only, with the access test carrying the security claim; and both new tests gained the drops they were missing.

Independently enumerated and cleared, recorded so they are not re-litigated: parser precedence (ATTACH TABLE is tried first and the new branch requires end-of-statement, so no previously valid parse is shadowed); the format round-trip of the new AST shape, which matters because a Replicated database re-parses the formatted entry on each replica; readJSON shape validation; children ordering; the deliberate omission of has_inner_uuid_clause and attach_as_replicated, both unreachable on this path (the first is derived from a clause parsed after the branch, the second has no parser in the view path at all); the asymmetry of the stored-kind check, whose symmetric arm would break ATTACH TABLE on a detached view; the TEMPORARY spelling, which stays rejected in the interpreter exactly as ATTACH TEMPORARY TABLE is; and the DETACH side, which derives the required privilege from the runtime object kind rather than the typed keyword and so has no matching gap.

Session id: cron:clickhouse-review-slot-48:20260818-185823

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, no server needed: printf 'ATTACH VIEW v\n' | clickhouse format returns Code: 62 ... SYNTAX_ERROR at position 15 on every run of the base binary.
b Root cause explained? ParserCreateTableQuery has a short-attach shortcut (ParserCreateQuery.cpp:858) and ParserCreateDictionaryQuery skips its body clauses when attaching; ParserCreateViewQuery has neither, so it requires the view body and fails at the mandatory AS. ParserCreateTableQuery needs the literal TABLE keyword, so the VIEW spelling never reaches its shortcut.
c Fix matches root cause? The missing branch is added in the view parser, next to the precedent it mirrors. Not a guard, not a widened bound, not a message-only change. The two interpreter changes were each proven necessary on a build carrying the parser change alone, before being added.
d Test intent preserved / new tests added? Three new stateless tests (syntax matrix, access arm, sql_security suppression), each verified to FAIL on the base binary. Every guard and copied AST field in the new branch is pinned by an arm proven to redden under a build deleting exactly that one line: !sql_security, !replace_view, is_materialized_view and cluster (four mutation binaries, distinct build ids, each reddening only its own arm). One existing test is strengthened rather than weakened: 01600_detach_permanently used ATTACH TABLE for two materialized views only because the short form did not parse, so it now uses the short form, with its .reference unchanged. Each test drops what it creates. 01153_attach_mv_uuid guards that ATTACH TABLE on a detached view still works, and it passes.
e Both directions demonstrated? Yes for every part: parser (base Code: 62 vs fix accepted, 6 spellings); the sql_security synthesis (parser-only build BAD_ARGUMENTS, fixed build succeeds, plus a default-setting control arm that passes on both so the test isolates the guard and not the parser); the access hole (parser-only build attaches a table with only CREATE VIEW, fixed build returns INCORRECT_QUERY and attaches nothing); the converted 01600_detach_permanently (fails on base with SYNTAX_ERROR on both new statements, passes on the fix, .reference untouched); and each of the four single-line mutations above.
f Fix is general across code paths? Sibling parsers enumerated: table and dictionary already have the shortcut; ATTACH WINDOW VIEW has the same gap and is deliberately deferred to #114747, which removes WINDOW VIEW from this same file; the DETACH side (ParserDropQuery accepts only bare VIEW) is disclosed in the body and out of scope. Fixed in the parser, where the asymmetry lives.
g Fix generalizes across inputs (params/datatypes/wrappers)? Matrix run: ordinary and materialized view; IF NOT EXISTS twice (idempotent); ON CLUSTER (resolves the cluster); db.name; UUID '...'; trailing ;; TEMPORARY; cross-kind (VIEW spelling on a table and on a dictionary, MATERIALIZED VIEW spelling on an ordinary view, bare VIEW on a materialized view); plus 7 spellings asserted to stay rejected.
h Backward compatible? (maintainer-approved exception only) Yes. Additive on the parser side: the branch fires only where master returns SYNTAX_ERROR. No setting added or default changed, so no SettingsChangesHistory.cpp entry. No serialization or format version change; the AST is what formatQueryImpl already emits for views, round-trip verified twice through clickhouse format. The one behavior change applies only to the body-less VIEW spelling, which did not parse before this PR.
i Invariants and contracts preserved? The new AST carries only fields parsed before the branch point, so every clause the stub path would silently drop is null there (comment, refresh_strategy, select, targets, as_table_function, aliases_list, columns_list, storage, to_inner_uuid). has_uuid_clause is the deliberate exception and the existing guard rejects it. is_short_attach is computed before the sql_security defaulting and nothing between writes storage, columns_list or attach. The DDL guard is still taken before metadata is read. No new locks, no data deletion.

Session id: cron:clickhouse-impl-slot-6:20260818-175300

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [87ce6de]

Summary: ✅


AI Review

Summary

This PR adds short ATTACH VIEW / ATTACH MATERIALIZED VIEW syntax, wires in the stored-definition access checks that the plain SQL surface needed, and rejects the ON CLUSTER / Replicated routes where those checks cannot run under the initiator's privileges. The normal SQL path now looks consistent, but the clickhouse_json entrypoint still leaves one blocker: a table-only attach_as_replicated flag can ride the new short-view attach surface and mutate detached materialized-view metadata before the stored-definition validation below has a chance to reject it.

Findings

❌ Blockers

  • [src/Interpreters/InterpreterCreateQuery.cpp:2039] attach_as_replicated is still reachable through clickhouse_json on the new view short-ATTACH surface. ASTCreateQuery::readJSON accepts the flag on any ATTACH, not just ATTACH TABLE, so a crafted ATTACH MATERIALIZED VIEW ... AS REPLICATED on a detached inner-table MV reaches convertMergeTreeTableIfPossible here and rewrites the detached metadata / clears transaction metadata before the stored SQL SECURITY / target checks run. With default table_engines_require_grant = 0, that parser-impossible query can even succeed for a user who only has CREATE VIEW; with stronger grants it still mutates on-disk state before an eventual ACCESS_DENIED. Reject the flag for view ASTs before this block (ideally in src/Parsers/ASTCreateQuery.cpp during JSON deserialization as well), and extend tests/queries/0_stateless/04926_attach_view_short_syntax_json_ast.sh with a detached inner-table MV carrier instead of only the detached-table mismatch.
Final Verdict

❌ Changes requested — the SQL surface looks good now, but the JSON AST entrypoint still exposes a real privilege/metadata-mutation hole on the new short-view attach path.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @evillique @SmitaRKulkarni, could you review this? ParserCreateViewQuery had no short-attach shortcut, so ATTACH VIEW v failed at the mandatory AS while DETACH VIEW v worked; adding it also required suppressing the empty sql_security synthesis for the body-less shape and rejecting a VIEW-spelled short ATTACH against non-view metadata, since authorization happens from the typed keyword before metadata is read.

@evillique evillique self-assigned this Aug 18, 2026
@evillique evillique added the can be tested Allows running workflows for external contributors label Aug 18, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 87ce6deec with master 5a4550297 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 46dfb8152; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

9 translation units recompiled, 29 s compile time in total, 9 of them have a recent master baseline.

Job report

groeneai and others added 2 commits August 19, 2026 05:28
The short ATTACH shortcut for views added in this PR is authorized from the
typed keyword, before the stored definition is read: getRequiredAccess() sees
only the stub AST, so it asks for CREATE_VIEW, and processSQLSecurityOption is
skipped because the stub's sql_security is null. Nothing re-validates after the
metadata load, so a user holding CREATE_VIEW but not SET_DEFINER or
ALLOW_SQL_SECURITY_NONE could re-attach a view whose stored metadata carries
SQL SECURITY DEFINER or NONE, then read through it.

Measured on a debug build: a user granted only SELECT and CREATE VIEW attaches a
permanently detached DEFINER view and reads data it has no SELECT grant for,
while CREATE VIEW ... DEFINER = u is refused ACCESS_DENIED for the same user.

The TABLE spelling is not affected in the same way because it requires
CREATE_TABLE, which is strictly stronger (CREATE_TABLE implies CREATE_VIEW), so
widening to the VIEW spelling is what exposes the operation to a weaker
audience. Authorize the loaded clause after the metadata load and before it
takes effect, only for the view spelling; tightening the pre-existing TABLE path
would be a backward-incompatible change and is left alone.

The call is check-only for a stored clause: the defaulting branch is skipped
because a stored clause always has its type set, and the ephemeral-definer
branch is gated on CREATE-level loading, so no user is created on attach.
Server startup and Replicated DDL worker legs run with no user and keep full
access; the Replicated path enqueues before the metadata load. A definer
re-attaching their own view is unaffected, and INVOKER views carry neither
gated property.

Reported by the automated reviewer on this PR.
The short ATTACH path authorizes from the typed keyword before the stored
definition is loaded, so a VIEW-spelled statement only ever demanded
CREATE_VIEW. getRequiredAccess adds SELECT | INSERT for every named target of
a materialized view, but on this path the stub AST has no targets, so the
grants the full CREATE syntax demands on the target were never checked.

Measured on the previous head: a user holding only CREATE VIEW and SELECT on
the source re-attached a detached MATERIALIZED VIEW ... TO dst and the
pipeline then wrote into dst, while the same user was denied both the
equivalent CREATE and a direct read or write of dst.

Authorize the loaded targets after the metadata load and before the copy,
mirroring what getRequiredAccess does for the full syntax. View spelling only:
the TABLE spelling requires the stronger CREATE_TABLE.

Co-Authored-By: Claude Fable 5 <[email protected]>
groeneai and others added 5 commits August 19, 2026 20:54
A short ATTACH carries no definition of its own, so the grants it needs are known only
after the stored metadata is read. Every distributed route enqueues the entry before that
read, and the worker that replays it runs with no user, which grants full access, so the
stored-kind check, the SQL SECURITY authorization and the named-target authorization can
only be enforced for a query that executes on the initiating node.

Measured on a Keeper-backed Replicated database and on ON CLUSTER: a user granted only
CREATE VIEW re-attached a detached MATERIALIZED VIEW ... TO dst and a stored
SQL SECURITY DEFINER view, then read data it holds no grant for, while the equivalent
CREATE spellings and the direct grants on the target were all denied. Before this PR that
user had no route at all, since ATTACH TABLE and ATTACH DICTIONARY demand grants it lacks
and the VIEW spelling did not parse.

The check sits in execute() rather than createTable() because
distributed_ddl_entry_format_version below 3 dispatches ON CLUSTER queries straight to
executeQueryOnCluster and never reaches createTable; versions 1 and 2 are still supported,
and the bypass was reproduced at both. ATTACH TABLE keeps working on these routes and
remains the way to re-attach a detached view there. ATTACH DICTIONARY and ATTACH DATABASE
are unaffected.

Co-Authored-By: Claude Fable 5 <[email protected]>
The distributed guard tested `!create.storage` while `createTable` treats a storage node
without an engine as short syntax too, so a `clickhouse_json` AST carrying an empty storage
clause slipped past it. Both sites now call one `isShortAttach` helper, which is what keeps
them from drifting apart again.

The error also suggested an unqualified `ATTACH TABLE v` for `ATTACH VIEW other.v`, which
names a different table; it now keeps the database qualifier.

Tests: pin `distributed_ddl_entry_format_version = 2`, since versions below 3 dispatch
`ON CLUSTER` before `createTable` and a guard placed there would leave the other cases
green. Tag the tests that re-attach views locally `no-replicated-database`, because the
harness database is Replicated under that job and those attaches are now rejected, and tag
the new Replicated test `zookeeper` so jobs without Keeper skip it.

Co-Authored-By: Claude Fable 5 <[email protected]>
The error suggested `ATTACH TABLE db.v;`, which silently dropped `ON CLUSTER` and
`IF NOT EXISTS` from the query it was rejecting; following it would attach locally and lose
idempotence. It now names the spelling to replace and says to keep the rest of the query,
so nothing has to be reconstructed.

The JSON AST dialect can carry an `ASTStorage` without an engine, which the SQL short-view
parser never produces, so the added test pins the shape that motivated sharing
`isShortAttach`. Verified against a build using the former `!create.storage` predicate: the
statement passes the guard and reaches the cluster dispatch, and the test reddens. Its DDL
wait is bounded so that regression fails fast instead of blocking on the task timeout.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ored Window Views

Two defects in the stored-definition authorization added earlier in this PR, both measured.

The `SQL SECURITY` and target checks ran before the `if_not_exists` no-op was reached, so a
caller holding only CREATE VIEW got ACCESS_DENIED for a view that was already attached and
whose definition would not be applied at all. The checks now skip that case.

`isView()` also covers Window Views, which the view parser cannot spell, so the stored kind
was accepted and then overwrote the stub: `ATTACH VIEW wv` attached a stored WINDOW VIEW
with engine WindowView. Rejected now, with `ATTACH TABLE` named as the way to attach one.

Co-Authored-By: Claude Fable 5 <[email protected]>
…hint

The top-level grammar applied the `ON CLUSTER` suffix to every alternative, including the view
spellings that are local only, so it contradicted the restriction stated below it. Split it.

The Window View diagnostic suggested a bare `ATTACH TABLE wv;`, which drops the database
qualifier and `IF NOT EXISTS`; it now names the spelling to replace, like the distributed one.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7a37de2

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_tsan, flaky check) job wedged in stateful-dataset prep, SIGKILLed at the 9000s cap before any test ran (no test rows published) a fix task is created (investigating at full effort - fixing-PR link to follow on this PR)

Not caused by this PR: the other 4 flaky-check legs at this head (amd_asan_ubsan, amd_binary,
amd_debug, amd_msan) are all green, and this PR's own new 04926_attach_view* tests are 1755 OK /
0 FAIL. The job's last output is the tpch table listing from create_tpch.sh at 00:00:14Z, followed
by ~2h23m of silence and Timeout exceeded [9000]; clickhouse-test never started. Breadth on this
job flavour is 17 rows across 15 unrelated PRs and 0 master in 30 days.

Session id: cron:our-pr-ci-monitor:20260820-053000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stateless tests (amd_tsan, flaky check) job timeout on the CI finish ledger above: #115585

The job was not failing a test: prepare_stateful_data wedged on one statement and praktika's 9000 s watchdog killed the job before clickhouse-test started, so the check published no test result at all. Five occurrences in 60 days, all amd_tsan, none on master. #115585 bounds each prep statement so the wedge fails fast with the statement named, and the job still reaches log collection.

Master moved the ATTACH and DETACH reference pages into the source that
generates them: the page bodies now sit between AUTOGENERATED markers and
are produced from the `.description` strings registered by
`factory.registerStatement` in ParserCreateQuery.cpp and ParserDropQuery.cpp
(9253de5). ci/jobs/docs_job_mintlify.py rejects a pull request that
edits a marked region directly, so this branch's documentation of the short
`ATTACH VIEW` spelling moves from the .mdx pages into those two strings; both
pages are taken from master unchanged.
The check in `execute` resolves the database once, but `createTable` resolves it
again before it enqueues a replicated DDL entry or sends the query on to a
cluster, so a view spelling could still reach either route if the database
changed in between. Both routes now call the rejection directly, and the
rejection itself moves into one function the three sites share.

The `.syntax` field registered for `ATTACH` gains the view shorthand: it is
served from `system.statements`, and the description beside it already
documented the spelling.
…ects alone

`isShortAttach` tested `columns_list` for presence, but the JSON AST dialect can
build a columns node that declares nothing, and formatting omits such a node.
The initiator therefore took the full-definition route and queued text that
reparses as a short `ATTACH VIEW` on the workers, which authorize the stored
definition without the initiating user. Measured on a single node before the
change: the empty-columns carrier reached `executeQueryOnCluster` (`Code: 139`,
no DistributedDDL configuration) where the same query without the node was
rejected.

A temporary object belongs to no database, so the view check no longer runs for
one: `DatabaseReplicated::shouldReplicateQuery` answered for the current database
first and reported the Replicated restriction instead of the rejection that names
temporary attach.

Both carriers get a regression arm. The temporary arm was verified to fail
without the exclusion.
The engine conversion that `AS REPLICATED` asks for rewrites the metadata on disk
and removes transaction files, and neither is rolled back when the query then
fails. It ran before the checks that compare the spelling in the query against
the kind found in the stored metadata, so a view spelling aimed at a stored
`MergeTree` table converted that table and only afterwards reported that the
object is not a view. Measured with the flag carried on a view AST through
`clickhouse_json`: the query failed identically either way, but the stored engine
came back as `ReplicatedMergeTree` before this change and stays `MergeTree` after
it. The conversion now follows every check of the stored kind.
`.claude/CLAUDE.md` asks for `f` rather than `f()` when the text refers to a
function itself.
Comment on lines +215 to +228
/// A short ATTACH is authorized only once the stored definition has been read, which happens on the
/// node that executes the query. A distributed route enqueues before that read, and the worker
/// replaying the entry runs with no user, hence full access.
void rejectShortAttachViewOutsideOneNode(const ASTCreateQuery & create)
{
if (!create.isView() || !isShortAttach(create))
return;

throw Exception(ErrorCodes::INCORRECT_QUERY,
"The short ATTACH {0} is not supported for ON CLUSTER queries and Replicated "
"databases, because the stored definition is read on the node that executes the "
"query. Replace {0} with TABLE, keeping the rest of the query.",
create.is_materialized_view ? "MATERIALIZED VIEW" : "VIEW");
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This makes this feature completely useless.

because the stored definition is read on the node that executes the query

Yeah, that is kind of the whole point.

What is the actual problem with allowing it on ON CLUSTER queries and in Replicated dbs?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and the semantics are not what I was guarding: reading the stored definition on the executing node is the point. What differs is which grant is enough.

Measured on a Keeper-backed Replicated database and via ON CLUSTER, guard absent, user granted only CREATE VIEW ON rr.* plus SELECT on the source table:

  • a stored SQL SECURITY DEFINER view attaches, and that user then reads privileged data it holds no SELECT grant for;
  • a stored MATERIALIZED VIEW ... TO dst attaches with TO dst preserved, and rows start flowing into dst.

Locally both are ACCESS_DENIED. Controls for that user all deny: CREATE VIEW ... DEFINER = default, INSERT INTO rr.dst, and a direct read of the source. Cause: both routes enqueue before getCreateTableQuery loads the definition, and the replaying worker has no user, where full_access is !user_id (Context.cpp:2309), so the post-load checks are no-ops there.

The bypass itself is pre-existing, ATTACH TABLE does the same on master. It just demands CREATE TABLE, which implies CREATE VIEW, so the short view spelling would hand it to a strictly weaker audience. That widening is the whole of my objection.

So instead of rejecting, I will require on those two routes what the TABLE spelling already requires: CREATE TABLE on the object. Then the short view spelling works everywhere and nobody reaches anything they could not reach before. Loading and authorizing the definition before the enqueue would be better, but the initiator may not hold the database for an ON CLUSTER query, which is the replicated-DDL authorization fork in #111561.

If you would rather have no check there at all and treat the widening as acceptable because ATTACH TABLE already allows it, say so and I will simply delete the guard.

@evillique

evillique commented Aug 27, 2026 •

Copy link
Copy Markdown
Member

@groeneai, Also, if we add attach materialized view, then shouldn't we add a detach with the same 'materialized'. Otherwise, there is still a discrepancy, as in the original issue. What do you think? What is the general SQL rules for this in other dbs?

Should we even have ATTACH MATERIALIZED VIEW?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Measured on master 82cfa6a421bb9c1, formatQuery per spelling:

  • DETACH MATERIALIZED VIEW mv and DROP MATERIALIZED VIEW mv are both Code 62 SYNTAX_ERROR. MATERIALIZED is not a keyword in ParserDropQuery at all, only TABLE, VIEW, DICTIONARY, and DETACH VIEW / DROP VIEW accept a materialized view.
  • ATTACH MATERIALIZED VIEW mv (...) ENGINE = ... AS SELECT ... is already accepted, and it is the form the server itself writes: the metadata file of a materialized view begins ATTACH MATERIALIZED VIEW _ UUID '...' TO INNER UUID '...'.

So the asymmetry in #115259 is DETACH VIEW against ATTACH VIEW, and the short form closes exactly that pair. ATTACH MATERIALIZED VIEW mv adds no keyword, it is the short form of a spelling master already parses and emits, so it creates no new discrepancy: the MATERIALIZED gap sits on the DETACH / DROP side, covers the long form as well, and predates this PR.

Adding DETACH MATERIALIZED VIEW means adding MATERIALIZED to ParserDropQuery, which also yields DROP MATERIALIZED VIEW, as a synonym for what DROP VIEW already does. Small, and I am happy to do it here or separately.

Other engines: I checked PostgreSQL 16.15 only. It carries both spellings on both sides and enforces the kind exactly, DROP VIEW mv gives ERROR: "mv" is not a view. HINT: Use DROP MATERIALIZED VIEW to remove a materialized view., DROP MATERIALIZED VIEW v gives ERROR: "v" is not a materialized view, and ALTER behaves the same. ClickHouse is permissive in the other direction. I did not check MySQL, which has no materialized views, or any other engine.

On whether ATTACH MATERIALIZED VIEW should exist: in the short form the keyword is decorative, since the kind comes from stored metadata and nothing compares the two, so ATTACH MATERIALIZED VIEW on a plain view is accepted. I lean to keeping it, because it mirrors the stored form and it is what the 01600_detach_permanently.sh comment this PR deletes was complaining about. Dropping it is a two-line parser change and ATTACH VIEW mv still re-attaches a materialized view. If you prefer the PostgreSQL rule, I can reject a kind mismatch instead. Tell me which of the three you want.

Master added `replaceLegacyToTimeInCreateQuery`,
`substituteUserDefinedFunctionsOutsideEngines` and
`normalizeLegacyToTimeInCreateQuery` at the same place this branch adds
`isShortAttach` and `rejectShortAttachViewOutsideOneNode`, and the conflict cut
just before the brace closing the last one. Kept both sets.

The translation unit was syntax-checked after the resolution.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
/// `getRequiredAccess` ran on the stub, which has no definition, so nothing the stored
/// definition carries is authorized yet, and CREATE_VIEW alone reaches here. An `IF NOT
/// EXISTS` no-op applies no definition, so it must not demand the definition's grants.
if (create.isView() && !(if_not_exists && database->isTableExist(create.getTable(), getContext())))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

attach_as_replicated is still reachable on the new short-view surface through clickhouse_json, and this block applies it before the post-load checks below. ASTCreateQuery::readJSON() only rejects attach_as_replicated on non-ATTACH queries, not on view ASTs, so a crafted ATTACH MATERIALIZED VIEW JSON payload can carry AS REPLICATED, pass getRequiredAccess() with only CREATE VIEW, and land here with a detached inner-table MV. convertMergeTreeTableIfPossible(create_query, ...) then rewrites the detached metadata file (and may clear transaction metadata) before anything rejects the parser-impossible view/table mismatch. For MVs that also carry stored SQL SECURITY or TO dst, the ACCESS_DENIED from the new block at :1919 would arrive only after those side effects.

Please reject attach_as_replicated for any view-spelled short ATTACH before this block, and ideally at ASTCreateQuery::readJSON() too, since the SQL parser cannot produce that combination. A focused regression arm in 04926_attach_view_short_syntax_json_ast.sh on a detached inner-table MV would pin it.

@clickhouse-gh clickhouse-gh Bot added the comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. label Sep 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

Dear @evillique, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

alexey-milovidov and others added 2 commits October 10, 2026 17:34
Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	src/Interpreters/InterpreterCreateQuery.cpp
WINDOW VIEW was removed on master (ClickHouse#114747), so `ASTCreateQuery` no longer
has `is_window_view` and the stored metadata can no longer hold that kind:
`isView()` is now exactly an ordinary or a materialized view. Remove the
check that rejected a stored Window View and its test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Oct 10, 2026
groeneai and others added 5 commits October 11, 2026 02:51
A full ATTACH MATERIALIZED VIEW ... TO ... AS SELECT carries no columns and no
engine, so it takes the short-ATTACH path, where createTable rejects the clauses
it would drop with BAD_ARGUMENTS. The early check in execute() ran before that
and answered INCORRECT_QUERY ("the short ATTACH ... is not supported for ON
CLUSTER queries and Replicated databases") for a query that is not the short form,
which broke 04247 cases 18-20 under the Replicated database lane.

The clause check moves into one helper that both sites call, and execute() runs
it before the route rejection, so every route reports the dropped clauses first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
CREATE resolves `DEFINER = CURRENT_USER` into the creator's name but keeps the
`is_definer_current_user` flag on the AST. An on-disk database reparses the
formatted metadata, which loses the flag, but a Memory database returns a clone
of the parsed AST, so the short ATTACH VIEW authorization resolved the flag
again: the definer became the attaching user and SET DEFINER was never checked.
Measured: a user with only CREATE VIEW re-attached another user's DEFINER view
in a Memory database and became its definer, while the same query in an Atomic
database is refused with "necessary to have the grant SET DEFINER ON <creator>",
and ATTACH TABLE keeps the creator.

A stored definer is authoritative, so the flag is cleared before the stored
clause is authorized.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The early rejection in execute() resolved the database to ask whether it is
Replicated, and it runs before checkAccess. A user without any grant therefore got
INCORRECT_QUERY for `ATTACH VIEW rdb.v` when `rdb` is a Replicated database and
ACCESS_DENIED for an Atomic or a missing one, which reveals the engine of a database
the user cannot see. Measured with a user holding no grants: both now answer
ACCESS_DENIED.

The early check keeps only the syntactic ON CLUSTER case, which needs it because
distributed_ddl_entry_format_version below 3 dispatches straight to the cluster.
A Replicated database is still rejected in createTable, after authorization.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
execute() no longer looks the database up, so createTable is the only place that
classifies it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-view Logical (non-materialized) views. and removed comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. labels Nov 19, 2026

This branch has not been deployed

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

Labels

can be tested Allows running workflows for external contributors comp-view Logical (non-materialized) views. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ATTACH VIEW <name> is a syntax error although DETACH VIEW <name> is accepted

3 participants