Referencia · §8.15

Table storage

storage, §M14.20

Ez az oldal a nucleus saját dokumentációjából készül, ezért angol nyelvű.

How a table’s rows are kept is a module (principle 12): an implementation of TableStorage among those registered — row, column, row,column and sealed (§8.40) built in, others added through Registry::add_storage (process-wide, so every database’s tables may name them; nc_catalog.storages lists them). A table names its storage: CREATE TABLE … WITH (storage = name) (row by default; an unknown storage is 42704, an unknown option 22023), kept in its record (table record version 10) and shown in nc_catalog.tables.storage. Beside it, WITH (engine = lsm) puts the table’s keys in the LSM tree instead of the B+tree (§4.6).

The SQL layer reads and writes rows only through the trait, by row key — the table’s primary index prefix and the row’s primary key or hidden row id — and by ranges of row keys: write(txn, t, key, row, old), remove, exists(…, validated) (primary key and foreign key checks), get(…, wanted, labels) (a secondary index’s rows, which the index finds by row key), get_many (a group of them at once: the row storage’s through KvTxn::get_many, their descents overlapped), rows(Scan) (a range ascending, only the wanted columns decoded), batches(Scan) (the same a batch at a time for the vectorized executor — by default from rows), check (the integrity check’s part: rows as stored, problems noted), index_ids (the key spaces it uses under the table’s data prefix). Secondary indexes, constraints, foreign keys, policies, parallel splits and the executor stay above it, the same for every storage; a storage keeps all it stores under the table’s data prefix, so dropping or truncating a table removes it.

row encodes a row’s values together under its key (§8.1), a long value in chunks under the table’s index u32::MAX (§M14.26); its batches decode the encoding straight into vectors (§8.5).

