ClickHouse
ClickHouse in Ptah - the capability-limited preset, the MergeTree round trip, views and materialized views, roles and grants, and the revision table's engine.
Edge documents the current development build and may describe unreleased behavior. To use those commands, build Ptah from master. For an installed release, select its version in the header.
ClickHouse support is capability-limited. The preset models enums as inline
Enum8/Enum16 column types: a column typed with a declared enum, or typed
ENUM with its values, is written as Enum8('draft' = 1, 'live' = 2), numbered
from 1 in declaration order, and as Enum16 past 127 values. Foreign keys are
outside the preset; CHECK constraints are created and enforced, within the limits
CHECK constraints states. Roles and grants are managed declaratively, within the
boundaries Roles and grants states.
Review generated SQL and the
capability gates before adopting a workflow
on ClickHouse.
Schema sources
Section titled “Schema sources”Choose SQL, YAML, HCL, DBML, or Go annotations for the desired schema.
These examples declare the same events table with a MergeTree engine sorted
by id. Save the selected file, then run the command below it to preview SQL
without connecting to a database.
CREATE TABLE events ( id UInt64, payload String) ENGINE = MergeTree ORDER BY id;ptah schema render --schema-file schema.sql --dialect clickhousetables: events: columns: id: type: UInt64 primary: true not_null: true payload: type: String not_null: trueptah schema render --schema-file schema.yaml --dialect clickhousetable "events" { column "id" { type = "UInt64" } column "payload" { type = "String" } primary_key { columns = [column.id] }}ptah schema render --schema-file schema.hcl --dialect clickhouseTable events { id UInt64 [pk, not null] payload String [not null]}ptah schema render --schema-file schema.dbml --dialect clickhousepackage models
//ptah:schema:table name="events"type Event struct { //ptah:schema:field name="id" type="UInt64" primary="true" not_null="true" ID uint64 //ptah:schema:field name="payload" type="String" not_null="true" Payload string}ptah schema render --root-dir ./models --dialect clickhouseSQL expresses ClickHouse engine clauses directly. YAML and HCL use table
platform properties for clickhouse; Go annotations use
platform.clickhouse.* attributes. DBML uses the default MergeTree engine and
the declared primary key for sorting. It cannot declare engine overrides,
skipping-index granularity, views, roles, or grants. Use another format when
the desired schema must own those settings or objects.
The supported declarations differ by format:
| Format | Engine overrides and index granularity | Views, roles, and grants | Refresh schedules | Row policies |
|---|---|---|---|---|
| SQL | Yes | Yes | Yes | Yes |
| YAML | Yes | Yes | Yes | Yes |
| HCL | Yes | Yes | Yes | Yes |
| DBML | No | No | No | No |
| Go annotations | Yes | Yes | Yes | Yes |
The same source selectors work with schema comparison and migration planning. See Work with a desired schema for the shared workflow and DBML limitations for objects a DBML source leaves outside its scope. External programs emit SQL, YAML, or HCL; they use the same syntax as the corresponding file format.
Heredocs in migration files
Section titled “Heredocs in migration files”A migration file may hold a heredoc, $tag$ ... $tag$, and Ptah splits the file
into statements as ClickHouse reads it. A semicolon inside a heredoc, or the
delimiter a -- atlas:delimiter directive declares, does not end the statement:
CREATE TABLE notes (id UInt8, body String DEFAULT $1abc$x; y$1abc$) ENGINE = MergeTree ORDER BY id;The server stores the default as 'x; y'. A tag holds ASCII letters, digits,
underscores and characters outside ASCII, and may begin with a digit, so $1abc$
opens a heredoc here, where PostgreSQL reads $1 as a parameter. A tag that is
never closed opens nothing: CREATE TABLE t (id UInt8, $ab$ UInt8) names a column
$ab$, and the statement ends at its semicolon. A dollar sign inside a name
opens nothing, so x$b$ is one name, while 1$a$x$a$ is the number 1 and a
heredoc. ptah migrations lint and ptah sql lint split a file the same way,
and a name inside a heredoc does not decide the order a schema’s views are
created in.
ClickHouse 24.10 also reads a tag that holds any other character but a dollar
sign, so it reads $a-b$x; y$a-b$ as one heredoc. Ptah does not, and splits that
text at the semicolon, so the server refuses both parts. Use a tag of letters,
digits and underscores on 24.10. ClickHouse 25.8, 26.3, 26.9 and 26.10 refuse a
tag that holds a hyphen or a character outside ASCII with code 62.
One database per run
Section titled “One database per run”A run reads and writes the one database the URL names, or default when it names
none. A document may leave a table unqualified, or name that database. A YAML
table names its database in its schema key; a bare table key such as app.t is
refused rather than read as a table named app.t. A document
that declares another database, with schema "other" {} or CREATE DATABASE other;, or puts an object in one, is refused before anything is planned:
error: the document declares database "other", but the target URL is limited to database "app"; name that database in the URL, or leave the database out of the nameA read cannot find a table in another database, so without the refusal every run
plans its CREATE TABLE again. Ptah creates no ClickHouse database, so a run
against a database the server does not hold fails on the server instead.
Ptah writes every ClickHouse name it puts into a statement in backticks:
databases, tables, columns, constraints, indexes, views, the sorting key it
derives from the primary-key columns, and each column a skipping index names
in its column list. Inside the backticks a backtick is doubled and a backslash
is written as two, because ClickHouse reads a backslash in a quoted name as an
escape. Measured on 24.10 and 26.10, `a\tb` names the three characters
a, a tab and b, and `a\\tb` names a\tb.
So a column named c -- d is one name. Written bare, ALTER TABLE tq DROP COLUMN c -- d reads -- d as a comment and drops the column c with its
rows. A skipping index declared on the column x-y is an index on that column,
which the server reports back as `x-y`; written bare, its key would be the
expression x - y.
A quoted name in a SQL schema file is read as the server reads it: \t is a
tab, \x41 is A, \N stands for nothing, and a backslash before a byte with
no escape meaning, as in `a\zb`, is kept. A quoted name that the server
refuses, such as `a\x4`, or that its release lines read differently, such
as \x before a byte that is not a hexadecimal digit, refuses the file:
error: error parsing schema file: read SQL schema file schema.sql: schema file schema.sql: line 1: the quoted name `a\x4` is not a clickhouse name Ptah reads as the server does: inside quotes a backslash starts an escape, and this escape is incomplete, refused by the server, or read differently by server release; write a backslash the name holds as twoAn expression the declaration writes reaches the server as written, so a name
inside it is quoted by its author. That holds for a TTL, a CHECK, the key
expression of a skipping index, an explicit ORDER BY, PRIMARY KEY,
PARTITION BY or SAMPLE BY, and a DEFAULT, MATERIALIZED or ALIAS
value. The server prints a name back in its own spelling, and the comparison
reads a quoted name and its bare spelling as one name: a sorting key written
(`id`, `a b`) reads back as id, `a b` and plans nothing.
A name spelled not, in any case, cannot appear quoted in such an
expression, in the arguments of a table engine such as
ReplacingMergeTree(`not`), in the body of a view or a materialized view,
in the filter of a row policy, or in the sorting key Ptah derives from a
primary-key column of that name. Measured on 24.10 and 26.10, the server
stores the name as the bare word not, and then SHOW CREATE and every read
of the schema fail with code 62, or, for `not` + 1, read back NOT 1,
another expression. A row policy filter fails sooner: the server refuses
CREATE ROW POLICY itself with code 62, after the plan has created the table.
25.8, 26.3, 26.7, 26.8 and 26.9 store a sorting key and a view body the same
way, and 26.11 keeps the backticks. Ptah renders without knowing the release,
so it refuses the render or the plan on every release before anything runs,
and names the clause and the name. A plan that creates a table again names the
copy it creates, ptah_rebuild_<table>:
error: error rendering clickhouse schema: unsupported feature: ClickHouse: the ORDER BY of table "tq" names `not`; releases before 26.11 store that name as the bare word not, the NOT operator, so the statement or every later read of the schema fails, or the definition means another expression; rename itA nullable column named not cannot be made NOT NULL, even with a default.
Ptah fills its NULL rows with ALTER TABLE ... UPDATE before the MODIFY COLUMN, and 25.8 to 26.10 refuse that statement with code 62 for such a
column, in backticks, in double quotes or escaped. The plan is refused:
error: generate schema apply operations: column tq.not cannot be made NOT NULL: its NULL rows take the default through ALTER TABLE ... UPDATE, and ClickHouse 25.8 to 26.10 refuse that statement for a column named not, however the name is quoted; rename the column firstOtherwise a column named not is created, changed, renamed, dropped and read
like any other column, measured on 24.10 and 26.10. A data write that names it
in a mutation is the server’s to refuse: 25.8 to 26.10 answer code 62 for an
ALTER TABLE ... UPDATE whose WHERE names it, and 24.10 to 26.10 for a
DELETE FROM whose WHERE does.
Dev-database cleanup
Section titled “Dev-database cleanup”Dev-database replay cleanup requires ClickHouse 24.11 or newer
and global SHOW DATABASES plus SHOW TABLES. Because ordinary views have no
complete catalog dependency metadata, cleanup also requires that other user
databases contain no view-like or dictionary objects and no Buffer,
Distributed, or Merge tables.
The narrower reset used by shadow verification, by the schema apply dev
rehearsal, and by schema clean removes tables, views, and materialized views.
A materialized view goes as one object, with DROP VIEW, so its inner storage
table leaves with it rather than being dropped out from under it. Live views and
window views are left alone, matching what the ClickHouse reader reports; use
the database-realm cleanup above when a database has to be emptied completely.
Tables and their engine clauses
Section titled “Tables and their engine clauses”A MergeTree table’s sorting key is carried through the read, so a table Ptah
creates reads back as itself: the primary-key flag comes from
system.columns.is_in_primary_key, and the renderer derives the ORDER BY a
MergeTree engine requires from it. Where a table declares both a narrower
PRIMARY KEY and a wider ORDER BY, the sorting key is carried separately, so
a description does not silently sort by fewer columns than the table it
describes. Before this the read dropped the key entirely: a declaration carrying
primary="true" differed from its own table on every comparison, so
ALTER TABLE ... MODIFY COLUMN was re-planned forever, and ptah db read
exited 2 against any ClickHouse database Ptah could create because the
description it produced could not be rendered (stokaro/ptah#1603).
A declaration states the key on the engine, as PRIMARY KEY or ORDER BY, and
the comparison reads the key columns from those clauses as the server does: the
PRIMARY KEY clause, or ORDER BY without one, and every column either names,
inside an expression too. A table identical to its SQL or YAML declaration
therefore compares as identical.
A declaration whose key moves a column into or out of the table’s primary key
is refused when the plan is made. ClickHouse fixes a MergeTree table’s primary
key when the table is created: MODIFY PRIMARY KEY is not a statement, and
MODIFY ORDER BY has to keep the primary key as a prefix of the sorting key.
The refusal names --allow-table-rebuild, which makes Ptah create the table
again and copy its rows; see Creating a table again.
Every other clause of the engine is carried with it, so a table read and
replayed is the table that was read rather than a MergeTree that happens to hold
the same columns. The engine is taken with its parameters — a
ReplacingMergeTree(ver) stays one, and does not fall back to the default
MergeTree, which would merge on nothing — and so are the PARTITION BY,
PRIMARY KEY, ORDER BY, SAMPLE BY, TTL and SETTINGS clauses. The TTL
is the one that changes what the data does rather than how fast it is read: a
table replayed without it keeps rows it was configured to delete.
A SQL schema file states the engine’s parameters in its ENGINE clause, as
SHOW CREATE TABLE prints them: ENGINE = ReplacingMergeTree(ver). An empty
list, ENGINE = MergeTree(), is the engine’s name alone, which is how the server
prints it back. A file that declares a projection, PROJECTION p (SELECT ...), is
refused by name: Ptah models no declared projection, so leave it out of the file.
A plan leaves the projections a table holds as they are.
A MySQL-family storage engine is refused rather than rendered. A table’s engine
reaches the renderer through the same key both families fill, so engine = "InnoDB" on a struct, and ENGINE=InnoDB in a SQL source, arrive
indistinguishable from a value written for ClickHouse. Rendering one produces
statements the server rejects with Code: 56 ... Unknown table engine, and
because the whole CREATE TABLE is lost the author gets no table at all rather
than a weaker one. Ptah names the engine instead. Declare a ClickHouse engine
with SQL’s ENGINE clause, YAML or HCL table platform properties, or
platform.clickhouse.engine in Go annotations. Removing the engine takes the
MergeTree default.
Only names that belong to the MySQL and MariaDB families are refused, and only
those they do not share with ClickHouse — Memory, Merge and S3 are real
ClickHouse engines and render as written. ClickHouse’s engine set grows with
every release, so nothing here decides whether a name is a ClickHouse engine:
an engine Ptah has never heard of renders unchanged.
Before adopting the round trip, know that both of these come from the server’s answer rather than from the declaration’s text:
- The settings are the server’s resolved values, not the ones a
CREATEnamed.system.tablesreportsindex_granularity = 8192for a table that never mentioned it, so a description carries that value and a replay pins it. It is the value the source table is actually running with. A declaration that leavesindex_granularityout does not manage it, so it does not differ from a table that carries it. - A clause keyword is a legal column name, and the two are told apart by
position. A table sorted by a column named
settingsorttlis read as what it is; the clause is only recognized where a clause can start.
Storage changes
Section titled “Storage changes”Ptah changes the storage clauses of an existing MergeTree table in place where
ClickHouse has an ALTER TABLE for the change, and refuses the others by name.
A refused change can be made by creating the table again, which Ptah plans only
when asked with --allow-table-rebuild; see
Creating a table again. Omitting a clause from the
declaration keeps the inspected one, and the plan needs a complete storage
observation of the table.
| Clause | Planned as | Rule |
|---|---|---|
ORDER BY |
MODIFY ORDER BY |
Drops expressions from the end, or adds expressions over columns the same ALTER TABLE adds. |
SAMPLE BY |
MODIFY SAMPLE BY, REMOVE SAMPLE BY |
The sampling key is one of the primary key’s expressions. |
TTL |
MODIFY TTL, REMOVE TTL |
An explicitly empty TTL removes the rules. |
SETTINGS |
MODIFY SETTING, RESET SETTING |
Settings ClickHouse fixes at creation are refused. |
ENGINE, PARTITION BY, PRIMARY KEY |
Refused, or created again | ClickHouse has no ALTER TABLE for them. |
ClickHouse keeps the parts already on disk sorted by the old sorting key. A new
key may therefore drop expressions from its end, and may add an expression only
over columns the same ALTER TABLE adds. Such a column cannot be Nullable or
have a DEFAULT, MATERIALIZED or ALIAS value. When the key gains an
expression, the plan adds every new column of the table in the statement that
changes the key:
ALTER TABLE `events` ADD COLUMN `region` String, MODIFY ORDER BY (id, region);The primary key stays a prefix of the sorting key. A table created without
PRIMARY KEY keeps its old sorting key as its primary key after the change,
which is what ClickHouse records and what a declaration that omits the primary
key asks for. A new key that reorders the old one, drops an expression that is
not last, or adds a column the table already has is refused by name, and can be
made by creating the table again. On an
engine that merges rows by its sorting key, such as ReplacingMergeTree,
dropping an expression lets rows that differed only in it merge into one, so the
plan marks that change destructive.
ClickHouse refuses a sampling key that is not one of the primary key’s
expressions, and allow_sampling_expression_not_in_primary_key is not a table
setting on the supported lines, so Ptah refuses such a key when the plan is
made.
Table settings compare as a set of name = value entries, so their order does
not count. A setting the declaration adds or changes is set with
MODIFY SETTING, and one it leaves out is reset with RESET SETTING.
ClickHouse fixes some settings when the table is created, among them
index_granularity, index_granularity_bytes,
enable_mixed_granularity_parts, table_disk and the
add_minmax_index_for_* family. A change to one of them is refused by name, and can be made by creating the table again. A
setting named twice in one SETTINGS clause is refused too, because the plan
cannot know which value the table runs with.
Each changed clause is one statement, outside a transaction. Settings the change sets come first, then the sorting key, the sampling key and TTL, and settings it resets come last. Column additions the new clauses need run before them, and removals of columns only the old clauses use run after them. A column the table’s storage still uses after the change cannot be removed or modified by the same plan. When a TTL rule moves to a new column, for example, the plan adds that column, changes TTL, then removes the old column.
The reverse migration restores the captured clauses in place. It cannot restore
rows or values TTL already expired or aggregated, undo TTL data movement or the
merges and moves done under changed settings, or separate rows a merging engine
combined while its key lacked a dropped expression. A reverse ClickHouse cannot
run in place is refused when the migration is generated. Dropping the last
sorting-key expression while its column stays has no reverse, because the
reverse would add a column the table already has to the key; ptah schema apply, which plans no reverse, plans that change.
Creating a table again
Section titled “Creating a table again”A change of the engine, of PARTITION BY or PRIMARY KEY, of a setting
ClickHouse fixes at creation, or of an ORDER BY that MODIFY ORDER BY cannot
make (a reordered key, or an expression over a column the table already has),
can only be made by creating the table again. A plain DROP TABLE followed by
CREATE TABLE would lose every row, so Ptah plans that change only when asked
on the one invocation, with --allow-table-rebuild on ptah schema apply,
schema plan, schema diff and migrations generate. Without it the plan is
refused, and the refusal names the flag. The flag reads no environment variable
and ptah.yaml has no key for it, so a shell profile or a CI job cannot leave it
on for every later plan.
With the flag, the plan creates the new table under another name,
ptah_rebuild_<table> in the table’s database, copies the rows into it, and swaps
the two with EXCHANGE TABLES. The table stays as it is until the swap:
SELECT throwIf((SELECT count() FROM system.databases WHERE name = currentDatabase() AND engine = 'Atomic') = 0, '...'), throwIf((SELECT count() FROM `events`) != (SELECT ifNull(sum(total_rows), 0) FROM system.tables WHERE database = currentDatabase() AND name = 'events'), '...') SETTINGS apply_deleted_mask = 0;SYSTEM START MERGES `ptah_rebuild_events`;CREATE TABLE `ptah_rebuild_events` (`id` UInt64, `name` String) ENGINE = ReplacingMergeTree ORDER BY (id) PRIMARY KEY (id) SETTINGS index_granularity = 8192;SELECT throwIf((SELECT arraySort(groupArray((name, compression_codec))) FROM system.columns WHERE ... table = 'ptah_rebuild_events' ...) != (... table = 'events' ...), '...'), throwIf((SELECT arraySort(groupArray((name, query))) FROM system.projections WHERE ... table = 'ptah_rebuild_events') != (... table = 'events'), '...');SYSTEM STOP MERGES `ptah_rebuild_events`;INSERT INTO `ptah_rebuild_events` (`id`, `name`) SELECT `id`, `name` FROM `events` SETTINGS max_partitions_per_insert_block = 0, optimize_on_insert = 0, insert_deduplicate = 0;WITH (SELECT count() FROM `ptah_rebuild_events`) AS copied, (SELECT count() FROM `events`) AS source SELECT throwIf(copied < source, '...'), throwIf(copied > source, '...');SYSTEM START MERGES `ptah_rebuild_events`;EXCHANGE TABLES `events` AND `ptah_rebuild_events`;DROP TABLE `ptah_rebuild_events` SYNC;The first statement fails, before anything is created, when the swap or the copy could not keep the rows:
- The table’s database is not
Atomic. Only anAtomicdatabase swaps two tables: anOrdinaryor aMemorydatabase answersEXCHANGE TABLESwith code 48. AReplicateddatabase is refused as well, because it runs each statement on every replica. - The user running the plan does not read every row the table stores. The copy reads
the table as that user, so a row policy that applies to the user, or a table filter
in the user’s settings, would leave rows out of the copy, and they would go with the
old table. The guard compares
count()withtotal_rowsinsystem.tables, which no policy filters.apply_deleted_mask = 0makescount()include the rows a lightweightDELETEhides, whichtotal_rowsstill counts. The copy leaves those rows out. - The table has projections, the new engine merges rows (
ReplacingMergeTreeand every otherMergeTreeengine butMergeTreeitself), and neither the declaredSETTINGSnor the server’s default setdeduplicate_merge_projection_modetodroporrebuild. ClickHouse refuses a projection on such a table otherwise.
The copy writes the rows as they are, through three settings of the INSERT:
optimize_on_insert = 0stops aReplacingMergeTreeorCollapsingMergeTreecopy from merging the rows of a block as it writes them;insert_deduplicate = 0stops a deduplication window from dropping a block;max_partitions_per_insert_block = 0lifts the limit of 100 partitions in one block.
When the new engine merges rows, or the new table has a TTL, a background merge
would remove rows from the copy before they are counted:
3,000,000 rows over 100,000 keys, written in blocks of 50,000 into a
ReplacingMergeTree copy, came down to between 100,000 and 278,147 rows, measured on
24.10 and 26.10. So the plan stops the merges of the copy with SYSTEM STOP MERGES
around the copy and the count, and starts them again before the swap. That needs
the SYSTEM MERGES privilege on the copy. The rows a declared TTL has expired are
then counted, and the merges of the new table remove them after the swap.
The SYSTEM START MERGES before CREATE TABLE checks that privilege while the copy
does not exist yet. The server checks the privilege before it looks for the table,
and starting the merges of a table that does not exist does nothing, so a user
without it is refused with code 497, which names the privilege, before anything is
created. Neither 24.10 nor 26.10 has a function that reads a privilege, and 24.10 has
no CHECK GRANT for SYSTEM MERGES. A copy whose merges remove no row has neither
statement and needs no such privilege.
The statement after the copy fails when the copy holds fewer rows than the table: a
row was written to the table while it was copied, or a limit in the user’s settings
cut the copy short. It fails when the copy holds more rows, too, since rows deleted
from the table during the copy would come back; the table’s own merges can remove
rows when its engine merges rows or it has a TTL, so that half is left out for
such a table. Either way the table is as it was.
The new table keeps what no declaration can state, and Ptah reads from the table:
the codec of each column it keeps, every projection, and every ASSUME constraint.
They are added to the new table before the rows, and a check that the new table
reports the same codecs and projections as the table stops the plan before the copy
otherwise. The plan names them in a comment.
The new table holds the declared CHECK constraints, and the copy checks every row
against them. A row that breaks one stops the plan before the swap with code 469,
and the table is as it was: a constraint ALTER TABLE ... ADD CONSTRAINT added later
than the row leaves the row in place, and a rebuild does not. Drop
ptah_rebuild_<table>, fix or remove the row, and run the plan again.
A codec fits the type it was chosen for, so the codec of a column whose type changes
is left behind, and the plan names it beside the declared changes, as in
column x: codec Delta(8), ZSTD(1) -> none, the type changes. Carried onto a
String column, the codec of a UInt64 one is a codec CREATE TABLE refuses with
code 36, measured on 26.10.
What the declaration states follows the declaration, as it does
on the ALTER TABLE path: a table or column comment the declaration leaves out is
not on the new table, and the plan names each comment and index that changes. An
unnamed CHECK keeps the name it has on the table. A rebuild that would lose
something is refused before anything is created:
- a column with a column
TTL,STATISTICSorSETTINGS, which Ptah does not carry; - a projection that uses a column the declaration drops;
- an
ASSUMEconstraint that uses a column the declaration drops.
The columns follow the declaration:
- A column the declaration adds takes its default. A column it drops is not copied, and its data is gone from the rebuilt table. A rename without a rename hint is a drop and an add, so the column that takes the new name starts with its default; the plan names the dropped columns in a comment.
- A column whose type or nullability changes is copied through
accurateCast. It fails on a number the new type cannot hold (300intoUInt8,1.5into an integer), on aNULLinto a column that no longer allows it, on a string that does not parse as the new type, and on a string too long for aFixedString. A plainINSERT ... SELECTwould wrap the number around and turn theNULLinto zero;ALTER TABLE ... MODIFY COLUMNwraps the number around too. A failure there leaves the table as it was. The rest converts asMODIFY COLUMNconverts it, without an error: aDecimalloses the digits past its new scale, aDateTimeloses its time of day as aDate, and a date string out of range, such as'2024-13-45', becomes1970-01-01. - Computed columns (
MATERIALIZED,ALIAS,EPHEMERAL) are not copied. - The declared skipping indexes are created on the new table before the rows are written, so the rows are indexed. A row policy and a grant name the table, so they hold for the new table after the swap, and none is written.
- A
PRIMARY KEYthe declaration omits follows the newORDER BYwhen the table’s primary key was its sorting key. A declaredPRIMARY KEYthat is not a prefix of the newORDER BYis refused.
The steps are not atomic. A row written to the table between the count and the swap
is lost. The plan says so in a comment and marks the plan destructive. migrations lint reports the
last DROP TABLE as destructive/drop-table, since after the swap it drops the old
table and its rows, and the report is meant to stand. Stop writers before applying
it.
A rebuild can stop part way, for a reason the plan cannot know. Whichever statement it stopped at, the table holds every row the rebuild read under its own name:
- Before the swap, the table is as it was, and
ptah_rebuild_<table>holds part of the copy or all of it. - After the swap, the table is the new one and holds every row of the copy, and
ptah_rebuild_<table>is the old table. Only the lastDROP TABLEis left, and the server refuses it while something depends on the old table, such as a dictionary that loads from that name.
So drop ptah_rebuild_<table> and run the plan again. While it exists, a plan that
rebuilds the table is refused and says so. A plan with nothing left to rebuild drops
it like any other table the declaration does not hold. The server refuses to create
the new table over one the plan does not see, such as a table an exclude selector
leaves out, so nothing is overwritten.
Everything that finds the table by name follows the swap. A materialized view that
reads the table is not fed the copy and fires for the new table after the swap. One
that writes to the table (TO) writes to the new table, a Buffer table flushes
into it, and a dictionary loads from it. A view, a Merge table and a remote()
query read it. None of them stops the rebuild, and none is written. Measured on
24.10 and 26.10. A Merge table whose pattern also matches ptah_rebuild_<table>
reads both tables while the copy exists.
Ptah rebuilds only a table whose engine, as it is and as declared, keeps the rows on
this server: a MergeTree engine that is not replicated or shared, Memory, Log,
StripeLog, and TinyLog as the new engine. A TinyLog table is refused by name
when the plan is made: it reports no total_rows, so nothing would prove that the
copy holds every row. Any other engine is refused whatever the request says,
because the copy would read the rows from elsewhere (Kafka, Distributed), write
them elsewhere (MySQL, URL) or drop them (Null).
A Replicated*MergeTree or Shared*MergeTree engine, as it is or as declared, is
refused by name, whatever the request says. The new table is created on this server
only, the copy reads one replica that may lag, and a new table at a fixed Keeper
path meets the metadata the other replicas keep at that path. ON CLUSTER is not
planned. Create such a table again by hand, on every replica. A table whose name
contains a dot is refused earlier, by the feature planning (feature table name disagrees with its captured identity), whatever the request.
ptah migrations generate --allow-table-rebuild writes the down direction the same
way: the reverse of a rebuild is a rebuild back to the previous definition.
On ptah-compat, the same change is asked for with a diff "clickhouse" block in
atlas.hcl, or with PTAH_ALLOW_TABLE_REBUILD=1. The block may sit at the top level
or in an env, and an env’s block merges over the top-level one:
diff "clickhouse" { allow_recreate = true}The block is the Atlas spelling and Ptah reads it per dialect: allow_recreate under
the label of a dialect that has no table rebuild is refused. The
project configuration page says how the env block, the
top-level block and the variable combine. Atlas Community Edition has no ClickHouse
driver and plans no rebuild. The strict policy (PTAH_ATLAS_STRICT_COMPAT=1) therefore
refuses the block as an ignored construct, and refuses the variable.
The dev-database rehearsal of ptah-compat lets the guards read system.databases
and system.tables, since a SELECT changes no database, and lets the plan stop and
start the merges of one table in the dev database, the only SYSTEM statements a
replay accepts.
CHECK constraints
Section titled “CHECK constraints”ClickHouse checks each row an INSERT writes against the CHECK constraints of the
table, and refuses a row that breaks one with code 469. Ptah creates the CHECK
constraints a schema declares: the check of a column, the checks list of a table,
and a table constraint. On a table that exists, a change is planned as
ALTER TABLE ... DROP CONSTRAINT and ALTER TABLE ... ADD CONSTRAINT.
ClickHouse refuses a CHECK without a name, so Ptah names each table CHECK that
the schema leaves unnamed. On a table that exists, an unnamed CHECK takes the name
of the CHECK the table holds with the same condition, so a reordered checks list,
or a named CHECK added beside the unnamed ones, renames none of them. Each one
left is <table>_check, then <table>_check1 and on, past the names already taken.
The unnamed CHECK of a column is <table>_<column>_check. A render, a plan and a
comparison give the same name, so the next plan finds the constraint that the apply
created:
//ptah:schema:table name="t"//ptah:schema:constraint type="CHECK" table="t" check="v > 0"type T struct { //ptah:schema:field name="id" type="UInt64" primary="true" ID uint64 //ptah:schema:field name="v" type="Int32" not_null="true" V int32}CREATE TABLE `t` ( `id` UInt64, `v` Int32, CONSTRAINT `t_check` CHECK (v > 0)) ENGINE = MergeTree ORDER BY (`id`);A SQL schema file may write a table CHECK condition with or without parentheses
around it, as SHOW CREATE TABLE prints it on 24.10 and 26.11:
CONSTRAINT c CHECK v > 0 is the condition of CONSTRAINT c CHECK (v > 0), and a
condition written without them runs to the end of its table element.
The server keeps the constraints of a table only in its CREATE TABLE statement, so
Ptah reads them from system.tables.create_table_query. The server writes the
condition its own way, and each release line in its own. Measured on 24.10 and
26.10, both write CAST(v AS Int64) > 0 and v::Int64 > 0 as
CAST(v, 'Int64') > 0, and 24.10 writes equals(v, v) as v = v. So against a
connected server, Ptah asks the server to format the declared condition and the one
it holds with formatQuerySingleLineOrNull, and a CHECK whose two conditions
format alike is unchanged. A declared condition the server cannot parse formats to
NULL and is another CHECK, which the server then refuses with its own message. The server keeps the case of a name, and a CHECK over a column
V is another CHECK from one over v.
A comparison with no server, such as one of two schema files, compares the text, by
the grouping the operators’ precedence gives: there v > 0 AND v <> 5 and
(v > 0) AND (v != 5) are one condition, and CAST(v AS Int64) > 0 and
CAST(v, 'Int64') > 0 are two. A server without formatQuerySingleLineOrNull is
compared the same way, and the run warns, before the plan, that each CHECK it
pairs is compared as written.
A CHECK the table holds and no schema declares is dropped, as any object the
schema leaves out is. --exclude t.hand leaves the CHECK named hand on table t
out of the plan.
ALTER TABLE ... ADD CONSTRAINT checks only the rows written after it, not the rows
the table holds, measured on 24.10 and 26.10. So the plan counts the rows the table
holds that the CHECK refuses, once ahead of the ADD and again after it, and says
so in a comment above the ADD:
SELECT throwIf(count() > 0, 't_check is broken by rows t holds') FROM `t` WHERE NOT ifNull((v > 1), 0);-- CLICKHOUSE: ADD CONSTRAINT t_check checks only the rows written after it; a SELECT ahead of it and one after it scan t for held rows the CHECK refusesALTER TABLE `t` ADD CONSTRAINT `t_check` CHECK (v > 1);SELECT throwIf(count() > 0, 't_check is broken by rows t holds') FROM `t` WHERE NOT ifNull((v > 1), 0);A row the condition answers NULL for is counted, since an INSERT of it is refused
with code 469 too. A held row the CHECK refuses stops the apply with code 395 and a
message that names the constraint. The count ahead of the ADD stops the apply while
the constraint is absent, so a retried apply plans the ADD again and stops again
until the rows are deleted or corrected. The count after the ADD finds a row
written between the two counts. It stops the apply with the constraint on the table,
since ClickHouse has no transaction to undo the ADD, and the next plan finds the
constraint and plans nothing, so delete or correct that row, or drop the constraint.
A row written after the ADD is the constraint’s to refuse.
A changed CHECK is dropped and added again. When the plan adds no column and
changes no column definition, the first count runs ahead of the DROP CONSTRAINT.
Removing a column or changing its comment keeps this order: neither changes the
values the new condition reads. A held row the new condition refuses stops the apply
with the old CHECK still on the table, refusing the rows written after it:
SELECT throwIf(count() > 0, 't_check is broken by rows t holds') FROM `t` WHERE NOT ifNull((v > 5), 0);ALTER TABLE `t` DROP CONSTRAINT `t_check`;-- CLICKHOUSE: ADD CONSTRAINT t_check checks only the rows written after it; a SELECT ahead of it and one after it scan t for held rows the CHECK refusesALTER TABLE `t` ADD CONSTRAINT `t_check` CHECK (v > 5);SELECT throwIf(count() > 0, 't_check is broken by rows t holds') FROM `t` WHERE NOT ifNull((v > 5), 0);When the plan adds a column or changes a column’s type, nullability, default or
generated expression, the new condition may need the resulting values. The first
count then waits until the columns have changed and runs right ahead of the ADD.
The old CHECK is dropped before those column changes, so a held row the new
condition refuses then leaves the table with neither condition until the rows are
corrected.
The counts read the whole table twice for each CHECK the plan adds, so on a large
table they cost what two of those SELECT statements cost. To find the rows before
you apply, run the same filter:
SELECT count() FROM t WHERE NOT ifNull((v > 1), 0)WHERE NOT (v > 1) misses a row the condition answers NULL for, because NOT of
NULL is NULL.
To plan without the counts, pass --skip-check-scan, or set PTAH_SKIP_CHECK_SCAN=1,
which the flag reads and which is the only way to ask on ptah-compat. The plan then
reads no rows, a comment above each ADD says that the rows the table holds are not
checked, and the run warns once before the plan:
-- CLICKHOUSE: ADD CONSTRAINT t_check checks only the rows written after it, and the plan has no scan: the rows t already holds are not checkedALTER TABLE `t` ADD CONSTRAINT `t_check` CHECK (v > 1);On a table the plan keeps, a held row the CHECK refuses then stays, and the
constraint refuses only the rows written after it. A table rebuild still copies
rows into a new table whose CREATE TABLE carries the CHECK, so the copy refuses
such a row even with the scans skipped.
ptah migrations generate --skip-check-scan leaves the scans out of both generated
up and down files. The warning appears during generation; applying those files
does not repeat it or add a scan. The strict compatibility profile,
PTAH_ATLAS_STRICT_COMPAT=1, refuses PTAH_SKIP_CHECK_SCAN.
The server refuses to drop a column that a CHECK reads, and to add a CHECK over
a column the table does not have, both with code 47. A plan therefore drops CHECK
constraints before its column changes and adds them after. ADD COLUMN has no
CHECK, so a column added with a check takes its constraint from an
ADD CONSTRAINT of its own.
ClickHouse also has ASSUME, a constraint the query optimizer reads and no row is
checked against. No schema source declares one. Ptah reads it, and a table rebuild
carries it onto the new table; see Creating a table again.
Data-skipping indexes
Section titled “Data-skipping indexes”A data-skipping index declares its type and granularity as ClickHouse settings
of the index. SQL uses TYPE and GRANULARITY; YAML and HCL use the index’s
platform group for clickhouse. Go annotations use
platform.clickhouse.type and platform.clickhouse.granularity.
On ClickHouse the common type attribute names the
skipping-index type too, and declaring the type both ways is refused. The type
keeps its parameters, such as set(100) or bloom_filter(0.01).
Add the index to the events declaration above. SQL, YAML, HCL, and Go declare
bloom_filter(0.01) with granularity 64. The DBML variant uses the creation
defaults because DBML cannot set granularity:
Place the index inside the CREATE TABLE column list:
INDEX idx_e_payload payload TYPE bloom_filter(0.01) GRANULARITY 64Add this top-level indexes entry:
indexes: idx_e_payload: table: events fields: [payload] type: bloom_filter(0.01) platform: clickhouse: granularity: 64Add this block inside table "events":
index "idx_e_payload" { columns = [column.payload] type = "bloom_filter(0.01)" platform "clickhouse" { override "granularity" { value = "64" } }}Add this block inside Table events. It creates a minmax index with
granularity 1:
Indexes { payload [name: 'idx_e_payload']}Place the annotation on the Payload field, beside its field annotation:
//ptah:schema:index name="idx_e_payload" fields="payload" type="bloom_filter(0.01)" platform.clickhouse.granularity="64"DBML cannot declare the granularity in this example. Use SQL, YAML, HCL, or Go annotations to manage both skipping-index settings.
A new index that declares neither setting is a minmax index with
GRANULARITY 1. Index granularity counts table granules per index block; it is
separate from the table’s index_granularity setting, which controls rows per
granule. In Go annotations, YAML and HCL, a setting left out of the declaration
of an existing index keeps the value the server reports. A .state suffix with
the value default, such as platform.clickhouse.granularity.state="default",
asks for the creation default instead. A SQL source is read as ClickHouse reads
it: an INDEX ... TYPE ... clause without GRANULARITY means one granule, so
comparing it with an index that has another granularity plans a change.
ClickHouse changes neither setting in place. A changed type or granularity is
planned as ALTER TABLE ... DROP INDEX, then ADD INDEX with the declared key
expression and settings. A key with several parts is written as a tuple,
including one the server reports as a bare list, a, b, for INDEX i (a, b).
The pair runs around a change to a column either expression reads. When the
plan already rebuilds the index for another reason, that rebuild carries the new
settings and no second pair is planned. ADD INDEX indexes data written
afterwards; existing parts have no index data until a separate
MATERIALIZE INDEX runs. The reverse migration restores the previous key and
settings the same way and reports that it cannot restore materialized index
data.
A declared key that names a column the table does not declare, such as a
misspelled field, is refused before anything runs, for a new index and for a
changed one: ClickHouse refuses the ADD INDEX, and a changed index is gone
before the new one is added. A settings change is refused the same way when the
plan also removes a column the declared key reads. Only a name that can be
nothing but a column is checked: a bare key part, or a bare argument of a call,
such as payload in lower(payload).
The comparison matches skipping indexes by name, and compares the key
expression as well as the settings. A changed key is planned the same way, as
DROP INDEX then ADD INDEX. ClickHouse stores a key in its own formatting:
b * 2 + 1 reads back as (b * 2) + 1, LOWER(a) as lower(a), and
tuple(a, b) as a, b. So spacing, case outside string literals, and
parentheses that only group are not read as a change; a change that only
regroups an expression or only changes the case of a name plans nothing.
Database inspection reads the type with its parameters, from the type_full
column, and the granularity from system.data_skipping_indices. A server whose
catalog has no type_full column is refused with a message that names the
column; every release line Ptah tests has it. HCL and Go output write the
settings as ClickHouse platform properties. A ClickHouse ADD INDEX or
DROP INDEX operation sent to another target is refused. See the
ClickHouse skipping-index reference.
A secondary index declaring a PostgreSQL or MySQL access method is refused the
same way as a MySQL engine, and for the same reason: an index’s type reaches
ClickHouse through the field those families fill, so USING GIN in a SQL source
arrives here looking like a data-skipping type. Rendering it produces an
ALTER TABLE the server rejects with Code: 80 ... Unknown Index type, and the
index is not added. The ClickHouse owner refuses the type wherever it reads the
settings, so comparison and planning refuse it too, before a settings change
could drop the old index. Ptah names the type and points at the fix: declare a
ClickHouse data-skipping type such as minmax, or drop the type to take the
minmax default. As with the engine, the refusal reads the closed PostgreSQL
and MySQL sets rather than deciding what a ClickHouse type is, so a type from a
future release renders unchanged.
Column changes
Section titled “Column changes”A changed column is planned as one ALTER TABLE ... MODIFY COLUMN that states
the column’s type and, when the column declares one, its default. The default
is in the statement because a MODIFY COLUMN that names only a type keeps the
default the column already had.
A comment is planned as a statement of its own, because MODIFY COLUMN keeps
the comment the column holds: ALTER TABLE ... COMMENT COLUMN for a column and
ALTER TABLE ... MODIFY COMMENT for the table. A column whose comment is the
only change takes no MODIFY COLUMN, and an empty comment clears the one the
server holds.
A column’s type is compared as the server stores it, width included. A live
Int32 declared Int64, UInt8 declared UInt16, Float32 declared
Float64, Decimal(9, 2) declared Decimal(18, 2) and DateTime declared
DateTime64(3) are each planned as a MODIFY COLUMN, and so is a change inside
Nullable(...), LowCardinality(...), Array(...) or Map(...). A spelling
the server stores under another name is the same type: Decimal32(2) is
Decimal(9, 2), Boolean is Bool, SMALLINT UNSIGNED is UInt16, and
Enum('a', 'b') is Enum8('a' = 1, 'b' = 2).
A portable type name is compared as the type Ptah writes for it, which is not
always the type ClickHouse makes from the same word. A declared DATETIME is
written as DateTime64(3), so a live DateTime column declared DATETIME is
planned as a change. A ClickHouse type name, spelled the way ClickHouse spells
it, is written as it stands: Int8 is an 8-bit column and DateTime a
second-precision one, while the portable INT8 is Int64.
The safety report rates a live DateTime declared timestamp as a warning:
the plan adds temporal precision.
A narrowing is planned as well. Measured on 24.10 and 26.9, the server accepts
MODIFY COLUMN d Int32 over an Int64 column and stores a value that does not
fit wrapped: 30000000000 becomes -64771072. A decimal narrowing whose values
do not fit fails the conversion and leaves the column unreadable. A lower temporal
type is accepted too: DateTime64(6) under DateTime64(3) loses three digits, and
DateTime under Date loses the time of day. Float64 under Float32 loses digits, and
Int64 under Float64 loses the low digits of a large value, without a word. The plan’s
safety report marks an integer narrowing between ClickHouse type names, a float, decimal
or FixedString narrowing, a lost Enum member and a temporal narrowing as destructive;
check the values before applying any of them.
A lower scale, a Decimal under an integer, and a lower DateTime64 or Time64
precision cut each value: 1234.567 under Decimal(8, 1) reads 1234.5 and under
Int32 reads 1234. While a row holds a value the change would alter,
ptah schema plan, ptah schema apply, ptah migrations plan and
ptah migrations generate refuse the change, and a generated migration file reads the
rows again where it runs; see
A change that rounds stored values.
A type that already admits NULL, such as LowCardinality(Nullable(String)), is
not wrapped in a second Nullable, which ClickHouse refuses. A Nullable inside
an array, a map or a tuple makes the elements nullable and not the column, so
Array(Nullable(Int32)) is a column that is never NULL itself.
An expression default is compared as the operations its operators group, by ClickHouse’s precedence. The server stores a default with every operation it groups in parentheses. Each pair below is one default, so a second apply plans nothing:
| Declared | Stored by ClickHouse 26.10 |
|---|---|
1 + 2 * 3 |
1 + (2 * 3) |
a - b - c |
(a - b) - c |
a + 1 IS NOT NULL AND NOT b = 1 |
((a + 1) IS NOT NULL) AND (NOT (b = 1)) |
a <> 1 |
a != 1 |
1.50 * a |
1.5 * a |
a IN 1 OR s NOT LIKE 'x%' |
(a IN (1)) OR (s NOT LIKE 'x%') |
A parenthesis that changes the grouping is part of the default: (1 + 2) * 3
and 1 + 2 * 3 differ.
Some expressions are compared as written and may plan again. ClickHouse
rewrites || as concat(), so an expression that holds ||, ILIKE,
GLOBAL IN, a cast, a lambda, an array or a qualified name is not read.
Neither is NOT (a) followed by a tighter operator, which ClickHouse 24.10 and
26.10 group differently.
ClickHouse has no shift operator, so a default that holds << or >> is
refused when the file is read; bitShiftLeft(a, b) and bitShiftRight(a, b)
are the functions. DEFAULT NOT NULL is the default NOT NULL, which is NULL,
on a nullable column.
A default the declaration takes away is removed with its own statement, written before the one that states the type:
ALTER TABLE `asn` MODIFY COLUMN `n` REMOVE DEFAULT;ALTER TABLE `asn` MODIFY COLUMN `n` Int32;REMOVE DEFAULT comes first. A type the old default cannot take is refused
while the default is still there. In a single ALTER, ClickHouse 24.10 keeps
the default and reports no error. A down migration that takes a default away is
planned the same way.
Making a nullable column NOT NULL needs a default for the rows that hold
NULL. The server lines handle those rows differently. ClickHouse 26.3 and later
refuse MODIFY COLUMN n Int32 without a DEFAULT, even on an empty table, and
fill every NULL row from the DEFAULT when there is one. ClickHouse 24.10 and
25.8 accept the statement with or without a DEFAULT, change the column’s
type, and then fail on a row that holds NULL, which leaves the table
unreadable.
So a column that declares a default has its NULL rows filled first, on every line, by an update that waits for its mutation:
ALTER TABLE `asn` UPDATE `n` = '7' WHERE `n` IS NULL SETTINGS mutations_sync = 2;ALTER TABLE `asn` MODIFY COLUMN `n` Int32 DEFAULT '7';A column that declares no default is refused when the plan is made, on every
line. Ptah does not invent a value such as 0 for the NULL rows. Give the
column a default, which the NULL rows take.
The same rule applies to a down migration. ptah migrations generate refuses
to make a NOT NULL column without a default nullable, because the down
migration would have to make it NOT NULL again. To make such a column
nullable, give it a default in one migration, then make it nullable in the
next.
A nullable MATERIALIZED column made NOT NULL is dropped and added back as
declared:
ALTER TABLE `asn` DROP COLUMN `x`;ALTER TABLE `asn` ADD COLUMN `x` Int32 MATERIALIZED id + 1;On 26.3 and later, MODIFY COLUMN fails the conversion for such a column and
leaves it unreadable. The column holds only what its expression computes, so
dropping it loses nothing, and the server computes the values again for the
existing rows. An expression that can yield NULL, such as s + 1 over a
nullable s, cannot back a non-nullable column on any line: reading a row
where it yields NULL fails. An ALIAS column stores nothing, and
MODIFY COLUMN changes its type on every line.
Computed columns
Section titled “Computed columns”A ClickHouse column takes its value from one of DEFAULT, MATERIALIZED,
ALIAS and EPHEMERAL. A MATERIALIZED column is computed and stored when a
row is inserted. An ALIAS column is computed when it is read and stores
nothing. An EPHEMERAL column stores nothing either: an insert may name it, and
the expressions of the other columns read it.
CREATE TABLE events ( id UInt64, price Int64, qty Int64, total Int64 MATERIALIZED price * qty, doubled Int64 ALIAS total * 2, raw String EPHEMERAL, tag String DEFAULT upper(raw)) ENGINE = MergeTree ORDER BY id;Go annotations and YAML declare the kind with generated and
generated_kind, such as generated="price * qty" generated_kind="MATERIALIZED".
STORED is read as MATERIALIZED, VIRTUAL as ALIAS, and an expression
without a kind as MATERIALIZED. generated_kind="EPHEMERAL" stands without
generated, as the bare keyword does in SQL; any other kind without an
expression is refused. Ptah writes an EPHEMERAL column without an expression
as EPHEMERAL defaultValueOfTypeName('String'), which ClickHouse 24.10 and
26.10 read the same as a bare EPHEMERAL: a column created with the bare
keyword refuses any other kind later, with
Syntax error (after altering table).
These kinds are Ptah’s own. The community Atlas binary has no ClickHouse
driver and refuses a clickhouse:// URL with unknown driver "clickhouse", so
ptah-compat offers them as a native capability, not as a matched Atlas
contract.
The expression is compared as the operations its operators group, the way a
default is, so price * qty + 1 matches the stored (price * qty) + 1. A
changed kind or expression is one MODIFY COLUMN. A column made ordinary loses
its kind first, because a MODIFY COLUMN that names only a type keeps it:
| Change | Statements |
|---|---|
| Another kind or expression | MODIFY COLUMN `total` Int64 ALIAS price * qty |
MATERIALIZED or ALIAS to ordinary |
MODIFY COLUMN `total` REMOVE MATERIALIZED, then MODIFY COLUMN `total` Int64 |
EPHEMERAL to ordinary |
MODIFY COLUMN `raw` String DEFAULT defaultValueOfTypeName('String'), MODIFY COLUMN `raw` REMOVE DEFAULT, then MODIFY COLUMN `raw` String |
EPHEMERAL has no REMOVE, and REMOVE DEFAULT refuses an EPHEMERAL
column, so the column becomes a DEFAULT one first. A column another
column’s expression reads stays readable throughout.
ClickHouse does not compute the rows already stored again. A MATERIALIZED
column whose expression changes, or which becomes ordinary, keeps the values it
stored. An ALIAS or EPHEMERAL column made ordinary reads its type’s default
for those rows, such as 0, and an EPHEMERAL column made MATERIALIZED
computes its expression for them.
Views and materialized views
Section titled “Views and materialized views”Plain views participate in the complete render, plan, and introspection cycle.
Ptah emits CREATE VIEW, CREATE OR REPLACE VIEW, and DROP VIEW, preserving
qualified names and query bodies, and reads ordinary views from
system.tables. An empty query body, WITH CHECK OPTION, or
DROP VIEW ... CASCADE fails instead of being ignored.
A read of one database reports its views and materialized views without that
database’s name, as it does for tables. References to that database inside a view
query become local references too. For example, a view read from app with
SELECT app.id FROM app.events AS app is described as
SELECT app.id FROM events AS app: the alias stays, and the source follows the
database where the SQL runs. References to another database, string literals and
comments keep their text.
This scope applies to schema diff and to migration files, including the down
files that restore a view. A diff between database URLs changes the database
selected by --from when its SQL is applied there. A migration generated from
one database can run on another with the same starting schema; explicit references
to a foreign database still require that database. A declaration that explicitly
names the connection’s current database matches its local catalog query when
the remaining SQL tokens agree.
A database-qualified column expression such as app.events.id can mean
something different after removing app: ClickHouse may read events.id as a
tuple field instead of a table column. Ptah refuses any expression with three or
more parts that starts with the current database name, even when an explicit
alias has that name. The diagnostic names the view and asks for a table alias
different from the database name. For example, write
SELECT e.id FROM app.events AS e, or SELECT e.payload.id FROM app.events AS e
for a tuple field. The same refusal covers scalar aliases with that name in
multipart expressions. Two-part column and tuple expressions keep their meanings.
Add these declarations to the selected schema source from the table example:
CREATE VIEW event_count AS SELECT count() AS c FROM events;CREATE MATERIALIZED VIEW event_statsENGINE = MergeTree ORDER BY tuple() AS SELECT count() AS c FROM events;views: event_count: body: SELECT count() AS c FROM eventsmatviews: event_stats: body: SELECT count() AS c FROM eventsview "event_count" { as = "SELECT count() AS c FROM events"}materialized "event_stats" { as = "SELECT count() AS c FROM events"}//ptah:schema:view name="event_count" body="SELECT count() AS c FROM events"type EventCount struct{}
//ptah:schema:matview name="event_stats" body="SELECT count() AS c FROM events"type EventStats struct{}DBML has no view or materialized-view declaration. Use another format for these objects.
Materialized views do too. Ptah emits
CREATE MATERIALIZED VIEW <name> ENGINE = MergeTree ORDER BY tuple() AS <query>,
reads the object back from system.tables, and plans a changed query as a drop
followed by a create. Several ClickHouse-specific points are worth knowing
before adopting them:
-
A materialized view maintains itself from inserts into its source. Ptah declares no refresh strategy and emits no refresh: a declaration that carries
refresh_strategyis refused when it is parsed, on every dialect. -
ClickHouse’s own scheduled materialized views are managed. A declaration carries the schedule as ClickHouse spells it, and Ptah renders it, reads it back, and reconciles it:
SQL, Go annotations, YAML, and HCL can declare a refresh schedule. For example:
CREATE MATERIALIZED VIEW event_stats REFRESH EVERY 1 HOURENGINE = MergeTree ORDER BY tuple() AS SELECT count() AS c FROM events;Go annotations:
//ptah:schema:matview name="event_stats" body="SELECT count() AS c FROM events" refresh="every 1 hour"type EventStats struct{}YAML uses the same clause in a
matviewsentry:matviews:event_stats:body: SELECT count() AS c FROM eventsrefresh: EVERY 1 HOURHCL uses a string on a
materializedblock:materialized "event_stats" {as = "SELECT count() AS c FROM events"refresh = "EVERY 1 HOUR"}The server rewrites what it stores —
EVERY 60 MINUTEbecomesEVERY 1 HOUR,AFTER 90 SECONDbecomesAFTER 1 MINUTE 30 SECOND— so a declaration is normalized to the stored spelling before anything compares it. Any spelling of the same schedule therefore converges instead of re-planning forever.A changed schedule is applied with
ALTER TABLE <view> MODIFY REFRESH, which keeps the rows the view accumulated. A view gaining its first schedule or losing its last is a drop and a create instead, because the server refuses that transition in place:Alter of type 'MODIFY_REFRESH' is not supported by storage MaterializedView. Adding or removingAPPENDis a drop and a create for the same reason: 24.10 answersAdding or removing APPEND is not supportedand 26.9 answersChanging APPEND or INCREMENTAL is not supported. That drop empties the view, and the plan reports it as destructive.OFFSET,RANDOMIZE FOR,DEPENDS ONandAPPENDare carried too, each at most once and in that order, as the server takes them.OFFSETbelongs toEVERYalone, and an interval mixing calendar units with clock ones is refused where it is declared, both matching the server. 24.10 also refusesDEPENDS ONwithAFTER. A refreshSETTINGSlist is not modeled: a declaration cannot state one, and a view the server stores with one has a schedule Ptah could not read. A view created elsewhere withTO <table>has its schedule read up to the target table.The schedule is a ClickHouse setting of the view, not part of the shared materialized view. A SQL file states it between the view name and
AS, as shown above.The storage clause may be left out. When it is written, it has to be
ENGINE = MergeTree ORDER BY tuple(), the storage Ptah creates every view with. Another storage is refused, because Ptah does not model it and would create the view without it. All four sources state every view’s schedule. Omittingrefresh, or writing an empty string in Go, YAML, or HCL, declares a plain view. Removing an existing schedule replaces the view and discards its stored rows. HCL export preserves a supported schedule.A schedule Ptah could not read is never read as no schedule. A source that declares one, or that declares the view plain, leaves the view undecided; a change to the view’s query from any source is refused, because the replacement would recreate the view without the schedule;
ptah db readand other renders of the database write the view with a comment saying its schedule was not captured; and exporting the database to Go annotations or HCL is refused, because the export would declare the view plain. An account that may not readsystem.view_refreshesreads the database all the same, with every view’s schedule uninspected: a source that declares a schedule is then undecided, and one that declares plain views plans nothing for them.Other targets do not carry the schedule. A PostgreSQL or Oracle view rendered from the same declaration has none, and
ptah schema validate --no-skippeddoes not report it, because the declaration was made for ClickHouse alone. -
The storage clause is written explicitly rather than left to the server. ClickHouse 25.x and later accept a materialized view with no storage clause and supply
MergeTree ORDER BY tuple()themselves; 24.x rejects it withORDER BY or PRIMARY KEY clause is missing. -
Ptah generates
DROP VIEW.DROP MATERIALIZED VIEWis a syntax error on ClickHouse. A SQL schema file may also useDROP TABLEto remove a view or materialized view. Either form removes its inner storage table. -
Tables, views and materialized views share one namespace, and ClickHouse refuses to create one while another holds its name:
Table <database>.<name> already exists(code 57). When a declaration gives the name of a relation to one of another kind, the plan drops the old relation before it creates the new one. A view or materialized view is dropped ahead of theCREATE TABLE, after its row policies, which ClickHouse would otherwise apply to the new table. A table is dropped ahead of the view, after the plan’s other changes to it, and its rows go with it. In both directions the grants the plan removes on the old relation are revoked directly ahead of its drop, since a grant is bound to the name as well and would otherwise apply to the new relation until theREVOKE. -
POPULATEis never emitted, so a materialized view starts empty and fills from inserts into its source rather than from the rows already there.POPULATEis a one-shot argument that leaves no trace in the catalog, so nothing Ptah reads back could diff it. Backfill existing rows yourself if you need them. -
A query written without a database qualifier is read back carrying one. ClickHouse resolves the query when the view is created and records what it resolved, so
SELECT count() AS c FROM userscomes back fromsystem.tables.as_selectasSELECT count() AS c FROM <database>.users. Comparison removes the qualifier the object’s own database added, the same way it does for an ordinary view, so an unchanged declaration is not reported as drift and is never planned as a drop and a create. A qualifier naming some other database is a real difference and is still reported. -
A changed query is applied destructively. The drop takes the inner storage table and every row the view had accumulated, and the replacement omits
POPULATE, so the view starts empty again and refills only from new inserts. ClickHouse does haveALTER TABLE <view> MODIFY QUERY, which keeps the stored rows, but it refuses any query whose output columns differ from the ones the storage table already has, and a Ptah declaration carries a query body with no column list to compare, so the planner cannot tell the two cases apart before the statement runs. Treat a materialized-view body change as a change that empties the view.
The TO <target table> form is not emitted: the shared schema model carries a
name and a query, so it cannot name a separate target table.
Ptah models no storage for a materialized view but the
ENGINE = MergeTree ORDER BY tuple() it creates every view with. A view the
server stores any other way is read with its storage marked as not described:
another engine, a sorting key, a PARTITION BY, SAMPLE BY or TTL clause, a
setting other than the index_granularity = 8192 the server adds, or a TO
target. The read takes the clause from system.tables.create_table_query,
because system.tables reports every form with the same engine and the same
as_select, and the reason names the clause:
-- materialized view analytics.totals: ptah.run/clickhouse/view-storage was not captured (the view stores its rows with ENGINE = SummingMergeTree ORDER BY c SETTINGS index_granularity = 8192, which Ptah does not model), and its statement does not carry itschema inspect --format sql and ptah db read write that comment beside the
view, whose statement still carries Ptah’s storage. A comparison reports the
view undecided rather than synchronized, so schema drift against such a
description fails instead of reporting no drift. A change to the view’s query is
refused, because the drop and create it plans would recreate the view with
Ptah’s storage, and for a TO view inserts would stop reaching the target
table. HCL, YAML and Go annotations state no storage for a view, so an export to
them carries none. Manage such a view’s storage outside Ptah.
Generating a migration that removes such a view is refused before either file
is written. Its down file would have to recreate the view, and the captured
definition cannot restore its engine, sorting key or target table. This check
applies to ptah migrations generate and to ptah-compat migrate diff when
the directory format writes a rollback, such as golang-migrate. They use
the same plan for both directions. Keep the view in the desired schema, or
write reviewed migration SQL that retains its complete storage definition.
A view stored with Ptah’s default storage can still be removed and recreated,
even when another view’s storage is not described.
A one-way removal through ptah schema apply can still drop the view. The
Atlas directory format also publishes only forward SQL. These operations
discard the view’s inner storage without generating a file that restores it.
The check does not change migration SQL that was already written.
Roles and grants
Section titled “Roles and grants”Roles and grants complete the render, plan, apply, introspect, and diff cycle.
A declared role and a database- or table-scoped grant are applied, read back
from system.roles and system.grants, and compared to zero difference on the
next run. SQL, YAML, HCL, and Go annotations declare them, with the grant scope
written as database.table. These examples grant read access to the events
table in the ptah_test database:
CREATE ROLE ptah_reader;GRANT SELECT ON ptah_test.events TO ptah_reader;roles: ptah_reader: {}grants: ptah_reader_events: role: ptah_reader privileges: [SELECT] on_table: ptah_test.eventsrole "ptah_reader" {}permission { to = role.ptah_reader for = "ptah_test.events" privileges = [SELECT]}//ptah:schema:role name="ptah_reader"type PtahReaderRole struct{}
//ptah:schema:grant role="ptah_reader" privileges="SELECT" on_table="ptah_test.events"type PtahReaderEventsGrant struct{}DBML cannot declare roles or grants. Rendering the selected source emits:
CREATE ROLE IF NOT EXISTS `ptah_reader`;GRANT SELECT ON `ptah_test`.`events` TO `ptah_reader`;Roles are always planned before grants, because ClickHouse refuses a grant to a
role it does not know. GRANT ... WITH GRANT OPTION is emitted when the
declaration asks for it, and taking that option away again is the single
statement REVOKE GRANT OPTION FOR ..., which leaves the privilege itself in
place. Removing a grant emits REVOKE <privileges> ON <scope> FROM <role>.
A declared REVOKE ALL ON <table> takes every access type system.grants
reports for the role on the table, whatever the release calls it.
DROP ROLE IF EXISTS has a rendering for a schema source that spells one out,
but comparison never plans it — see “Roles are never dropped” below.
What Ptah manages here is roles and grants, and nothing else in ClickHouse’s access control:
| Not managed | What that means for you |
|---|---|
| Users | No user is created, altered, or read, so no credential enters a description, a plan, or a log. Provision users outside Ptah and grant them a managed role. |
| Role membership of a user | A user is not managed, so GRANT <role> TO <user> is not modeled. Role-in-role membership is: see below. |
| Quotas, settings profiles | Outside the schema model entirely; a declaration cannot express them and a read does not report them. |
| Column-scoped grants | GRANT SELECT(id) ON db.t is refused when declared and excluded when read. Grants are managed at database and table scope. |
| Wildcard and global scopes | *.* and a wildcard database are refused. Such a grant reaches objects no declared schema describes. |
| Privilege names the server rewrites | ALL, CREATE, DROP, SYSTEM, SYSTEM FLUSH, ACCESS MANAGEMENT, SHOW ACCESS, SHOW FILESYSTEM CACHES, and — at table scope only — SHOW and ALTER. See below. |
Five refusals arrive before anything on the server changes, and the reason for each is worth knowing in advance:
- A ClickHouse role carries no attributes.
system.rolesis(name, id, storage), so a declaredpassword,login,superuser,createdb,createrole, orreplicationis refused rather than dropped. Dropping a password would leave you believing a credential was set on an object that cannot hold one.ALTER ROLEis refused for the same reason: there is nothing to alter. - The server absorbs a narrower grant into a broader one. Granting
SELECTondb.*and ondb.tleaves one row fordb.*, in either order, and the table-level grant is recorded nowhere. Declaring both is refused, because the pair could never converge: the absorbed grant would read as missing on every inspection and the plan would re-issue it forever. Declare the broader scope. - A grant scope must be qualified as
database.table. An unqualified table name is refused. Rendering is offline and has no current database to resolve it against, and resolving an access-control decision against whichever database a session happens to have selected is not a formatting mistake. A trailing dot such asshop.is refused too, rather than read as the whole database: a typo must not widen one table’s privilege to every table. - A grant must name a role the same schema declares. ClickHouse resolves a
grantee by name across users AND roles, with no syntax to say which is meant.
If nothing of that name exists the
GRANTfails partway through a migration withUNKNOWN_ROLE; if a user of that name exists it succeeds and lands on the user, where the reader never sees it again — the plan re-issues it forever and a real account quietly holds a privilege nobody declared for it. Declaring the role removes both outcomes, because Ptah creates it in the same plan. One case this cannot cover: if a live ClickHouse user shares a name with a declared role, resolution still prefers the user. Do not name a role after an account. - Some privilege names are groups the server rewrites.
GRANT CREATE ON db.*records four rows —CREATE DATABASE,CREATE TABLE,CREATE VIEW,CREATE DICTIONARY— and never reads back asCREATE, so a schema declaring it can never converge.GRANT ALLrecords 45 individual rows on 26.7 and 39 on 24.10.GRANT SHOW ACCESSis stored asSHOW ROW POLICIES.GRANT SHOW FILESYSTEM CACHESis accepted and records nothing at all, which would tell you a grant applied while the role held no privilege. Declare the individual privileges instead. Group names that do read back as written stay declarable —ALTER TABLE,ALTER VIEW,ALTER COLUMN,ALTER INDEX,ALTER STATISTICS,ALTER PROJECTION,ALTER CONSTRAINT,SYSTEM SENDS, andSHOWandALTERon a database scope. A name the server itself refuses, such asINTROSPECTIONorSYSTEM RELOAD, needs no gate here: ClickHouse answersCode: 509 ... cannot be granted on the database level, which names the problem more precisely than Ptah could.
Three more boundaries shape what a run does:
- Roles are never dropped. A role that exists on the server and not in the
schema is named in the plan and left alone. A ClickHouse role is server-wide
and may carry grants outside the managed schema, so removing it is not Ptah’s
decision to make. A read reports only the roles the described grants name, and
leaves out roles defined in the server’s configuration files, whose
storageisusers_xml, because SQL does not own those. - A partial revoke fails the comparison.
GRANT SELECT ON db.* TO rfollowed byREVOKE SELECT ON db.t FROM rleaves two rows insystem.grants, and the role’s effective privileges are the first minus the second. A declaration cannot express an exception, so on a managed role Ptah refuses instead of comparing equal and reporting convergence. Remove the partial revoke, or stop declaring the role. - A revoke under a database grant fails the comparison. After
GRANT SELECT ON db.* TO r, a declaredREVOKE ALL ON db.t FROM rhas no row ondb.tto take, and takingdb.tout of the database grant would leave a partial revoke. Ptah refuses the revoke, for any role, unless the plan removes the database grant, as it does for a role the schema creates and does not grant that privilege ondb. Revoke ondb.*, or grant per table. A grant on*.*is outside the read, so a revoke under one is not seen. - An account that may not read the access catalog still gets a read.
Reading
system.rolesandsystem.grantsneeds a privilege reading a table does not, and an account holding onlySELECT,SHOW TABLESandSHOW COLUMNSis answeredCode: 497 ... (ACCESS_DENIED)by both. Rather than failing the whole read — which would break reading a schema that declares no role at all — Ptah describes everything else and records that it did not look. Comparison then withholds every declared role instead of planning aCREATE ROLEit could not verify, and nothing destructive can follow, because removal is decided from live rows and there are none.ptah-compat schema inspectsays so on stderr.
Two operational notes. ClickHouse RBAC statements carry no ON CLUSTER clause,
so on a cluster they affect the connected replica only; Ptah does not model
cluster propagation, and a multi-replica deployment needs its own arrangement
for that. And a ClickHouse role is server-wide rather than database-scoped, so a
role created against a dev or throwaway database outlives the database that
workflow drops.
A grant outlives its table in the same way. migrations drift and
migrations up --check-drift replay the history’s grants in the shadow
database and compare each one as the target’s grant on its own table or
database. A schema apply --dev-url rehearsal with PTAH_TRUST_REPLAY_SQL=1
writes the target’s grants onto the dev database’s tables. In both cases the
role keeps the grants on the shadow or dev database after its tables are
dropped.
The connected account needs the privileges these statements require —
ROLE ADMIN plus GRANT OPTION on what it grants. The docker-compose.yaml
in this repository configures CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT=1, which
is what gives its ptah_user that authority.
Role memberships
Section titled “Role memberships”member_of on a role names the roles it joins, and a plan runs GRANT `group` TO `member` and REVOKE. A membership may state the admin option, which is
WITH ADMIN OPTION; ClickHouse has no per-membership inherit or set option,
so a declaration that states one is refused. A plan withdraws the admin option in
place with REVOKE ADMIN OPTION FOR, which keeps the membership. A declaration
that states no option means no admin option. A read reports only the grants of a
role to a role, and a grant of a role to a user is not read.
A plan revokes a membership on ClickHouse by the same rule as on PostgreSQL: a
role that states member_of, even empty, owns its memberships, and a role
without the key keeps all of them. See
Role memberships for the rule and for the
UNMANAGED line schema apply and schema compare write for a membership
they keep.
Row policies
Section titled “Row policies”A row policy filters the rows of one table that the users and roles it names may read. SQL, HCL, YAML, and Go annotations can declare one:
CREATE TABLE orders ( id UInt64, tenant_id UInt64) ENGINE = MergeTree ORDER BY id;
CREATE ROW POLICY tenant_rows ON ordersFOR SELECT USING tenant_id = 1AS RESTRICTIVE TO ALL EXCEPT admin;table "orders" { column "id" { type = UInt64 } column "tenant_id" { type = UInt64 } primary_key { columns = [column.id] }}
row_policy "tenant_rows" { on = table.orders using = sql("tenant_id = 1") to = "ALL EXCEPT admin" as = "RESTRICTIVE"}tables: orders: columns: id: type: UInt64 primary: true not_null: true tenant_id: type: UInt64 not_null: truerow_policies: tenant_rows: table: orders using: tenant_id = 1 to: ALL EXCEPT admin as: RESTRICTIVEpackage models
//ptah:schema:table name="orders"//ptah:schema:rowpolicy name="tenant_rows" table="orders" using="tenant_id = 1" to="ALL EXCEPT admin" as="RESTRICTIVE"type Order struct { //ptah:schema:field name="id" type="UInt64" primary="true" not_null="true" ID uint64 //ptah:schema:field name="tenant_id" type="UInt64" not_null="true" TenantID uint64}DBML cannot declare ClickHouse row policies.
Render the SQL example:
ptah schema render --schema-file schema.sql --dialect clickhousePolicy and table names may be quoted; a table may name its database. ALTER ROW POLICY updates a policy declared earlier in the same
file or an earlier file of the schema load. It changes only the clauses it
states: USING NONE clears the filter, and TO NONE clears the recipients.
DROP ROW POLICY is accepted as migration syntax and refused in a desired
schema; omit the declaration to request removal during comparison.
SQL sources refuse IF NOT EXISTS, replacement declarations, ON CLUSTER,
access-storage clauses, renames, multiple policies or tables in one statement,
and backslash escapes in names. Use doubled quotes for embedded quote
characters. Unsupported clauses are reported before planning.
usingis the filter. Without one, the policy admits every row to the users it names.tonames users and roles,ALL,ALL EXCEPTnames, orNONE. Without one, the policy applies to nobody, as ClickHouse’s own default does.asisPERMISSIVE, the default, orRESTRICTIVE. A user reads the rows that pass at least one permissive policy and every restrictive one.
HCL uses a row_policy block with on pointing to its table. The using
attribute accepts a string or sql(...); to is a string with the same grammar
as YAML. Quote a literal role named ALL with backticks inside that string.
HCL export preserves the policy, and refuses a read that could not inspect the
policies.
The PostgreSQL policy block does not declare a ClickHouse row policy.
The compatibility CLI refuses row_policy in strict CE mode, even when the
dev database uses another dialect.
The directive and HCL block bind the policy to ClickHouse, so another target
leaves it out.
In YAML, an entry of the row_policies key declares the same policy with the
same attributes, keyed by its name. Row-level security scoped to ClickHouse is
refused in both formats, since it declares PostgreSQL’s row-level security,
and so is an enablement: ClickHouse has no table switch.
A plan creates, alters in place or drops each policy, and a read reports every policy on a table of the database, restrictive ones included. These are refused rather than dropped:
- A write check. ClickHouse parses
WITH CHECKand discards it, so the policy would filter reads and leave writes open. - A command other than
SELECT. A row policy filters reads only. - A comment, which a row policy cannot hold.
- A filter that names a column
notquoted, which 24.10 and 26.10 refuse with code 62; see Names.
The server binds a policy to a table name, not to a table. It keeps the policy
when the table is dropped, accepts one for a name no table has, and applies it at
once to the next table created under that name. A comparison reports such a
policy like any other, and the plan changes it on its own, before any
CREATE TABLE of the name:
- A policy the declaration leaves out is dropped with
DROP ROW POLICY. - A declared policy of the same name is changed with
ALTER ROW POLICY. The server refuses aCREATE ROW POLICYfor it with code 493 (ACCESS_ENTITY_ALREADY_EXISTS), measured on 24.10 and 26.10.
The rollback changes the policy back only after its DROP TABLE, so the old
filter is never in force on a table that still holds rows.
A schema written from the database has no table to declare such a policy on.
ptah db read, ptah schema inspect and ptah introspect leave it out, and
name it on standard error with the statement that drops it. So does a
comparison whose desired side is a database, or a migration directory replayed
on the dev database, such as ptah schema apply --to <url>:
warning: ClickHouse row policy "p" on table "gone" is left out: the database holds it for a table it does not hold, and applies it to the next table created under that name; no schema can declare it, so applying a schema written from this read drops it with DROP ROW POLICY `p` ON `gone`;Every schema source describes every row policy, so applying the written schema back drops the policy, and so does applying the desired side to a database that holds a policy of the name.
This holds when both sides hold the policy, by design: the plan brings the
server to what a schema can declare. ptah schema diff --from <url> --to <url>
on one database prints DROP ROW POLICY p ON gone. So does a comparison of two
environments that both hold the policy. ptah schema drift against a schema
written from the database reports the drop as a destructive
ptah.run/clickhouse/row-policy-change finding.
A plan that drops such a policy cannot be rehearsed on a dev database. The dev
database would have to hold the policy first, and a row policy outlives the dev
database, so ptah schema apply --dev-url refuses the statement before any
statement runs, measured on 24.10 and 26.10:
error: statement 1 cannot be rehearsed on the dev database: clickhouse migration replay rejects DROP ROW because its effects cannot be confined to the disposable database realm; if you trust this SQL to run with the dev connection's privileges, set PTAH_TRUST_REPLAY_SQL=1PTAH_TRUST_REPLAY_SQL=1 does not get past it. The rehearsal then runs the
drop, and the dev database refuses it with code 523, because no schema can
declare the policy, so the rehearsal never writes it there. In both cases
nothing reaches the target. Drop the policy on the target with the statement
the warning names, then apply.
A policy written ON db.* applies to every table of a database, and Ptah does
not model it. Nor does Ptah read a view, a materialized view, a dictionary, a
Null or Distributed table, or its own bookkeeping tables as tables. A policy
on any of these is kept while its relation remains: the plan changes nothing
for it and reports it as a policy the comparison could not decide. A schema
written from the database leaves it out too, and says so: a SQL export in a
comment, an HCL export in its header, and ptah introspect on standard error.
A comparison whose desired side is such a database leaves it out and names it on standard error, and the plan does not create it on the target. These notices describe what the read can declare. They do not predict whether a plan keeps or drops a policy.
A plan that drops a view or materialized view drops the policies on it first,
so the next relation created under the name does not inherit them, and the
comparison does not report them. That includes a table the declaration
creates under the name, since the plan drops the view ahead of the
CREATE TABLE. A view that another view or materialized view
replaces under the same name keeps its policies.
The down migration ptah migrations generate writes for such a plan creates
the view’s policies again and then the view. The read keeps each policy’s
filter, composition and role lists from system.row_policies, outside what the
comparison compares, and the rollback writes CREATE ROW POLICY from them
ahead of every CREATE VIEW. ClickHouse accepts a policy on a name that holds
no relation and filters the view created under it, measured on 24.10 and
26.10. The statements run without a transaction, so the order decides what a
failure leaves: a policy the server refuses, for a role dropped since the up
migration for example, stops the rollback before the view exists, and nothing
shows the rows the policy hid.
A policy whose definition the read did not keep is named in a comment in the down file, with the reason. A table the up migration drops comes back with the policies the read described on it.
The revision table’s storage engine
Section titled “The revision table’s storage engine”ClickHouse gives a table no engine unless the statement names one, and whether
an unnamed one is legal at all is decided by the server’s default_table_engine
— whose own default value is None. Against such a server the first
migrations up stopped before the first migration:
code: 119, message: Table engine is not specified in CREATE queryPtah names ENGINE = MergeTree in both revision layouts, which is what a server
whose default is already MergeTree was producing, so an existing deployment
sees the table it had.
An existing operation log is upgraded in place when a migration writes to it.
Ptah adds the run_reference, actor_origin, and repeatable columns as
Nullable(String). This form works in ClickHouse 24.10’s ALTER TABLE grammar
as well as on current servers; VARCHAR(...) NULL, although accepted when
creating a table, is rejected when adding a column on 24.10. Existing log rows
remain present, with NULL in the added columns.
A replicated deployment has to say so. With the default, the migration
history is a node-local MergeTree on whichever node ran the migration, and
every replica then reports itself consistent. Name the engine instead:
$ ptah migrations up --db-url 'clickhouse://…' \ --migrations-engine "ReplicatedMergeTree('/clickhouse/tables/{shard}/schema_migrations', '{replica}')"PTAH_MIGRATIONS_ENGINE carries the same value, and is the only spelling on the
compatibility surface — ptah-compat registers no flag for it, because the
community binary has none and the conformance cli-surface tier asserts flag
parity against it. ptah-compat migrate apply, status, set and down read
the variable; the native verbs take either. An empty or blank value is refused
before the run connects: read as unset, it would create the table with
MergeTree.
Whichever command creates the table decides its engine, so both of these hold:
- Every command that can create the table has to be given the same value.
migrations up,down,status,tag,baseline,repair, and the maintenance verbsedit,rmandrebaseall initialize metadata when they are the first to run.CREATE TABLE IF NOT EXISTSdoes not re-engine a table that already exists, so whichever command ran first decided it. - An engine the revision table cannot be is refused before any statement
runs. On MySQL and MariaDB it must be InnoDB, which is the only engine that
records an applied migration when the statement around it fails. Only
ClickHouse and the MySQL family take an engine clause, so on PostgreSQL,
CockroachDB, YugabyteDB, SQLite, SQL Server and Oracle any engine is refused.
The refusal happens first because MySQL DDL commits: rejecting the table
afterwards would leave one Ptah will neither use nor recreate. Every path of
migrations tagrefuses it too,--versionincluded, since the tag table stands beside the revision table.
Atlas revision metadata
Section titled “Atlas revision metadata”Ptah creates the Atlas revision table with partial_hashes declared as text.
ClickHouse reads a trailing NULL on a column definition as Nullable(T), so
declaring that column JSON asks for Nullable(JSON), and no ClickHouse server
handles that the way the rest of the Atlas revision layout needs:
- Servers that reject
Nullable(JSON)refuse theCREATEduring type analysis (code: 43, Nested type JSON cannot be inside Nullable type). The rejection happens before theIF NOT EXISTSexistence check, so an already-provisioned database does not escape it, and Atlas-format apply fails before any user migration SQL runs. - Servers that accept
Nullable(JSON)coerce the JSON null Ptah writes into the JSON type and store{}instead. The value the author wrote is replaced, and the column can no longer be scanned into a string by an Atlas-compatible consumer.
Declaring the column text resolves to Nullable(String) on both, which stores
the same JSON null every other dialect stores. This is stated by behavior rather
than by a version cut-off on purpose: the release that changed Nullable(JSON)
from rejected to accepted was not measured, and the column type is correct on
either side of it.
CREATE TABLE IF NOT EXISTS does not alter a table that already exists, so a
revision table created by an earlier Ptah against a server that accepted
Nullable(JSON) keeps that column type and keeps storing {}. Ptah ignores a
legacy {} on clean rows, but reads partial_hashes on dirty Atlas-format rows
with committed progress. Malformed metadata, including {} where a digest
array is required, fails closed during status or retry. Ptah does not rewrite
the column automatically; alter it to Nullable(String) or recreate the table
before recovering such a dirty row.
Setting a revision directly (SetAtlasRevision) is still unsupported on
ClickHouse, because revision history cannot be updated atomically there.
Next steps
Section titled “Next steps”- Which release lines are declared and at what support level: Database support matrix.
- Capability keys per dialect: Capabilities.
- Choosing an input format and source selector: Work with a desired schema.