column (column_store, segment) keeps rows as column segments: up to 32 768 rows with consecutive keys (fewer when wide), one KV value per column and one for the row keys, segments covering disjoint key ranges in key order, listed in a directory keyed by each one’s last key — after the table’s prefix, so a table moved to another id keeps it (§4.6; whole in a table made before record version 23) — (index u32::MAX - 3; with its first key, rows, and each column’s least and greatest values and NULLs). Columns are encoded by what they hold: integers, dates, times and timestamps by frame of reference and bit packing, or runs; doubles as they are, booleans a bit each; text (and char(n), as kinds of its own) as a dictionary and bit-packed codes when values repeat, else Arrow’s offsets and bytes; decimals of one scale whose unscaled values fit 64 bits as those integers, by frame of reference and bit packing; anything else value by value; NULLs a bitmap (a segment lists the table columns it holds: a partial column copy holds some). A segment’s id is a hash of its contents, so it never changes and its decoded columns are cached by id (in 16 shards by key, a hit locking its shard only to read; the size bound, all shards’ together, is an eighth of the memory the process may use — half the index objects’ budget, a bound, not memory taken — at least 256 MiB; past it the columns used longest ago in any shard go, an eighth of the bound at a time) — its directory entry decoded too, once (a lookup’s), and its row keys with every 32nd key’s first 8 bytes as a number beside them (a search narrows to 32 keys in that small array first, ClickHouse’s marks). A read of one row (by its key: an index lookup, a correlated subquery’s) takes each column’s value from the column decoded if it is cached, else from its encoding as stored — cached instead of the column decoded, smaller — read where the value lies (segment::value_at: every layout but value by value’s). A scan reads only the wanted columns of the segments its range overlaps, skips a segment the filters right above it rule out (column-constant comparisons against the segment’s least and greatest values), and hands each run of a segment’s rows to the vectorized executor as vectors. A dictionary column is decoded — and cached — as it is stored, its entries and each row’s code (Vector::Dict, a fraction of its text’s memory); a scan gives it as text, or as codes to a filter right above that asked for them (Scan::dicts): the filter’s leading conjuncts that test the column against constants by what cannot fail (comparisons, IN, LIKE, IS NULL, NOT, AND, OR) are tested on the entries, once a segment, and a row whose entry one holds FALSE for is dropped before the filter runs — the rows an AND would drop reading no further, so no later conjunct’s error is skipped. The rows left are made text (gathered into a batch of their own when at most half are left), and when every such conjunct held TRUE for each, only the filter’s other conjuncts are tested (lineitem’s 6 million rows: l_shipmode = 'MAIL' 16 → 12 ms, IN 20 → 14 ms, LIKE '%PERSON' 29 → 8 ms). Writes: rows a statement inserts — and the new versions of segment rows it updates — are gathered until it ends (4 segments’ worth at most, then written at once); then, 4096 or more go to segments directly, fewer to a delta store in the row storage’s format (index u32::MAX - 4, the rows’ key suffixes). An update or delete of a segment row marks it deleted: a marker keyed by the row (index u32::MAX - 2), not by its place in a segment, so it stays right when a merge rewrites the segment — deletes do not conflict with merges or with each other. A merge rewrites the segments the incoming rows’ key range overlaps — deleted rows dropped, delta rows moved — so appends make new segments and updates rewrite the segments they touch. Scans merge the segments’ rows with the delta store’s in key order; a key lookup checks the delta store, then the segment whose range holds the key. The rows an index finds are fetched a group at a time (get_many): the delta store’s and the markers’ keys read together — or, where the transaction sees none of the table’s, not at all, a loaded table’s usual case — and the keys in order, so the keys of one segment find it once. A snapshot’s lookups that ask the directory often enough — 64 keys, or a quarter of its segments when it was last read — read it whole once and look segments up in memory from then on: kept by (database, table, snapshot), 16 at a time, for transactions whose reads are their snapshot’s alone (KvTxn::reads_snapshot: nothing written, reads not recorded); a transaction that wrote looks its own segments up in the store (issue #5). MVCC and crash safety are the KV’s: segments, markers and delta rows are versioned keys written in their transactions; a delete and a merge of one segment, in either order, both commit and the delete holds (crates/sql/tests/column.rs). Concurrent writes conflict as a row table’s do: the directory is keyed by a segment’s last key, so two segments over the same keys need not share a key to conflict on — instead a merge reads the directory validated from its first incoming key through the first entry past its last (to the directory’s end without one) and the delta store’s keys in that range, and a statement that stores rows in the delta store reads the directory the same way for its keys. A segment another transaction commits over those keys meanwhile, or a delta row among them, fails the later commit with a retryable 40001, and no committed row is lost; small writes to different keys never conflict. A scan read validated (a backfill’s part, issue #18) validates the deletion markers of the rows it read alone, a batch at a time, not its segments’ whole: a write to another row of the segment does not fail it. A write past the last segment claims the directory to its end, so two writers appending there at once may conflict even with different keys (one retries); tested for every pair of large and small writes, overlapping or not, in either order (crates/sql/tests/column.rs). A statement that fails part way leaves nothing gathered: a table is registered for the statement’s clean-up when its first row is gathered, so the rows of a statement that fails — say on a unique index while updating — are dropped with it, never stored by the next statement on the thread. What a statement keeps per table it writes — the rows written and gathered — is one statement context (storage::TableWrites, behind with_writes / peek_writes / take_writes; §M14.20 W3), cleared when the statement ends, whatever its outcome. An existence check (a key’s uniqueness on insert) looks at the gathered rows — past the last one, a load’s every key, one comparison — then at the directory’s first segment ending at or after the key and, when none does, at the delta store’s first row at or after it: both first reads, which the transaction answers from memory inside a range it found empty (§6.1), so a load’s ascending keys read the store once each time rows are stored, not once a row. A batch (§8.7) that is strictly ascending and meets no stored row — none gathered between its first and last key, no segment there, no delta row — is gathered whole without a check per row; any other batch goes row by row. A segment is built from typed vectors (§M14.20 W3b): the rows moved, not copied, into columns transposed in parts on threads, each column joined and encoded on threads of its own (Vector::typed, the one row-to-column builder; integer least and greatest values from the kernels; a text column’s dictionary chosen by a distinct count that stops past a quarter of the rows). Values read from a segment are stored values; an enum’s labels come from the reading transaction’s catalog (Labels::fill), so a renamed label reads renamed. The same SQL runs on both storages with the same results: the tests run loads, updates, key changes and deletes on a row and a column table and compare every query, a row and a batch at a time and in parallel, and the integrity check. On a million rows (docs/benchmarks.md): a sum 22 → 2 ms (one thread 81 → 13 ms), a filtered count 23 → 2.4 ms, a 1000-group GROUP BY 35 → 19 ms, the file of its columns 32 MB against 61; key lookups 0.1 → 0.3–1.7 ms. The delta store’s deleted rows stay as versions until vacuum.

row,column keeps both copies (HTAP): the rows whole in the row storage — which key lookups, row scans and constraint checks read — and a column copy of every column or of some, which scans whose columns it holds read. Writes go to the row copy and note their keys among the changed (index u32::MAX - 5; a segment row they replace marked), and the column copy reads a changed key’s row from the row copy; merges take changed keys into segments as the column storage’s merges its delta store.

Changing a table’s storage (convert): ALTER TABLE t SET STORAGE row | column | row, column | column (a, b, …) | sealed (column (a, b, …) a column copy of those columns beside the rows; sealed, §8.40) converts the table online — in transactions of its own, a part at a time, while other sessions read and write it; not inside a transaction block (25001). Building a column copy, the table is row,column with the copy being built (writes note their keys) and segments are written from the rows a segment at a time; building a row copy, the table is row,column with reads from the column copy and the segments’ rows not written since copied a thousand at a time; dropping a copy, the table switches at once and the copy’s keys go afterwards, a part at a time. Between column and row,column the delta moves over a part at a time after the switch (the table reads both meanwhile; writes go to the new one), so no step has to catch up with writes. Each switch is a small transaction that rewrites the table’s record, and every write reads the record validated, so a write begun under the old state fails (40001) and runs again; a conversion cut short leaves a state that reads and writes correctly, and running it again finishes it (the table’s record keeps the state, nc_catalog.tables its storage). crates/sql/tests/convert.rs converts through every pair with writes between, converts while another thread writes (each write retried on 40001), and crashes conversions at I/O points, comparing a row table’s results and running the integrity check each time. On a million rows, a row table gets its column copy in 0.7 s. crates/sql/tests/storage.rs registers a module’s storage and runs writes, unique and foreign key checks, index lookups, scans a row and a batch at a time, in parallel, and the integrity check through it, against row tables.