diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 48377c44a..35820d37f 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -21,12 +21,14 @@ concurrency: env: CARGO_TERM_COLOR: always - # The size of the shipped code, rounded up to 500 lines, and the number of tests, rounded up - # to 10. A change that crosses either number edits it here, in the same change, where its - # reader sees that the code grew or shrank. Neither ever passes 150,000 lines or 1,000 tests. - SHIPPED_LINES: 21000 - TESTS: 380 - TEST_LINES: 38000 + # The shipped code, rounded up to 500 lines; the tests, rounded up to 10; the lines of tests, + # rounded up to 500. Each holds from both sides, at most the number and within one rounding of + # it, so a cleanup lowers it for good. Reaching one means a refactor first: a number is raised + # only when a planned stage of the work ends, never inside a fix (v2/AGENTS.md). Neither size + # ever passes 150,000 lines or 1,000 tests. + SHIPPED_LINES: 25000 + TESTS: 400 + TEST_LINES: 41000 jobs: lint: @@ -80,12 +82,13 @@ jobs: test "$TESTS" -le 1000 test "$tests" -le "$TESTS" test "$tests" -gt "$((TESTS - 10))" - - name: Test lines are at most the stated number + - name: Test lines are at most the stated number and within 500 of it if: matrix.os == 'ubuntu-latest' run: | lines=$(find v2/*/tests v2/*/src -type f \( -path '*/tests/*' -o -name tests.rs \) -exec cat {} + | wc -l) echo "$lines test lines; the stated number is $TEST_LINES" test "$lines" -le "$TEST_LINES" + test "$lines" -gt "$((TEST_LINES - 500))" minimum-rust: runs-on: ubuntu-latest diff --git a/crates/contextdb-core/tests/timestamp_audit.rs b/crates/contextdb-core/tests/timestamp_audit.rs index a7a8a2262..1fa208f2d 100644 --- a/crates/contextdb-core/tests/timestamp_audit.rs +++ b/crates/contextdb-core/tests/timestamp_audit.rs @@ -46,8 +46,10 @@ fn walk_dir_into(dir: &Path, root: &Path, out: &mut Vec) { } fn path_is_excluded(rel: &str) -> bool { - rel.split('/') - .any(|component| component == ".git" || component == ".worktrees") + rel.starts_with("v2/") + || rel + .split('/') + .any(|component| component == ".git" || component == ".worktrees") } fn collapse_ws(line: &str) -> String { diff --git a/docs/performance/README.md b/docs/performance/README.md index 3117703f5..9a23c6a3b 100644 --- a/docs/performance/README.md +++ b/docs/performance/README.md @@ -1,4 +1,52 @@ -# Performance measurement +# Performance + +What contextdb promises about speed and size, the test that guards each promise, and the last +figure measured against it. The page has two parts: the bars of the engine in `v2/` (contextdb +2), and, further down, how the old engine (contextdb 1, the packages under `crates/`) is measured. + +## The bars of the engine in `v2/` + +**How a promise is kept.** A promise of speed or size is guarded by a test that the check of every +pull request runs and that counts the work an operation does, such as rows read and vectors +compared; it fails when the count grows, on any machine. No test decides by a clock. A timed +figure is taken on a named machine and printed beside the promise, with the machine named and the +date. A promise is stated only where the product's own documents state it: where they give no +figure, the row says "no figure promised", and a figure in the last column is a measurement, not a +promise. Where no counted test guards a promise yet, the row says "none yet" and what is not built or not guarded yet. + +**The machine.** Every figure below was taken on one build machine: an AMD Ryzen 9 9955HX with 16 +cores and 32 threads and 64 GB of memory (59 GiB as the operating system counts it). A search is +run by one thread in a read session under a 1 GiB memory limit. It is a desktop-class machine and +not a user's machine: read a figure as a comparison of one build of the engine with another on +this machine, and expect other machines to differ. A search time is the 95th percentile of its +passes. + +**How this folder is used.** A measurement is filed as a result in `results/`, from +[`results/TEMPLATE.md`](results/TEMPLATE.md), named `-.md`. The table's row takes +its last figure from its result file and links it. A promise enters the table when it enters the +product's root documents, with the counted test that guards it or "none yet". + +| Promise, in the product's words | Counted test that guards it | Last measured figure | Machine and date | +|---|---|---|---| +| **Find time at 100,000 vectors, with recall.** "As a store grows, a vector search stays within the time the product promises." No figure promised for the time or for recall. | `an_indexed_search_does_fewer_distance_evaluations_than_exact` (`v2/contextdb/tests/vectors_index.rs`) counts the vectors compared on a small store. None yet at 100,000 vectors. | 100,008 real passages in eight partitions, ten nearest: one partition 1.411 ms (automatic), recall 1.0000 (100 of 100 questions); all eight 4.027 ms (automatic), recall 0.9990 (99 of 100). [Result](results/2026-11-14-find-100k.md) | The machine above; 2026-11-14, tree of `0c708a979`. | +| **Find time at 1,000,000 vectors, with recall.** The same promise; no figure promised. | None yet. | 1,000,000 generated sightings in one partition, indexed: 30.577 ms, recall 1.0000; 1,000,000 generated vectors indexed: 1.132 ms, recall 1.0000 (this one not taken again at this tree). [Result](results/2026-11-14-find-1m.md) | The machine above; sightings 2026-11-14, tree of `0c708a979`; generated vectors 2026-11-14, tree of `7f150eed3`. | +| **Find time at 5,000,000 vectors, with recall.** The same promise; no figure promised. | None yet. | 5,000,000 sightings in one partition, indexed, three passes: 114.075 to 116.138 ms, recall 1.0000; exact search 856.9 to 874.4 ms (not taken again at the latest tree). [Result](results/2026-11-14-find-5m.md) | The machine above; 2026-11-14, tree of `cb9c072c6`. | +| **The consumer's declared find** (a search over one context, several, or all). "A growing store keeps its search time." No figure promised. | `a_filtered_search_reads_its_index_range_and_a_ranked_one_asks_every_vector` (`v2/contextdb/tests/vectors_statements.rs`) and `an_indexed_filter_reads_only_the_rows_it_returns` (`v2/contextdb/tests/counted_work.rs`) count the vectors compared and the rows read. | 100,008 passages: one context 1.462 ms, several 3.913 ms, all 4.136 ms (p95), reading 37, 36 and 36 rows (median). [Result](results/2026-11-14-declared-find.md); [filtered finds](results/2026-11-14-filtered-find.md) | The machine above; 2026-11-14, tree of `0c708a979`. | +| **Searches stay fast while writes arrive.** "When new vectors arrive faster than maintenance keeps up with them, searches are protected and the writer is slowed. ... a search made in the middle of it stays fast." | None yet: no limit on the new vectors a search compares one by one exists. | Not built yet: no limit on the new vectors a search compares one by one exists in this version. Measured earlier with 10,000 vectors not yet packed: a search took 24.714 ms at the median, 26.095 ms at p95. | The machine above; 2026-11-12. | +| **Import rate.** "A large import therefore runs only as fast as maintenance keeps up." No figure promised. | None yet: nothing slows a writer that outruns maintenance. | 1,000,000 sightings loaded in 35.3 s, then sealed in 15.4 s and grouped in 343.4 s; 100,008 passages loaded in 3.5 s. Not taken again at this tree: 1,000,000 small rows loaded in 11.3 s under a 64 MiB limit; 1,000,000 generated vectors loaded in 27.0 s, sealed in 20.4 s, grouped in 348.6 s. [Result](results/2026-11-14-import-rate.md) | The machine above; 2026-11-14, tree of `0c708a979` (the rows not taken again: tree of `7f150eed3`). | +| **A store in steady use stays within twice its data, and reports what each table takes.** "After maintenance, a store that has been written to and expired for any length of time takes at most twice the bytes of the data it holds now. ... The engine reports how much disk each table takes and how much free space the store holds." | `a_store_with_twelve_indexes_stays_under_twice_its_bytes_and_under_its_recorded_size` and `two_hundred_rows_of_50_000_byte_indexed_values_make_a_store_smaller_than_twice_their_bytes` (`v2/contextdb/tests/long_keys.rs`) guard freshly loaded stores. None yet for a store written and expired over time, and the report per table is not built yet. | Freshly loaded: 62,447 commands, 15 indexes 1.59 times its data; 100,008 passages, 13 indexes 1.58 times. Not within the promise: a small store rewritten whole by a few large commits keeps free space the size of its data (24,000 rows in 4 commits: 3.3 times; 2026-11-13). [Result](results/2026-11-14-store-size.md) | The machine above; 2026-11-14, tree of `0c708a979`. | +| **Running for months does not creep.** "Once a table's retention period is full and old rows expire as fast as new ones arrive, the store stays level however long it runs without a restart: the disk it takes, the memory its process holds and the work a search does stop growing." | None yet: the engine does not yet check this. | Not measured yet. | | +| **Crash recovery time does not depend on the store's size.** "Crash recovery time after power loss or a kill does not depend on how much the store holds." | None yet for the time. `a_kill_at_any_storage_call_of_a_commit_leaves_all_or_nothing` (`v2/contextdb/tests/crash/main.rs`) guards what a kill leaves, not how long the next open takes. | Not measured yet. After a killed writer the open reads every page the store has in use (`v2/contextdb/src/database/mod.rs`), so it does grow with the store in this version. | | +| **Sync runs by itself and sends only what changed.** "By default sync runs on a built-in schedule, which the host may change; nobody has to start it. ... sends only what has changed since then, so what crosses the network grows with what changed, not with the size of the store." | None yet: not built. | Not built yet. | | +| **A sync exchange that is cut off carries on.** "An exchange that is cut off carries on from where it stopped rather than starting again." | None yet: not built. | Not built yet. | | +| **A growing store keeps its search time.** "The engine's own maintenance does what keeps it there: it rebuilds the index with more clusters as the data grows ... The host does nothing for it." | None yet: maintenance by itself and searches at 10 and 20 million vectors are not built or measured. | Not built yet: nothing in this version runs maintenance unless the host calls `Database::run_maintenance_cycle`. Searches measured up to 5,000,000 vectors only (rows above). | | +| **Every promised speed and size is guarded by counting work.** "A promise of speed or size is written into the root documents only with the counted test that guards it named." | The rows above name the tests that exist (`v2/contextdb/tests/counted_work.rs`, `vectors_index.rs`, `vectors_statements.rs`, `long_keys.rs`); every row that says "none yet" still lacks its guard. | Not measured: whether every row has its guard is what the rows above list. | | +| **One commit.** "Rows, relationships, vectors and the index state built from them commit together or not at all." No figure promised for its speed. | `a_kill_at_any_storage_call_of_a_commit_leaves_all_or_nothing` and `a_kill_inside_a_commit_of_vectors_keeps_rows_and_vectors_together` (`v2/contextdb/tests/crash/main.rs`) kill the process at every storage call of a commit and check that all of it or none of it is there. | 20,000 commits of one row each (notes of 1.6 KB): 28.0 s (the merged code took 27.6 to 29.9 s in runs of the same kind; an earlier run in another folder took 11.1 s). [Result](results/2026-11-14-one-commit.md) | The machine above; 2026-11-14, tree of `0c708a979`. | + +## The old engine (contextdb 1): how it is measured + +Everything below this heading is about the old engine, the packages under `crates/`, and is kept +with its headings one level lower and its publishing steps adjusted to the new template; it does not describe contextdb 2. How a contextdb change is measured, how a measurement is judged against the product's acceptance bars, and how a reviewed result becomes public. **The @@ -10,7 +58,7 @@ here instead of repeating them. [`scripts/ci-performance.py`](../../scripts/ci-p is the executable truth for profiles and commands; if this page and the script ever disagree, the script wins and this page is wrong. -## Current state +### Current state - **No official measured result.** There is no official measured run yet, so there is no "latest result". [Measured results](#measured-results) lists one @@ -30,7 +78,7 @@ ever disagree, the script wins and this page is wrong. is not a product acceptance bar, and a benchmark run that completes is not acceptance evidence. -## Acceptance bars +### Acceptance bars The rows below specify required acceptance measurements for storage growth: imports of 10,000 and 100,000 passages, search, event append, open, memory, recall and @@ -63,7 +111,7 @@ Here, p95 is the 95th-percentile latency. `EXACT` and `AUTO` compare allowed sto These areas also remain binding for imports and vector search: exact work counts, acceleration, throughput, append, read-only open, maintenance, schema, snapshots, resources, whole-process memory, sustained writers, recall and 100k search latency. Continuous-writer reads, status reads and existing refusal budgets remain binding. -### Unpublished numeric limits +#### Unpublished numeric limits Two memory limits are part of the acceptance scope but have no number published here: the whole-process memory ceiling for grown-store transient @@ -85,7 +133,7 @@ What this means for a run made with this guide: acceptance threshold published in this repository. Until one is published, a summary cannot report `PASS` for them and reports them as `NOT RUN`. -## Why not GitHub-hosted runners +### Why not GitHub-hosted runners GitHub-hosted runners are shared virtual machines with variable neighbours, disk and CPU. A timing taken there says nothing reliable about this code, so @@ -94,9 +142,9 @@ disk and CPU. A timing taken there says nothing reliable about this code, so dedicated self-hosted machine is an owner-only future step (see [Future automation](#future-automation-owner-only-todo)) and is not configured. -## The journey +### The journey -### 1. See what the change touches (CI-only step) +#### 1. See what the change touches (CI-only step) This step happens only in CI: `scripts/ci-impact.py` reads the GitHub event and output files, so it has no local mode. The `impact` job of a PR run prints one @@ -111,7 +159,7 @@ required gate. It does **not** say which profile to run. The per-path classes it prints are a hint for the next step, not proof that other areas are unaffected. -### 2. Choose a profile +#### 2. Choose a profile Profiles come from [`scripts/ci-performance.py`](../../scripts/ci-performance.py) (`PROFILES`); what each target measures is in the @@ -147,7 +195,7 @@ not-run benchmarks) without running or downloading anything: bash scripts/verify performance manifest --profile ``` -### 3. Prepare two clean checkouts on one controlled host +#### 3. Prepare two clean checkouts on one controlled host The current native runner is Linux-only. It reads Linux `/proc` and `/sys` cgroup interfaces, calls util-linux `lscpu`, and calls GNU `df -T`; those @@ -182,7 +230,7 @@ bash scripts/verify performance report --profile --output .md`, for example `--.md`. -2. Fill in the mandatory `Kind` / `Status` first line, then only reviewed - public fields. Descriptive numbers go in the descriptive table, which has no - acceptance threshold and no verdict. The acceptance table lists only rows from +2. Fill in only reviewed public fields. The template is laid out for the engine in `v2/`; for the + old engine, also state the acceptance rows you report on from [Acceptance bars](#acceptance-bars), quoted verbatim, each `PASS`, `FAIL`, `NOT RUN` or `NOT EVIDENCE` with its evidence and coverage. Never paste the raw receipt, logs, filesystem paths, hostnames, user names, cgroup paths or any secret. -3. Add a line to [Measured results](#measured-results) starting with the same - Kind and Status, then area, hardware label, date and the exact candidate +3. Add a line to [Measured results](#measured-results) starting with its Kind and Status, then area, hardware label, date and the exact candidate source SHA that was measured. Link the run that was actually measured, never "the latest commit". 4. Open a normal pull request. The owner reviews and merges it. Merging a @@ -265,20 +311,20 @@ in a PR discussion), `historical` (measured before this template existed, reconstructed from what was kept). Only the owner adds entries to the official list. -## Measured results +### Measured results -### Official +#### Official None yet. Entries take the form: `Kind: official · Status: <…>` · area (profile) · hardware label · date · candidate SHA · link to the summary under `results/`. -### Community and historical +#### Community and historical None published. Community and historical entries are listed here, never under Official, and every one starts with its Kind and Status. -## Future automation (owner-only TODO) +### Future automation (owner-only TODO) Not implemented. `performance.yml` is a dormant placeholder: it cannot start on any push, tag or dispatch, and its manual-dispatch trigger stays commented diff --git a/docs/performance/results/2026-11-14-declared-find.md b/docs/performance/results/2026-11-14-declared-find.md new file mode 100644 index 000000000..bec9e28f3 --- /dev/null +++ b/docs/performance/results/2026-11-14-declared-find.md @@ -0,0 +1,28 @@ +# Performance result: the consumer's declared find on a 16-core desktop-class machine, 2026-11-14 + +## Promise + +- Promise, in the product's words: "As a store grows, a vector search stays within the time the product promises". No figure promised. The bars below were set for this step against the figures of 2026-11-12; they are not promises. +- Counted test that guards it: `a_filtered_search_reads_its_index_range_and_a_ranked_one_asks_every_vector` (`v2/contextdb/tests/vectors_statements.rs`) and `an_indexed_filter_reads_only_the_rows_it_returns` (`v2/contextdb/tests/counted_work.rs`) count the vectors compared and the rows read. + +## Measurement + +- Date: 2026-11-14; revision measured: `0c708a979e9eb5cbb1dca142f514edf96656711e`, five runs, the median of the five printed +- Program and command: the declared-find lines of `v2/numbers.sh` (`queries declared`): the consumer's own find statement, as it sends it, over a store built from its declarations +- Data: 100,008 passages, 13 indexes +- Passes and statistic: five passes after 5 untimed searches; p95 is the median over the five runs of the middle of a run's passes; threads: 1; memory limit: 1,073,741,824 bytes (read session) +- Machine: AMD Ryzen 9 9955HX, 16 cores and 32 threads, 59 GiB of memory (a 16-core desktop-class build machine; not a user's machine); operating system: unknown; Rust toolchain: unknown; user's machine: no +- Settings that can change the result: none recorded + +## Figures + +| Row | Figure | Unit | Previous figure and its date | +|---|---|---|---| +| one context, p95; rows read, median | 1.462; 37 | ms; rows | 1.489; 37 (2026-11-14, `090d140ec`); bar 1.50 | +| several contexts, p95; rows read, median | 3.913; 36 | ms; rows | 3.913; 36 (2026-11-14, `090d140ec`); bar 4.02 | +| all contexts, p95; rows read, median | 4.136; 36 | ms; rows | 4.167; 36 (2026-11-14, `090d140ec`); bar 4.33 | + +## Limitations + +- The bars were set by this step's measurement, not by the root documents, which promise no figure. +- Before the fixes of the last piece of SQL work, the same find read 12,004 rows on one context. diff --git a/docs/performance/results/2026-11-14-filtered-find.md b/docs/performance/results/2026-11-14-filtered-find.md new file mode 100644 index 000000000..ca0bc80ad --- /dev/null +++ b/docs/performance/results/2026-11-14-filtered-find.md @@ -0,0 +1,32 @@ +# Performance result: the filtered find on a 16-core desktop-class machine, 2026-11-14 + +## Promise + +- Promise, in the product's words: "As a store grows, a vector search stays within the time the product promises". No figure promised for a search under a filter. +- Counted test that guards it: `a_filtered_search_reads_its_index_range_and_a_ranked_one_asks_every_vector` (`v2/contextdb/tests/vectors_statements.rs`) counts the vectors compared by a filtered search. The step's bars for the rows below were measured, not counted. + +## Measurement + +- Date: 2026-11-14; revision measured: `0c708a979e9eb5cbb1dca142f514edf96656711e` for the first row and the exact figure of the second (five runs, the median of the five printed); every other row keeps the figures of `cb9c072c687d1ab062ee90d9e4a460b2482cbab4` with measuring programs added, not taken again at the head +- Program and command: the filtered-find rows of the step's measurement (`passages`, `measure landed 5000000`) +- Data: 100,008 passages for the first two rows; a store of 5,000,000 rows for the others, with a filter passing the rows named and the key ranges named +- Passes and statistic: five passes for the passages, three for the others, each value as printed; threads: 1; memory limit: 1,073,741,824 bytes (read session); release build +- Machine: AMD Ryzen 9 9955HX, 16 cores and 32 threads, 59 GiB of memory (a 16-core desktop-class build machine; not a user's machine); operating system: unknown; Rust toolchain: unknown; user's machine: no +- Settings that can change the result: search mode as named in the rows + +## Figures + +| Row | Figure | Unit | Previous figure and its date | +|---|---|---|---| +| a filter passing 992 rows on a column with the advised index present, indexed, p95; rows read | 32.653; 2,558 rows read | ms | 32.961, 32.731, 33.000, 32.468, 32.693; 2,558 rows read (2026-11-14, `cb9c072c6`); 251 ms, 100,018 rows read before the last fixes | +| the same filter, exact, p95; rows read | 38.122; 2,561 rows read | ms | 38.3 to 39.5 (2026-11-14, `cb9c072c6`); the rest of this row (no index, 33.054, 32.892, 32.629, 32.620, 32.847) is not taken again | +| a filter passing 1,000 rows, rows compared one by one | 3.117, 3.062, 3.070 | ms | 2.98 (before the last fixes) | +| a filter passing 10,000 rows | 36.866, 36.774, 38.023 | ms | 37.4 to 39.9 | +| a filter passing 100,000 rows | 453.450, 442.631, 444.045, against the search 440.796, 442.036, 441.162 | ms | 618.6 | +| a key range of 39,000 rows of 5,000,000 (inside the one-by-one bound of 39,062), `small_set: yes` | 107.016, 112.535, 108.126; 39,010 rows read | ms | not measured | +| a key range of 39,200 rows (past the bound), `small_set: no` | 459.486, 459.392, 461.319; 1,455 rows read | ms | not measured | + +## Limitations + +- The step across the bound is 4.3 times in time (about 108 ms to 460 ms) at this size. +- Time figures are of this machine only; no timed figure is a promise. diff --git a/docs/performance/results/2026-11-14-find-100k.md b/docs/performance/results/2026-11-14-find-100k.md new file mode 100644 index 000000000..7eba4a9d5 --- /dev/null +++ b/docs/performance/results/2026-11-14-find-100k.md @@ -0,0 +1,33 @@ +# Performance result: find at 100,008 vectors on a 16-core desktop-class machine, 2026-11-14 + +## Promise + +- Promise, in the product's words: "As a store grows, a vector search stays within the time the product promises" (architectural views, the paragraph "A growing store keeps its search time"). No figure promised. +- Counted test that guards it: `an_indexed_search_does_fewer_distance_evaluations_than_exact` (`v2/contextdb/tests/vectors_index.rs`) counts the vectors compared on a small store. None yet at 100,000 vectors. + +## Measurement + +- Date: 2026-11-14; revision measured: `0c708a979e9eb5cbb1dca142f514edf96656711e`, five runs, the median of the five printed +- Program and command: the passages measurement of `v2/numbers.sh`, run with the build wrapper that gives it the machine alone; lines `passages_100008_find_*` +- Data: 100,008 real search passages, each a vector of 768 numbers and five other columns, in eight partitions, built and then sealed; the ten nearest asked for, over one partition, over several, over all +- Passes and statistic: five passes in each run, five runs; p95 is the median over the five runs of the middle of a run's passes; recall is the share of the recorded true ten nearest found, over 100 questions; threads: 1; memory limit: 1,073,741,824 bytes (read session) +- Machine: AMD Ryzen 9 9955HX, 16 cores and 32 threads, 59 GiB of memory (a 16-core desktop-class build machine; not a user's machine); operating system: unknown; Rust toolchain: unknown; user's machine: no +- Settings that can change the result: search mode as named in the figures; build rustflags none; popcount counting + +## Figures + +| Row | Figure | Unit | Previous figure and its date | +|---|---|---|---| +| one partition, exact, p95 | 1.411 | ms | 1.436, 2026-11-14 (`090d140ec`) | +| one partition, indexed, p95 and recall | 0.694 and 1.0000 (all ten on 100 of 100) | ms | 0.709 and 1.0000, 2026-11-14 (`090d140ec`) | +| one partition, automatic, p95 and recall | 1.411 and 1.0000 (100 of 100) | ms | 1.436 and 1.0000, 2026-11-14 (`090d140ec`) | +| several partitions, indexed, p95 and recall | 1.541 and 0.9990 (99 of 100) | ms | 1.570 and 0.9990, 2026-11-14 (`090d140ec`) | +| several partitions, automatic, p95 and recall | 3.800 and 1.0000 (100 of 100) | ms | 3.857 and 1.0000, 2026-11-14 (`090d140ec`) | +| all partitions, exact, p95 | 10.789 | ms | 10.856, 2026-11-14 (`090d140ec`) | +| all partitions, indexed, p95 and recall | 4.031 and 0.9990 (99 of 100) | ms | 4.063 and 0.9990, 2026-11-14 (`090d140ec`) | +| all partitions, automatic, p95 and recall | 4.027 and 0.9990 (99 of 100) | ms | 4.054 and 0.9990, 2026-11-14 (`090d140ec`) | + +## Limitations + +- Time figures are of this machine and build only; no timed figure is a promise. +- Recall is over 100 recorded questions. diff --git a/docs/performance/results/2026-11-14-find-1m.md b/docs/performance/results/2026-11-14-find-1m.md new file mode 100644 index 000000000..651277977 --- /dev/null +++ b/docs/performance/results/2026-11-14-find-1m.md @@ -0,0 +1,31 @@ +# Performance result: find at 1,000,000 vectors on a 16-core desktop-class machine, 2026-11-14 + +## Promise + +- Promise, in the product's words: "As a store grows, a vector search stays within the time the product promises". No figure promised. +- Counted test that guards it: none yet at this size. + +## Measurement + +- Date: 2026-11-14; revision measured: `0c708a979e9eb5cbb1dca142f514edf96656711e` for the sightings rows (five runs, the median of the five); the generated-vector rows were not taken at this revision and keep the figures of `7f150eed3afb284c2c02220431c3cb858635f361` +- Program and command: the generated-vectors and sightings measurements of `v2/numbers.sh` (`measure synthetic` and `measure sightings`); lines `synthetic_1000000_*` and `sightings_1000000_*` +- Data: two stores of 1,000,000 generated vectors of 768 numbers in one partition each: random vectors near centres, and sightings in tracks of ten whose appearance drifts; sealed and grouped before searching; 100 questions +- Passes and statistic: p95 and p50 as the program prints them; threads: 1; memory limit: 1,073,741,824 bytes (read session) +- Machine: AMD Ryzen 9 9955HX, 16 cores and 32 threads, 59 GiB of memory (a 16-core desktop-class build machine; not a user's machine); operating system: unknown; Rust toolchain: unknown; user's machine: no +- Settings that can change the result: search mode as named in the figures; build rustflags none + +## Figures + +| Row | Figure | Unit | Previous figure and its date | +|---|---|---|---| +| generated, indexed, p95 and recall (not taken at the head; `7f150eed3`) | 1.132 and 1.0000 (100 of 100) | ms | 1.122 and 1.0000, 2026-11-12 | +| generated, automatic, p95 (same) | 1.054 | ms | 1.012, 2026-11-12 | +| generated, exact, p95 (same) | 176.581 | ms | 180.378, 2026-11-12 | +| sightings, indexed, p95 and recall | 30.577 and 1.0000 | ms | 30.011 and 1.0000, 2026-11-14 (`090d140ec`) | +| sightings, automatic, p95 and recall | 27.844 and 1.0000 | ms | 28.180 and 1.0000, 2026-11-14 (`090d140ec`) | +| load of 1,000,000 generated vectors (same) | 27.0 | s | 26.5 to 27.1, 2026-11-12 | + +## Limitations + +- Time figures are of this machine and build only; no timed figure is a promise. +- Recall is over 100 questions. diff --git a/docs/performance/results/2026-11-14-find-5m.md b/docs/performance/results/2026-11-14-find-5m.md new file mode 100644 index 000000000..0044470fb --- /dev/null +++ b/docs/performance/results/2026-11-14-find-5m.md @@ -0,0 +1,29 @@ +# Performance result: find at 5,000,000 vectors on a 16-core desktop-class machine, 2026-11-14 + +## Promise + +- Promise, in the product's words: "As a store grows, a vector search stays within the time the product promises". No figure promised. +- Counted test that guards it: none yet. + +## Measurement + +- Date: 2026-11-14; not taken again at revision `0c708a979` (a store of this size takes the better part of an hour to build); the figures below are of the fixed engine `cb9c072c687d1ab062ee90d9e4a460b2482cbab4` with measuring programs added (the final landing run of `numbers.sh` did not include this size) +- Program and command: `measure landed 5000000` on a built store of 5,000,000 sightings, reopened +- Data: 5,000,000 generated sightings of 768 numbers in one partition +- Passes and statistic: three passes, each value as printed; threads: 1; memory limit: 1,073,741,824 bytes (read session); release build +- Machine: AMD Ryzen 9 9955HX, 16 cores and 32 threads, 59 GiB of memory (a 16-core desktop-class build machine; not a user's machine); operating system: unknown; Rust toolchain: unknown; user's machine: no +- Settings that can change the result: search mode as named in the figures + +## Figures + +| Row | Figure | Unit | Previous figure and its date | +|---|---|---|---| +| indexed, three passes, recall | 115.926, 116.138, 114.075 and 1.0000 | ms | 126.9, 127.5, 126.6 (before the last fixes, 2026-11-14) | +| exact, three passes | 856.9, 874.4, 864.0 | ms | not recorded | +| indexed with a second sort key, three passes, recall | 119.851, 118.685, 118.939 and 1.0000 | ms | 129.3, 129.4, 128.9 (before the last fixes, 2026-11-14) | +| indexed with a rank policy, three passes, recall | 123.584, 116.221, 116.177 and 0.9900 | ms | 129.9, 126.9, 127.6 (before the last fixes, 2026-11-14) | + +## Limitations + +- The recall of the ranked search is against the plain exact search; recall against the ranked exact search is not measured at this size. +- Time figures are of this machine only; no timed figure is a promise. diff --git a/docs/performance/results/2026-11-14-import-rate.md b/docs/performance/results/2026-11-14-import-rate.md new file mode 100644 index 000000000..aae20932e --- /dev/null +++ b/docs/performance/results/2026-11-14-import-rate.md @@ -0,0 +1,31 @@ +# Performance result: import rate on a 16-core desktop-class machine, 2026-11-14 + +## Promise + +- Promise, in the product's words: "A large import therefore runs only as fast as maintenance keeps up, and a search made in the middle of it stays fast". No figure promised. +- Counted test that guards it: none yet. + +## Measurement + +- Date: 2026-11-14; revision measured: `0c708a979e9eb5cbb1dca142f514edf96656711e` for the rows of the first group, which come from the 100,008-passage, 62,447-command and sightings programs of five runs (the median of the five printed); the rows marked "not taken again" keep the figures of `7f150eed3afb284c2c02220431c3cb858635f361` +- Program and command: the load lines of `v2/numbers.sh` (`million_rows_load`, `passages_100008_load`, `synthetic_1000000_*`, `anchors_62447_load`) +- Data: as named in each row; 500 rows to a commit +- Machine: AMD Ryzen 9 9955HX, 16 cores and 32 threads, 59 GiB of memory (a 16-core desktop-class build machine; not a user's machine); operating system: unknown; Rust toolchain: unknown; user's machine: no + +## Figures + +| Row | Figure | Unit | Previous figure and its date | +|---|---|---|---| +| 1,000,000 small rows loaded under a 64 MiB limit (not taken again) | 11.3 | s | 10.7, 2026-11-12 | +| 100,008 passages loaded | 3.5 | s | 3.5, 2026-11-14 (`090d140ec`) | +| 138,084 rows of 62,447 commands loaded | 12.6 | s | 12.7, 2026-11-14 (`090d140ec`) | +| 1,000,000 sightings loaded | 35.3 | s | 35.2, 2026-11-14 (`090d140ec`) | +| those sightings sealed, 245 cycles | 15.4 | s | 15.5, 2026-11-14 (`090d140ec`) | +| those sightings grouped, 1,123 cycles | 343.4 | s | 343.5, 2026-11-14 (`090d140ec`) | +| 1,000,000 generated vectors loaded (not taken again) | 27.0 | s | 26.5 to 27.1, 2026-11-12 | +| those vectors sealed, 245 cycles (not taken again) | 20.4 | s | 25.7, 2026-11-12 | +| those vectors grouped, 1,150 cycles (not taken again) | 348.6 | s | 365.8, 2026-11-12 | + +## Limitations + +- A search made during the import is not measured yet; no limit on the vectors a search compares one by one exists yet. diff --git a/docs/performance/results/2026-11-14-one-commit.md b/docs/performance/results/2026-11-14-one-commit.md new file mode 100644 index 000000000..4357e3bf3 --- /dev/null +++ b/docs/performance/results/2026-11-14-one-commit.md @@ -0,0 +1,25 @@ +# Performance result: the cost of one commit on a 16-core desktop-class machine, 2026-11-14 + +## Promise + +- Promise, in the product's words: "Rows, relationships, vectors and the index state built from them commit together or not at all". No figure promised for its speed. +- Counted test that guards it: `a_kill_at_any_storage_call_of_a_commit_leaves_all_or_nothing` and `a_kill_inside_a_commit_of_vectors_keeps_rows_and_vectors_together` (`v2/contextdb/tests/crash/main.rs`) stop the process at every storage call of a commit and check that all of it or none of it is there. + +## Measurement + +- Date: 2026-11-14; revision measured: `0c708a979e9eb5cbb1dca142f514edf96656711e`, five runs, the median of the five printed +- Program and command: the `readme_*` lines of `v2/numbers.sh` (`measure readme`) +- Data: 20,000 notes of 1.6 KB, one commit per row +- Machine: AMD Ryzen 9 9955HX, 16 cores and 32 threads, 59 GiB of memory (a 16-core desktop-class build machine; not a user's machine); operating system: unknown; Rust toolchain: unknown; user's machine: no + +## Figures + +| Row | Figure | Unit | Previous figure and its date | +|---|---|---|---| +| 20,000 commits of one row | 28.0 | s | 27.9, 2026-11-14 (`090d140ec`); 11.1, 2026-11-14 (`7f150eed3`, a run in another folder) | +| the store they leave | 2.0 | MiB | 2.0, 2026-11-14 (`090d140ec`) | + +## Limitations + +- The time is of this machine only; no timed figure is a promise. +- The merged code (`4495faf1a`) took 27.6 to 29.9 s in the same five runs, so the engine did not slow it; the earlier 11.1 s was taken by `numbers.sh` in another folder, and the cause of the difference was not looked for. diff --git a/docs/performance/results/2026-11-14-store-size.md b/docs/performance/results/2026-11-14-store-size.md new file mode 100644 index 000000000..f296807da --- /dev/null +++ b/docs/performance/results/2026-11-14-store-size.md @@ -0,0 +1,31 @@ +# Performance result: store size against its data on a 16-core desktop-class machine, 2026-11-14 + +## Promise + +- Promise, in the product's words: "after maintenance, a store that has been written to and expired for any length of time takes at most twice the bytes of the data it holds now"; "Reference stores are measured against that limit at every release". +- Counted test that guards it: `a_store_with_twelve_indexes_stays_under_twice_its_bytes_and_under_its_recorded_size` (`v2/contextdb/tests/long_keys.rs`; 4,000 rows, 12 indexes; 1.76 times its data on 2026-11-13) and `two_hundred_rows_of_50_000_byte_indexed_values_make_a_store_smaller_than_twice_their_bytes` (same file). None yet for a store written and expired over time. + +## Measurement + +- Date: 2026-11-14 for the figures of `numbers.sh` (taken again at the head, five runs: the sizes are the same to the printed digit); 2026-11-13 for the stores of the layout landing list +- Revision measured: `0c708a979e9eb5cbb1dca142f514edf96656711e` for the rows taken again, `7f150eed3afb284c2c02220431c3cb858635f361` for those marked "not taken again"; the layout landing list is of `5f069d73cbb90c52c6f3775ccaef53ad59c454ab`, the merged layout commit +- Program and command: the size lines of `v2/numbers.sh`; `size_over_held` is the store's bytes over the bytes of the values put in +- Data: as named in each row +- Machine: AMD Ryzen 9 9955HX, 16 cores and 32 threads, 59 GiB of memory (a 16-core desktop-class build machine; not a user's machine); operating system: unknown; Rust toolchain: unknown; user's machine: no + +## Figures + +| Row | Figure | Unit | Previous figure and its date | +|---|---|---|---| +| 62,447 commands, 15 indexes | 270.8 MiB, 1.59 | MiB; times its data | 560.6 MiB, 3.29 (2026-11-12) | +| 100,008 passages, 13 indexes | 471.8 MiB, 1.58 | MiB; times its data | 471.8 MiB, 1.58 (2026-11-12) | +| the declared-find store of 100,008 passages | 527.6 MiB, 1.72 | MiB; times its data | 632.8 MiB, 2.06 (2026-11-12) | +| 165,855 passages | 766.3 MiB, 1.55 | MiB; times its data | not recorded | +| 173 session files (not taken again) | 214.5 MiB, 0.62 | MiB; times its data | 227.9 MiB, 0.66 (2026-11-12) | +| 1,000,000 generated vectors, sealed and grouped (not taken again) | 4,991.9 MiB, 1.70 | MiB; times its data | 5,302.9 MiB, 1.81 (2026-11-12) | +| 1,000,000 sightings | 4,990.0 MiB, 1.70 | MiB; times its data | 4,990.0 MiB, 1.70 (2026-11-14 (`090d140ec`) | + +## Limitations + +- Not within the promise: a small store rewritten whole by a few large commits keeps free space the size of its data (24,000 rows in 4 commits: 3.3 times its data, 5.1 times before the layout fix; it stops growing); rows of about 264 bytes with 12 indexes are 2.7 times their data. +- The engine does not yet report how much disk each table takes. diff --git a/docs/performance/results/TEMPLATE.md b/docs/performance/results/TEMPLATE.md index f4192eccd..6b4dae7ab 100644 --- a/docs/performance/results/TEMPLATE.md +++ b/docs/performance/results/TEMPLATE.md @@ -1,121 +1,42 @@ -Kind: `` · Status: `` +# Performance result: on , -# Performance result: on , +Copy this file to `docs/performance/results/.md` and fill every `<...>` from a +measurement. A row of [the bars](../README.md#the-bars-of-the-engine-in-v2) takes its last figure from +here. - +Rules: -Copy this file to `docs/performance/results/.md` and replace every -`<…>` from reviewed values only. See -[the guide](../README.md#publishing-a-result-manual). +- **Never invent a value.** A field that was not recorded is `unknown`; one that does not apply is + `not applicable`, with the reason. +- **A figure is not a promise.** The promise is the product's own words, copied from its root + document, or "no figure promised". +- **A speed or size promise names the test that guards it by counting work**, or says "none yet". +- **Name the machine** (processor, cores, memory) and say whether it is a user's machine. +- Never paste hostnames, user names, absolute paths or secrets. -Rules for filling it in: +## Promise -- **The first line is mandatory.** Kind and Status come before anything else, - and the same Kind and Status open this entry's line in the guide's index. - `historical` entries also keep the banner above. -- **Public only.** Never paste raw receipts, logs, absolute paths, hostnames, - user names, cgroup paths or secrets. Raw material stays private. -- **Never invent a value.** If a field was not recorded, write `unknown`; if it - does not apply, write `not applicable` and say why. A guessed number is not - an answer. -- **Descriptive is not acceptance.** Numbers go in the descriptive table, which - has no acceptance threshold and no verdict. Only a row quoted verbatim from - [the guide's acceptance thresholds](../README.md#acceptance-bars) goes in the - acceptance table. A benchmark assertion, a source budget or a completed run - is never an acceptance verdict. -- **Unknown is not a pass.** An acceptance row that was not run is `NOT RUN`; - one whose run does not match the row's scope, or whose provenance is partly - unknown, is `NOT EVIDENCE`. -- **Failed and partial runs are worth recording.** A historical run without a - paired baseline, or a run that stopped early, is published with that - limitation stated, not withheld. +- Promise, in the product's words: `` +- Counted test that guards it: `` -## Classification +## Measurement -- Kind: `` — historical means measured - before this template existed and reconstructed from what was kept. -- Measured by: ``; reviewed by: `` -- Run date: `` -- Run status: `` — failed: a - command exited non-zero; incomplete: stopped, timed out or only partly kept. +- Date: ``; revision measured: `` +- Program and command: `` +- Data: `` +- Passes and statistic: ``; threads: ``; memory limit: `` +- Machine: ``; operating system: `<...>`; user's machine: `` +- Settings that can change the result: `` -## Source +## Figures -- Paired comparison: `` -- Baseline: ``, or `not available: ` -- Candidate / measured revision: ``, or `unknown` -- Profile: `>` +| Row | Figure | Unit | Previous figure and its date | +|---|---|---|---| +| `` | `` | `` | `` | -## Workload and configuration - -Write `not applicable` for a field the benchmark does not have. - -- Fixture / dataset: ``; size: `` -- Input dimension: ``; concurrency: `` -- Features and settings: `` -- Repetitions / samples: ``; warm or cold: `` -- Build configuration: `` -- Exact command used (verbatim, with local paths replaced by placeholders): - `` - -## Environment - -- Hardware (public label): `` -- Filesystem and storage configuration (public): `` -- OS / kernel: `<…>` -- Toolchain: `` -- Resource limits: `` -- Isolation: `` - -## Scope - -- Benchmark targets expected: ``; completed: `` -- Selected: ``; not run: ``; filters: `` -- A single-profile or filtered run is a partial, descriptive measurement of - that area, never a global performance pass. - -## Acceptance (quoted acceptance thresholds only) - -One row per acceptance row this entry reports on. Quote the row from -[the guide's acceptance thresholds](../README.md#acceptance-bars) verbatim, with its -number, statistic and scope. If the entry reports on none, write "None -reported." and leave the table out. - -| Acceptance row (quoted verbatim) | Verdict | Evidence and coverage | -|---|---|---| -| `<"…" — the exact row text>` | `` | `` | - -## Descriptive measurements (no acceptance threshold and no verdict) - -| Target / benchmark | Statistic | Unit | Baseline | Candidate | Change | -|---|---|---|---|---|---| -| `<…>` | `` | `<…>` | `` | `` | `` | - -Notes (one line for any row that is not a straightforward paired value): - -- ``: `` - -## Missing metadata - -Tick what is not known; if any box is ticked, provenance is partly unknown and -no acceptance row may be `PASS` on the strength of this entry. - -- [ ] Baseline revision -- [ ] Measured revision -- [ ] Run date -- [ ] Workload / fixture identity -- [ ] Hardware, OS or toolchain -- [ ] Resource limits or isolation -- [ ] Full list of targets that ran -- [ ] Exact command - -Provenance: `` +For a search, also give recall (the share of the true ten nearest found) and the number of +questions it was taken over. For a size, give the data's own size beside the store's. ## Limitations -- `` -- `` - -Raw receipts kept privately by: `` +- `` diff --git a/scripts/ci-local.py b/scripts/ci-local.py index fdb7b7d5e..94ecfc05b 100755 --- a/scripts/ci-local.py +++ b/scripts/ci-local.py @@ -1,11 +1,11 @@ #!/usr/bin/env python3 """Run the pull-request workflow on this machine, each job in a box shaped like a hosted runner. - python3 scripts/ci-local.py [--tree DIR] [--work DIR] [--tmp DIR] [--out DIR] [--boxes N] - [--only REGEX] [--base SHA] [--path-prepend DIR ...] + python3 scripts/ci-local.py [--workflow FILE] [--tree DIR] [--work DIR] [--tmp DIR] [--out DIR] + [--boxes N] [--only REGEX] [--base SHA] [--path-prepend DIR ...] The job graph, matrices, `if:` conditions, `env:` blocks, outputs and `run:` steps are read from -.github/workflows/ci.yml at run time and executed the way a GitHub-hosted runner executes them for a +the workflow (.github/workflows/ci.yml, or check.yml for the packages under v2/) at run time and executed the way a GitHub-hosted runner executes them for a pull_request event: jobs start when their `needs` finish, matrix legs run concurrently, step outputs, GITHUB_ENV and GITHUB_PATH flow between steps, `continue-on-error` and step outcomes behave as on GitHub. A workflow construct this script does not model (an unknown action, expression @@ -38,7 +38,8 @@ Artifacts are kept by name under --work, so the shared-build jobs pack their target once and the test jobs restore it, as on GitHub. Hosted chores that need root (`sudo`, apt) are skipped and -listed; the tools they install must already be on PATH. The build cache action restores nothing +listed; the tools they install must already be on PATH, and so must each tool the tool-install +action names (its version is not checked). The build cache action restores nothing here, so a job GitHub serves from a warm cache compiles cold here. When `build-any` is on PATH every box step is admitted through it (the shared build-host @@ -46,7 +47,7 @@ Output in --out: jobs.tsv (job, name, result, cause, minutes in the box, peak memory, peak disk), steps.tsv, logs/, not-run.tsv and result.txt. Exit status 0 when the final required job passed, -1 when it did not, 3 on workflow drift, 130 when stopped by SIGINT/SIGTERM (the report is still +1 when it did not (a workflow without a `required` job: when every job passed), 3 on workflow drift, 130 when stopped by SIGINT/SIGTERM (the report is still written; unfinished jobs are marked interrupted). """ import argparse @@ -67,7 +68,6 @@ import yaml -WORKFLOW = '.github/workflows/ci.yml' BOX_CPUS = 4 # Free memory the shared parent slice must have before another box step starts. STEP_HEADROOM = 8 * 1024 ** 3 @@ -79,7 +79,7 @@ DISK_POLL_SECONDS = 20 SLICE = 'cilocal.slice' KNOWN_ACTIONS = ('actions/checkout', 'actions-rust-lang/setup-rust-toolchain', 'Swatinem/rust-cache', - 'actions/upload-artifact', 'actions/download-artifact') + 'actions/upload-artifact', 'actions/download-artifact', 'taiki-e/install-action') # Hosted-runner chores that need root; the tools they install must already be present here. ROOT_CHORE = re.compile(r'\bsudo\b|\bapt-get\b') # Commands that never compile; every other step is admitted through the build-host wrapper. @@ -505,6 +505,11 @@ def action(self, step, name): if action == 'actions/download-artifact': return self.run.download(self, to_str(w.get('name') or ''), to_str(w.get('pattern') or ''), to_str(w.get('path') or '.'), name) + if action == 'taiki-e/install-action': + path = self.run.base_env(self)['PATH'] + missing = [t for t in re.split(r'[,\s]+', to_str(w.get('tool'))) if t and not shutil.which(t.split('@')[0], path=path)] + self.run.note(self, name, f'tools missing from PATH: {missing}' if missing else 'tools taken from PATH') + return not missing raise Drift(f'unsupported action {uses!r}') # -- run: steps @@ -613,7 +618,7 @@ def __init__(self, a): self.stop_file = self.work / 'STOP' self.t0 = time.time() self.artifacts = self.work / 'artifacts' - self.doc = yaml.safe_load((self.tree / WORKFLOW).read_text()) + self.doc = yaml.safe_load((self.tree / a.workflow).read_text()) self.default_shell = ((self.doc.get('defaults') or {}).get('run') or {}).get('shell', 'bash') def git(self, *args, cwd=None): @@ -1012,7 +1017,8 @@ def report(self, total): line = f'DRIFT {self.drift}' code = 3 else: - final = self.needs.get('required', {}).get('result', 'missing') + final = (self.needs['required']['result'] if 'required' in self.doc['jobs'] else + 'success' if all(n['result'] in ('success', 'skipped') for n in self.needs.values()) else 'failure') failed = sorted(r[1] for r in rows if r[2] != 'success') line = f'{"PASS" if final == "success" else "FAIL"} required={final} jobs={len(rows)} not-success={len(failed)}' code = 0 if final == 'success' else 1 @@ -1137,6 +1143,7 @@ def main(): box_main(sys.argv[2:]) here = Path(__file__).resolve().parents[1] p = argparse.ArgumentParser(description=__doc__.split('\n')[0]) + p.add_argument('--workflow', default='.github/workflows/ci.yml', help='workflow file, relative to the tree') p.add_argument('--tree', default=str(here), help='checkout to run (default: this repository)') p.add_argument('--work', default=os.environ.get('CI_LOCAL_WORK', str(here / 'target/ci-local/work')), help='per-run box checkouts, targets and artifacts') diff --git a/v2/AGENTS.md b/v2/AGENTS.md index 9b7f51232..d66af2da1 100644 --- a/v2/AGENTS.md +++ b/v2/AGENTS.md @@ -23,7 +23,7 @@ The library is twelve parts, one folder each under `contextdb/src/`: | `sql` | grammar, parser, planner: text to a statement, a statement to a plan; reads every table option and column constraint (including `STATE MACHINE`, `PROPAGATE`, `CONTEXT_ID`, `SCOPE_LABEL`, `ACL` and the `ALTER TABLE` forms); `sql::formula` reads a rank formula, the one reading of it | touches storage or knows what a table holds | | `store` | the folder and data file, how each record is keyed, a row's large text, JSON and vectors kept beside the row in slices (text and JSON compressed there when that saves an eighth, `store/record.rs`), views of one moment, the reader files (one in `readers/` per reader that is inside a statement, naming the commit it reads) and the locks | interprets SQL or a table's rules | | `schema` | table declarations: checking, storing, printing them back; the `Rules` of a table (references, immutable columns, propagation, the Context, label and access columns, counts) worked out once from its declaration, and `ALTER TABLE` and `DROP` (`schema/alter.rs`) with the refusals of what a change would leave dangling | changes a row | -| `query` | answers a SELECT from one table; holds the one expression evaluator and the one filter of who may see a row (`Reader`, `Visible`, in `query/visible.rs` with its tests in `query/visible/`); a narrowed `Reader` is handed to every read and every search; counts the rows it reads and a search's distance evaluations; answers `SHOW VECTOR_INDEXES`, `SHOW VECTOR_PARTITIONS` and `explain` (which takes the `Reader`) from the vector part's small records | changes anything | +| `query` | answers a SELECT (joins, grouping, set operations, subqueries, graph patterns and a vector search included) and `EXPLAIN` of any statement; holds the one expression evaluator and the one filter of who may see a row (`Reader`, `Visible`, in `query/visible.rs` with its tests in `query/visible/`); a narrowed `Reader` is handed to every read and every search; counts the rows it reads and a search's distance evaluations; answers `SHOW VECTOR_INDEXES`, `SHOW VECTOR_PARTITIONS` and `explain` (which takes the `Reader`) from the vector part's small records | changes anything | | `write` | applies INSERT, UPDATE and DELETE to a change set; checks types, NOT NULL, the primary key (also the hidden key of a table with none) and UNIQUE rules, `IMMUTABLE`, the state machine, references both ways, a `DAG`, and the rows a `PROPAGATE` moves in the same statement; asks `Visible` whether the handle may write the row; keeps index entries and row counts; checks at commit what only the whole transaction answers (`write/commit.rs`) | returns a query's result to a caller | | `database` | the handle a store is opened for writing with, the handles narrowed from it (`scoped_with_constraints`), the refusal of a statement by the kind of handle (`Database::execute` refuses what `Plan::admin_only` names when the `Reader` is narrowed; the Rust call `set_memory_limit` makes the same refusal; `run_maintenance_cycle` does not look at the narrowing), its transactions and their numbers, row guards, the one commit function (where two transactions' conflicts are decided: first commit wins, no waiting); `table_meta` and `declaration`; `run_maintenance_cycle` (the sealing commit, then one step for every partition with work, each worked out with no lock held and committed through the one commit function); `explain` | has a second way to commit | | `read` | a session that reads a store without holding it for writing, from any process; its `explain` | changes anything a writer stored | @@ -64,7 +64,7 @@ A part reaches another only through what that part makes visible: the `pub(crate | `Asked`, `EvalContext`, `reads`; `Visible::new`, `Visible::reads`, `Visible::may_write`, `Reader::admin` | `query` | `write` is also handed these to evaluate and to ask who may write; from `store` it uses `Beside`, `Entry`, `EntryShape`, `KEY_LIMIT`, `RowGuard`, `View` and `CountId`, and from `schema` the fields of `Table` | | `QueryResult` | `query` | `database` and `read` build it and hand it to the caller | | `PhysicalPlan::VectorSearch`; `Expr::Distance`, `Expr::Row`, `Expr::InList` | `sql` | `query` runs the search, puts its distance wherever the select list writes `<=>`, and evaluates `IN` lists and row values | -| `VectorColumn` (a VECTOR column's number, partition key, limit, mode, quantization, `AUTO_INDEX_AT` and consolidation, with the numbers in force), from `Table::vectors`, `Table::vector` and `Catalog::vector` | `schema` | `query`, `write` and `vector` | +| `VectorColumn` (a VECTOR column's number, partition key, limit, mode, quantization, `INDEXING_THRESHOLD` and compaction, with the numbers in force), from `Table::vectors`, `Table::vector` and `Catalog::vector` | `schema` | `query`, `write` and `vector` | | `staged`, `vectors` and `vector_number` on `Read`; `put_vector`, `delete_vector` and `put_vector_number` on `ChangeSet`; `VectorRecord`, `VectorNumber`, `VectorId` | `store` | `vector` reads and stages its blocks, waiting entries, partition entries and counts through them; `store` keeps them and never interprets one | | `search`, `plan`, `Nearest`, `Route`, `distance` | `vector` | `query` calls `search` with the partitions the filter selects, the mode in force, the column's declaration and whether the statement has a filter on rows, and answers it, row by row, with `distance` of the row's stored vector, or with nothing for a row that is gone, filtered out or has no vector; `search` answers nothing at all only when INDEXED is refused (a selected partition is not usable, or a filter on rows leaves the index nothing to choose among), which `query` turns into the refusal. `plan` settles what a search does with each partition, from small records alone, and `search` runs exactly that plan, so `explain` cannot disagree with it | | `Tally`, the partitions a transaction has started and emptied | `vector` | `database` holds one beside each change set and forgets a refused statement's part of it; `write` notes every row it stages, including the rows a propagation moves, and settles the tally once per statement after following, which is where a statement over `MAX_PARTITIONS` is refused; `vector::tally::tuples` decides which rows have an entry (none for a row in an `EXCLUDE VECTOR` state, with a NULL vector, or missing) | @@ -100,7 +100,7 @@ Every path in this guide is written from `v2/`. | A partition with no grouping, a grouping of one group, or sketches that cannot tell its vectors apart is searched as an exact search searches it; below its size a column pays for no index | `contextdb/tests/vectors_index.rs`: `a_column_below_its_size_pays_nothing_and_is_searched_whole`, `a_grouping_whose_sketches_cannot_tell_its_vectors_apart_answers_as_exact` | | On the fixed vectors of the tests an indexed search counts fewer distance evaluations than an exact one (on other data it can count more, each an eighth of the bytes), reads sketches before blocks, and never costs more row visits than an exact one | `contextdb/tests/vectors_index.rs`: `an_indexed_search_does_fewer_distance_evaluations_than_exact`, `an_indexed_search_reads_sketches_before_blocks`, `an_indexed_search_that_takes_every_group_does_the_exact_evaluations` | | INDEXED is refused by name, before the filter would be asked of the whole table, when a partition is far behind its writes or a filter leaves the index nothing to choose among; AUTO is never refused for a grouping and answers exactly where one is behind or damaged | `contextdb/tests/vectors_index.rs`: `indexed_is_refused_whole_when_one_partition_is_behind`, `an_indexed_search_short_of_its_limit_is_refused_before_the_whole_table_is_read`, `an_indexed_search_whose_first_pass_takes_every_slot_is_refused_before_a_row_is_asked`, `auto_answers_exactly_where_a_grouping_is_behind_or_damaged`; `contextdb/src/vector/tests.rs`: `auto_answers_exactly_where_a_grouping_is_damaged` | -| AUTO is exact until the selected partitions hold `AUTO_INDEX_AT` vectors, then indexed in each partition that has a grouping and is not behind | `contextdb/tests/vectors_index.rs`: `auto_uses_groupings_from_auto_index_at_on`, `auto_searches_each_partition_by_what_its_grouping_saves` | +| AUTO is exact until the selected partitions hold `INDEXING_THRESHOLD` vectors, then indexed in each partition that has a grouping and is not behind | `contextdb/tests/vectors_index.rs`: `auto_uses_groupings_from_indexing_threshold_on`, `auto_searches_each_partition_by_what_its_grouping_saves` | | A write after a grouping is found at once, before any cycle and after sealing | `contextdb/tests/vectors_index.rs`: `writes_after_a_grouping_are_found_at_once` | | A grouping is built in bounded cycles and switched in by one commit; the old grouping serves until then, and a write or search runs between any two cycles | `contextdb/tests/vectors_upkeep.rs`: `a_grouping_is_built_in_bounded_cycles_and_switched_in_one`; `contextdb/tests/transactions.rs`: `a_statement_commits_while_a_cycle_works_out_a_step` | | Every block of a grouping, and every block sealed after the partition's mean exists, has a sketch for each slot; the index takes the bytes the layout says | `contextdb/tests/vectors_upkeep.rs`: `a_grouping_keeps_a_sketch_of_every_slot_and_measures_its_width`, `sealing_after_a_grouping_keeps_a_sketch_of_every_slot` | @@ -148,11 +148,11 @@ Every path in this guide is written from `v2/`. - A test goes through a public call of the library or through the built program, never an inner item. - SQL behaviour is a script under `contextdb/tests/sql/` with its expected output; tests that kill a process and reopen the store live in `contextdb/tests/crash/`. -- A unit test of one pure function may sit beside it in a file named `tests.rs`. -- A test asserts states, values, error kinds and counts, never a duration, and waits only on something a process announces. +- An inner test, in a file named `tests.rs` under `src/`, exists only for pure arithmetic or for bytes damaged on disk that no public call can write. When a fix round is green, tests that overlap are merged, as cases of one table, before the branch lands. +- A test asserts states, values, error kinds and counts. It never decides by elapsed time and never sleeps to wait: it waits for an event a process announces, or reads a count. Every promised speed or size is guarded by a test that counts the work (rows read, distances worked out, bytes), never one that times it. - Its data is fixed, and each test has its own store folder (`support::folder` in `contextdb/tests/support/mod.rs`). - Nothing is retried (`.config/nextest.toml` sets `retries = 0`) and no test is ignored. -- The check holds every test but slow work. Slow work is listed in the `nightly` profile of `.config/nextest.toml` and runs once a night in the check's scheduled run. A test that nears its limit on a hosted runner does less work or, when the size is the promise, moves there. +- The whole pull-request check finishes within thirty minutes on a hosted runner, macOS included. The check holds every test but slow work. Slow work is listed in the `nightly` profile of `.config/nextest.toml` and runs once a night in the check's scheduled run. A test that nears its limit on a hosted runner does less work or, when the size is the promise, moves there. Two lint settings hold this up: @@ -185,10 +185,13 @@ around it. Before writing a line: The check holds the line where no judgement is needed (`.github/workflows/check.yml`): -- It states the size of the shipped code, rounded up to 500 lines, and the number of tests, - rounded up to 10. A change that crosses either edits the number in the same change, and - says why in its description; a change that removes enough lowers it. Neither number ever - passes 150,000 lines or 1,000 tests. +- It states three sizes: `SHIPPED_LINES` (the shipped code, rounded up to 500 lines), `TESTS` + (the tests, rounded up to 10) and `TEST_LINES` (the lines of tests, rounded up to 500). Each + holds from both sides, at most the number and within one rounding of it, so a cleanup + lowers it for good. Reaching one means a refactor first. A number is raised only when a + planned stage of the work ends, by the maintainer who owns the plan, against that stage's + planned size, never inside a fix. The rewrite is planned at about 62,000 shipped lines and + 550 tests; the outer walls are 150,000 lines and 1,000 tests. - It refuses a shipped file longer than 1,500 lines, a test-only name in shipped code, an ignored test, and an `allow` attribute beyond the four named below. - The lint settings above refuse a sleep, a thread, a clock read, a random id and a walk diff --git a/v2/Cargo.lock b/v2/Cargo.lock index e6bb3b9d2..1f26cb144 100644 --- a/v2/Cargo.lock +++ b/v2/Cargo.lock @@ -158,6 +158,7 @@ dependencies = [ "lz4_flex", "pest", "pest_derive", + "serde", "serde_json", "uuid", ] @@ -431,6 +432,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", + "serde_derive", ] [[package]] @@ -546,6 +548,7 @@ checksum = "bed99139f7dac9b5cfe5f17be4d66dc7079a34dee1d74bcc77217119240e267c" dependencies = [ "getrandom", "js-sys", + "serde_core", "wasm-bindgen", ] diff --git a/v2/README.md b/v2/README.md index d97ad9dcb..e011a929b 100644 --- a/v2/README.md +++ b/v2/README.md @@ -27,10 +27,10 @@ cargo +1.89 check --manifest-path v2/Cargo.toml --workspace --locked ``` The last line checks the oldest Rust the packages declare (`rustup toolchain install 1.89` -first). The workflow also states the size of the library and the program, rounded up to 500 -lines, and the number of tests, rounded up to 10, and fails when either is passed or is no -longer within that distance: a change that grows or shrinks the code past a boundary edits -the number in the workflow file, in the same change. It also refuses a shipped file longer +first). The workflow also states three sizes: the library and the program in lines rounded up to 500 +(`SHIPPED_LINES`), the tests in number rounded up to 10 (`TESTS`) and the lines of tests rounded +up to 500 (`TEST_LINES`). It fails when one is passed or is no longer within that distance, and +`AGENTS.md` says when a number may be moved. It also refuses a shipped file longer than 1,500 lines, a test-only name in shipped code, an ignored test and an `allow` attribute beyond the four `AGENTS.md` names. `AGENTS.md` says how a change is made so that these hold. diff --git a/v2/contextdb-cli/src/output.rs b/v2/contextdb-cli/src/output.rs index 8635c326d..9fa885452 100644 --- a/v2/contextdb-cli/src/output.rs +++ b/v2/contextdb-cli/src/output.rs @@ -283,7 +283,9 @@ pub fn table(columns: &[String], rows: &[Vec]) -> String { let line = |cells: &[String]| { let mut line = String::from("|"); for (cell, width) in cells.iter().zip(&widths) { - line.push_str(&format!(" {cell: \\d Show a table's declaration as SQL.", - ".explain Show how a similarity search would be answered, without running it.", + ".explain Show the path a statement would take, without running it.", "SHOW VECTOR_INDEXES; SHOW VECTOR_PARTITIONS; Describe the VECTOR columns and their partitions.", ".help \\? Show this list.", ".quit \\q End the session.", diff --git a/v2/contextdb-cli/tests/shell.rs b/v2/contextdb-cli/tests/shell.rs index 36999879c..fa7843cb8 100644 --- a/v2/contextdb-cli/tests/shell.rs +++ b/v2/contextdb-cli/tests/shell.rs @@ -82,6 +82,21 @@ fn arg(path: &Path) -> &str { path.to_str().unwrap() } +/// A read shell over `store`. +fn run_read(dir: &Path, store: &Path, input: impl AsRef<[u8]>) -> Run { + shell(dir, &[arg(store)], input) +} + +/// A read-write shell over `store`. +fn run_write(dir: &Path, store: &Path, input: impl AsRef<[u8]>) -> Run { + shell(dir, &[arg(store), "--write"], input) +} + +/// A read shell over `store` that prints JSON documents. +fn run_json(dir: &Path, store: &Path, input: impl AsRef<[u8]>) -> Run { + shell(dir, &[arg(store), "--json"], input) +} + /// Every line of a stream as a JSON document. fn documents(stream: &str) -> Vec { stream @@ -172,7 +187,7 @@ fn reading_a_missing_store_is_refused_and_creates_nothing() { let dir = folder("reading-a-missing-store"); let store = dir.join("store"); - let run = shell(&dir, &[arg(&store)], SELECT_NOTES); + let run = run_read(&dir, &store, SELECT_NOTES); assert_eq!(run.code, Some(1), "{}", run.stderr); assert_eq!(run.stdout, ""); assert!( @@ -192,7 +207,7 @@ fn reading_a_missing_store_is_refused_and_creates_nothing() { let broken = dir.join("broken"); std::fs::create_dir_all(broken.join("data")).unwrap(); for (path, kind) in [(&store, "store_not_found"), (&broken, "store_io")] { - let run = shell(&dir, &[arg(path), "--json"], SELECT_NOTES); + let run = run_json(&dir, path, SELECT_NOTES); assert_eq!(run.code, Some(1), "{}", run.stderr); assert_eq!(run.stdout, ""); let refusals = documents(&run.stderr); @@ -217,11 +232,7 @@ fn write_creates_a_missing_store() { let store = dir.join("store"); let insert = "INSERT INTO notes (id, body) VALUES (1, 'first');\n"; - let run = shell( - &dir, - &[arg(&store), "--write"], - format!("{CREATE_NOTES}{insert}"), - ); + let run = run_write(&dir, &store, format!("{CREATE_NOTES}{insert}")); assert_eq!(run.code, Some(0), "{}", run.stderr); assert_eq!(run.errors(), Vec::<&str>::new()); assert!( @@ -235,17 +246,13 @@ fn write_creates_a_missing_store() { ); // It was a whole read-write session: the next shell reads what it wrote. - let run = shell(&dir, &[arg(&store)], SELECT_NOTES); + let run = run_read(&dir, &store, SELECT_NOTES); assert_eq!(run.code, Some(0), "{}", run.stderr); assert_eq!(run.stdout, ONE_NOTE); // On a store that is there, --write opens it and keeps what it holds. let insert = "INSERT INTO notes (id, body) VALUES (2, 'second');\n"; - let run = shell( - &dir, - &[arg(&store), "--write"], - format!("{insert}{SELECT_NOTES}"), - ); + let run = run_write(&dir, &store, format!("{insert}{SELECT_NOTES}")); assert_eq!(run.code, Some(0), "{}", run.stderr); assert!(run.stdout.contains(TWO_NOTES), "{}", run.stdout); } @@ -369,7 +376,7 @@ SELECT nope FROM notes; INSERT INTO notes (id, body) VALUES (2, 'second'); SELECT COUNT(*) AS n FROM notes; "; - let run = shell(&dir, &[arg(&store), "--write"], input); + let run = run_write(&dir, &store, input); // A statement may span lines, a command is one line, and every result is on the output. let first = run @@ -419,7 +426,7 @@ SELECT COUNT(*) AS n FROM notes; assert_eq!(run.code, Some(1)); // A run in which every statement succeeded exits 0 and prints its results and nothing else. - let run = shell(&dir, &[arg(&store)], SELECT_NOTES); + let run = run_read(&dir, &store, SELECT_NOTES); assert_eq!(run.code, Some(0), "{}", run.stderr); assert_eq!(run.stdout, TWO_NOTES); @@ -456,7 +463,7 @@ SELECT COUNT(*) AS n FROM notes; let mut input = script.as_bytes().to_vec(); input.extend_from_slice(b"\xff\xfe\n"); input.extend_from_slice(b"INSERT INTO notes (id, body) VALUES (11, 'after');\nCOMMIT;\n"); - let run = shell(&dir, &[arg(&store), "--write"], input); + let run = run_write(&dir, &store, input); assert_eq!( run.code, Some(1), @@ -470,7 +477,7 @@ SELECT COUNT(*) AS n FROM notes; "the refusal must name the line that cannot be decoded, line {line}: {}", run.stderr ); - let run = shell(&dir, &[arg(&store)], "SELECT COUNT(*) AS n FROM notes;\n"); + let run = run_read(&dir, &store, "SELECT COUNT(*) AS n FROM notes;\n"); assert!( run.stdout.contains(&format!("| {kept} |")), "only the statements before the undecodable line stand ({kept} notes): {}", @@ -541,11 +548,7 @@ fn a_read_shell_refuses_a_write_by_name() { let dir = folder("a-read-shell-refuses-a-write"); let store = dir.join("store"); let insert = "INSERT INTO notes (id, body) VALUES (1, 'first');\n"; - let made = shell( - &dir, - &[arg(&store), "--write"], - format!("{CREATE_NOTES}{insert}"), - ); + let made = run_write(&dir, &store, format!("{CREATE_NOTES}{insert}")); assert_eq!(made.code, Some(0), "{}", made.stderr); let writes = "\ @@ -557,7 +560,7 @@ BEGIN; "; // Each of the five is refused, telling the person what to add, and the read after them // answers with the row as it was. - let run = shell(&dir, &[arg(&store)], format!("{writes}{SELECT_NOTES}")); + let run = run_read(&dir, &store, format!("{writes}{SELECT_NOTES}")); assert_eq!(run.code, Some(1)); assert_eq!(run.errors().len(), 5, "{}", run.stderr); assert!( @@ -569,7 +572,7 @@ BEGIN; assert!(!run.stdout.contains("ok ("), "{}", run.stdout); // A program reads the refusal's kind. - let run = shell(&dir, &[arg(&store), "--json"], writes); + let run = run_json(&dir, &store, writes); assert_eq!(run.code, Some(1)); let refusals: Vec = documents(&run.stderr) .into_iter() @@ -584,11 +587,7 @@ BEGIN; } // Nothing was written: one row, one table. - let run = shell( - &dir, - &[arg(&store), "--json"], - format!("{SELECT_NOTES}.tables\n"), - ); + let run = run_json(&dir, &store, format!("{SELECT_NOTES}.tables\n")); assert_eq!(run.code, Some(0), "{}", run.stderr); let results = documents(&run.stdout); assert_eq!( @@ -618,8 +617,18 @@ fn a_read_shell_answers_while_a_writer_holds_the_store() { ) .unwrap(); + // The same for a similarity search: from [1, 0, 0] row 1 is at distance 1 and row 2 at 2. + for sql in [ + "CREATE TABLE passages (id INTEGER PRIMARY KEY, embedding VECTOR(3))", + "INSERT INTO passages (id, embedding) VALUES (1, [0.0, 1.0, 0.0]), (2, [-1.0, 0.0, 0.0])", + ] { + writer.execute(sql, ¶ms! {}).unwrap(); + } + let search = "SELECT id, embedding <=> [1.0, 0.0, 0.0] AS distance FROM passages \ + ORDER BY distance LIMIT 2;\n"; + // The store really is held: a second writer is refused, naming this process. - let second = shell(&dir, &[arg(&store), "--write"], SELECT_NOTES); + let second = run_write(&dir, &store, SELECT_NOTES); assert_eq!(second.code, Some(1), "{}", second.stderr); assert!( second.stderr.contains(&std::process::id().to_string()), @@ -628,20 +637,37 @@ fn a_read_shell_answers_while_a_writer_holds_the_store() { ); // A read shell needs nothing from the writer and answers. - let run = shell(&dir, &[arg(&store)], SELECT_NOTES); + let run = run_read(&dir, &store, SELECT_NOTES); assert_eq!(run.code, Some(0), "{}", run.stderr); assert_eq!(run.stdout, ONE_NOTE); + let run = run_read(&dir, &store, search); + assert_eq!(run.code, Some(0), "{}", run.stderr); + assert_eq!(nearest(&tables(&run.stdout)[0]), [(1, 1.0), (2, 2.0)]); - // The writer was not held up by it, and the next read shell reads its next commit. + // The writer was not held up by it, and the next read shell reads its next commit, in which + // row 3 is the nearest. + writer + .execute( + "INSERT INTO passages (id, embedding) VALUES (3, [1.0, 0.0, 0.0])", + ¶ms! {}, + ) + .unwrap(); writer .execute( "INSERT INTO notes (id, body) VALUES (2, 'second')", ¶ms! {}, ) .unwrap(); - let run = shell(&dir, &[arg(&store)], SELECT_NOTES); + let run = run_read(&dir, &store, SELECT_NOTES); assert_eq!(run.code, Some(0), "{}", run.stderr); assert_eq!(run.stdout, TWO_NOTES); + let run = run_read(&dir, &store, search); + assert_eq!( + nearest(&tables(&run.stdout)[0]), + [(3, 0.0), (1, 1.0)], + "{}", + run.stdout + ); writer.close().unwrap(); } @@ -663,7 +689,7 @@ SELECT id FROM notes ORDER BY id; ROLLBACK; SELECT id, body FROM notes ORDER BY id; "; - let run = shell(&dir, &[arg(&store), "--write"], input); + let run = run_write(&dir, &store, input); assert_eq!(run.code, Some(0), "{}", run.stderr); assert_eq!(run.errors(), Vec::<&str>::new()); @@ -681,15 +707,15 @@ SELECT id, body FROM notes ORDER BY id; assert!(seen_inside < seen_after); // The committed transaction reached the store, and the rolled-back one never did. - let run = shell(&dir, &[arg(&store)], SELECT_NOTES); + let run = run_read(&dir, &store, SELECT_NOTES); assert_eq!(run.code, Some(0), "{}", run.stderr); assert_eq!(run.stdout, TWO_NOTES); // As in Postgres, BEGIN inside a transaction and COMMIT or ROLLBACK outside one each warn on // the error stream and the run still ends well, so a script that lost its BEGIN is told. - let run = shell( + let run = run_write( &dir, - &[arg(&store), "--write"], + &store, "BEGIN;\nBEGIN;\nCOMMIT;\nCOMMIT;\nROLLBACK;\n", ); assert_eq!(run.code, Some(0), "{}", run.stderr); @@ -728,11 +754,11 @@ CREATE TABLE notes ( ); "; let authors = "CREATE TABLE authors (id UUID PRIMARY KEY, name TEXT);\n"; - let made = shell(&dir, &[arg(&store), "--write"], format!("{notes}{authors}")); + let made = run_write(&dir, &store, format!("{notes}{authors}")); assert_eq!(made.code, Some(0), "{}", made.stderr); // `.tables` lists the names in order, one a line. - let tables = shell(&dir, &[arg(&store)], ".tables\n"); + let tables = run_read(&dir, &store, ".tables\n"); assert_eq!(tables.code, Some(0), "{}", tables.stderr); let names: Vec<&str> = tables .stdout @@ -741,26 +767,23 @@ CREATE TABLE notes ( .collect(); assert_eq!(names, ["authors", "notes"], "{}", tables.stdout); - let schema = shell(&dir, &[arg(&store)], ".schema notes\n"); + let schema = run_read(&dir, &store, ".schema notes\n"); assert_eq!(schema.code, Some(0), "{}", schema.stderr); assert_eq!(schema.stdout, notes); // Each command has a short spelling that prints the same. - assert_eq!(shell(&dir, &[arg(&store)], "\\dt\n").stdout, tables.stdout); - assert_eq!( - shell(&dir, &[arg(&store)], "\\d notes\n").stdout, - schema.stdout - ); + assert_eq!(run_read(&dir, &store, "\\dt\n").stdout, tables.stdout); + assert_eq!(run_read(&dir, &store, "\\d notes\n").stdout, schema.stdout); // What `.schema` printed declares the same table again in another store. let copy = dir.join("copy"); - let made = shell(&dir, &[arg(©), "--write"], &schema.stdout); + let made = run_write(&dir, ©, &schema.stdout); assert_eq!(made.code, Some(0), "{}", made.stderr); - assert_eq!(shell(&dir, &[arg(©)], ".schema notes\n").stdout, notes); + assert_eq!(run_read(&dir, ©, ".schema notes\n").stdout, notes); // A command used wrongly prints how it is used, never that it is unknown. for (input, command) in [(".schema\n", ".schema"), (".tables extra\n", ".tables")] { - let run = shell(&dir, &[arg(&store)], input); + let run = run_read(&dir, &store, input); let usage = run.stderr.lines().find(|line| line.starts_with("Usage:")); assert!( usage.is_some_and(|line| line.contains(command)), @@ -820,7 +843,7 @@ fn the_memory_limit_option_is_the_sessions_ceiling() { "startup_ceiling", "ceiling_refresh_failures", ]; - let run = shell(&dir, &[arg(&store), "--json"], "SHOW MEMORY_LIMIT;\n"); + let run = run_json(&dir, &store, "SHOW MEMORY_LIMIT;\n"); assert_eq!(run.code, Some(0), "{}", run.stderr); assert_eq!( documents(&run.stdout)[0]["result"]["columns"], @@ -918,11 +941,7 @@ VALUES (1, 'a', [1.0, 0.0, 0.0]), (2, 'a', [0.0, 1.0, 0.0]), (3, 'b', [-1.0, 0.0 let rows = "SELECT id, v FROM t ORDER BY id;\n"; // Declared, written and searched in one piped write session. - let run = shell( - &dir, - &[arg(&store), "--write"], - format!("{declare}{search}{rows}"), - ); + let run = run_write(&dir, &store, format!("{declare}{search}{rows}")); assert_eq!(run.code, Some(0), "{}", run.stderr); assert_eq!(run.errors(), Vec::<&str>::new()); let printed = tables(&run.stdout); @@ -948,7 +967,7 @@ VALUES (1, 'a', [1.0, 0.0, 0.0]), (2, 'a', [0.0, 1.0, 0.0]), (3, 'b', [-1.0, 0.0 assert_eq!(printed[1][5], ["5", "[0.1, 0.2, 0.3]"], "{}", run.stdout); // For a program the distance is a number, a vector an array of numbers and no vector null. - let run = shell(&dir, &[arg(&store), "--json"], format!("{search}{rows}")); + let run = run_json(&dir, &store, format!("{search}{rows}")); assert_eq!(run.code, Some(0), "{}", run.stderr); let results = documents(&run.stdout); assert_eq!(results.len(), 2, "{}", run.stdout); @@ -979,7 +998,7 @@ VALUES (1, 'a', [1.0, 0.0, 0.0]), (2, 'a', [0.0, 1.0, 0.0]), (3, 'b', [-1.0, 0.0 // `.schema` prints the VECTOR column with its clauses in the order they are declared in, // and with the limit of 256 partitions that a key declared without one has. - let schema = shell(&dir, &[arg(&store)], ".schema t\n"); + let schema = run_read(&dir, &store, ".schema t\n"); assert_eq!(schema.code, Some(0), "{}", schema.stderr); let words = schema .stdout @@ -994,21 +1013,18 @@ VALUES (1, 'a', [1.0, 0.0, 0.0]), (2, 'a', [0.0, 1.0, 0.0]), (3, 'b', [-1.0, 0.0 // What it printed declares the same table again in another store. let copy = dir.join("copy"); - let made = shell(&dir, &[arg(©), "--write"], &schema.stdout); + let made = run_write(&dir, ©, &schema.stdout); assert_eq!(made.code, Some(0), "{}", made.stderr); - assert_eq!( - shell(&dir, &[arg(©)], ".schema t\n").stdout, - schema.stdout - ); + assert_eq!(run_read(&dir, ©, ".schema t\n").stdout, schema.stdout); } #[test] fn an_indexed_search_runs_through_the_program() { let dir = folder("an-indexed-search-runs"); let store = dir.join("store"); - let made = shell( + let made = run_write( &dir, - &[arg(&store), "--write"], + &store, "CREATE TABLE passages (id INTEGER PRIMARY KEY, embedding VECTOR(3));\n\ INSERT INTO passages (id, embedding) VALUES (1, [0.0, 1.0, 0.0]), (2, [1.0, 0.0, 0.0]);\n", ); @@ -1045,19 +1061,19 @@ fn an_indexed_search_runs_through_the_program() { ); } - // Two vectors outside any grouping under AUTO_INDEX_AT 1: the index is behind its writes, + // Two vectors outside any grouping under INDEXING_THRESHOLD 1: the index is behind its writes, // and INDEXED is refused by name rather than answered as an exact scan. let behind = dir.join("behind"); - let made = shell( + let made = run_write( &dir, - &[arg(&behind), "--write"], - "CREATE TABLE behind (id INTEGER PRIMARY KEY, v VECTOR(3) AUTO_INDEX_AT 1);\n\ + &behind, + "CREATE TABLE behind (id INTEGER PRIMARY KEY, v VECTOR(3) INDEXING_THRESHOLD 1);\n\ INSERT INTO behind (id, v) VALUES (1, [1.0, 0.0, 0.0]), (2, [0.0, 1.0, 0.0]);\n", ); assert_eq!(made.code, Some(0), "{}", made.stderr); - let run = shell( + let run = run_json( &dir, - &[arg(&behind), "--json"], + &behind, search("INDEXED") .replace("passages", "behind") .replace("embedding", "v"), @@ -1082,68 +1098,30 @@ VALUES (1, 'a', [1.0, 0.0, 0.0]), (2, 'a', [0.0, 1.0, 0.0]), (3, 'b', [-1.0, 0.0 "; /// The fields of `SHOW VECTOR_INDEXES`, in the order they are printed. -const INDEX_FIELDS: [&str; 31] = [ - "table", - "column", - "dimension", - "quantization", - "vector_count", - "bytes", - "partition_key_columns", - "max_partitions", - "live_partitions", - "search_mode", - "declared_auto_index_at", - "effective_auto_index_at", - "declared_consolidation_mode", - "declared_consolidation_change_percent", - "declared_consolidation_tombstone_percent", - "effective_consolidation_mode", - "effective_consolidation_change_percent", - "effective_consolidation_tombstone_percent", - "pending_inserts", - "tombstones", - "durable_vector_bytes", - "durable_index_bytes", - "indexed_available", - "maintenance_state", - "maintenance_vectors_total", - "maintenance_vectors_done", - "maintenance_vectors_remaining", - "unavailable_partitions", - "stalled_partitions", - "broad_route", - "recovery_action", -]; +const INDEX_FIELDS: &str = "\ +table column dimension quantization vector_count bytes partition_key_columns \ +max_partitions live_partitions search_mode declared_indexing_threshold \ +effective_indexing_threshold declared_compaction_mode \ +declared_compaction_change_percent declared_compaction_tombstone_percent \ +effective_compaction_mode effective_compaction_change_percent \ +effective_compaction_tombstone_percent pending_tuples tombstones \ +durable_vector_bytes durable_index_bytes indexed_available maintenance_state \ +maintenance_vectors_total maintenance_vectors_done maintenance_vectors_remaining \ +unavailable_partitions stalled_partitions broad_route recovery_action"; /// The fields of `SHOW VECTOR_PARTITIONS`, in the order they are printed. -const PARTITION_FIELDS: [&str; 18] = [ - "table", - "column", - "partition_key", - "live_rows", - "pending_inserts", - "tombstones", - "durable_vector_bytes", - "durable_index_bytes", - "indexed_available", - "availability_reason", - "maintenance_state", - "maintenance_reason", - "maintenance_vectors_total", - "maintenance_vectors_done", - "maintenance_vectors_remaining", - "lists", - "probes", - "recovery_action", -]; +const PARTITION_FIELDS: &str = "\ +table column partition_key live_rows pending_tuples tombstones durable_vector_bytes \ +durable_index_bytes indexed_available availability_reason maintenance_state \ +maintenance_reason maintenance_vectors_total maintenance_vectors_done \ +maintenance_vectors_remaining lists probes recovery_action"; #[test] fn vector_inspection_prints_one_field_to_a_line() { let dir = folder("vector-inspection-prints"); let store = dir.join("store"); let more = "CREATE TABLE other (id INTEGER PRIMARY KEY, w VECTOR(2));\n"; - let made = shell(&dir, &[arg(&store), "--write"], format!("{KINDS}{more}")); + let made = run_write(&dir, &store, format!("{KINDS}{more}")); assert_eq!(made.code, Some(0), "{}", made.stderr); // Each statement with the fields it prints and, for each row, the values of three of them. @@ -1154,17 +1132,18 @@ fn vector_inspection_prints_one_field_to_a_line() { ["other", "w", "{}"], ]; let cases = [ - ("SHOW VECTOR_INDEXES;\n", &INDEX_FIELDS[..], &indexes[..]), + ("SHOW VECTOR_INDEXES;\n", INDEX_FIELDS, &indexes[..]), ( "SHOW VECTOR_PARTITIONS;\n", - &PARTITION_FIELDS[..], + PARTITION_FIELDS, &partitions[..], ), ]; for (statement, fields, rows) in cases { + let fields: Vec<&str> = fields.split(' ').collect(); // For a person: rows with an empty line between them, each `name: value` lines in the // statement's order, and no line too long for a terminal. - let run = shell(&dir, &[arg(&store)], statement); + let run = run_read(&dir, &store, statement); assert_eq!(run.code, Some(0), "{}", run.stderr); assert!( run.stdout.lines().all(|line| line.chars().count() <= 120), @@ -1194,7 +1173,7 @@ fn vector_inspection_prints_one_field_to_a_line() { } // For a program: the usual result document, its columns the same names. - let run = shell(&dir, &[arg(&store), "--json"], statement); + let run = run_json(&dir, &store, statement); assert_eq!(run.code, Some(0), "{}", run.stderr); let results = documents(&run.stdout); assert_eq!(results.len(), 1, "{}", run.stdout); @@ -1209,7 +1188,7 @@ fn vector_inspection_prints_one_field_to_a_line() { fn explain_prints_how_each_partition_is_searched() { let dir = folder("explain-prints"); let store = dir.join("store"); - let made = shell(&dir, &[arg(&store), "--write"], KINDS); + let made = run_write(&dir, &store, KINDS); assert_eq!(made.code, Some(0), "{}", made.stderr); // Four vectors in two partitions, far below the 100,000 from which AUTO uses a grouping, @@ -1219,7 +1198,7 @@ fn explain_prints_how_each_partition_is_searched() { let lines = [ "requested_mode: AUTO", "resolved_mode: EXACT", - "effective_auto_index_at: 100000", + "effective_indexing_threshold: 100000", "aggregate_allowed_vectors: 4", r#"partition_key_columns: ["kind"]"#, "partitions: 2", @@ -1228,13 +1207,13 @@ fn explain_prints_how_each_partition_is_searched() { " lists: *", " probes: *", " live_rows: 2", - " outside_grouping: 2", + " unindexed_rows: 2", r#"partition: {"kind":"b"}"#, " route: exact", " lists: *", " probes: *", " live_rows: 2", - " outside_grouping: 2", + " unindexed_rows: 2", "refusal: none", ]; let same = |printed: &[&str]| { @@ -1248,7 +1227,7 @@ fn explain_prints_how_each_partition_is_searched() { let search = ".explain SELECT id FROM notes ORDER BY v <=> '[1,0,0]' LIMIT 3\n"; // The lines and nothing else: the search is not run, so no table of rows is printed. - let run = shell(&dir, &[arg(&store)], search); + let run = run_read(&dir, &store, search); assert_eq!(run.code, Some(0), "{}", run.stderr); assert!( same(&run.stdout.lines().collect::>()), @@ -1256,10 +1235,10 @@ fn explain_prints_how_each_partition_is_searched() { run.stdout ); - // Any other statement is refused in one line, and the session goes on to the next. - let other = ".explain SELECT id FROM notes ORDER BY id\n"; + // A statement that reads no stored table is refused in one line; the session goes on. + let other = ".explain SELECT 1\n"; let next = "SELECT id FROM notes WHERE id = 5;\n"; - let run = shell(&dir, &[arg(&store)], format!("{other}{next}")); + let run = run_read(&dir, &store, format!("{other}{next}")); assert_eq!(run.code, Some(1), "{}", run.stderr); let refusals: Vec<&str> = run.stderr.lines().collect(); assert_eq!(refusals.len(), 1, "{}", run.stderr); @@ -1274,7 +1253,7 @@ fn explain_prints_how_each_partition_is_searched() { assert_eq!(tables(&run.stdout), [[["id"], ["5"]]], "{}", run.stdout); // For a program: one document that holds the same lines. - let run = shell(&dir, &[arg(&store), "--json"], search); + let run = run_json(&dir, &store, search); assert_eq!(run.code, Some(0), "{}", run.stderr); let results = documents(&run.stdout); assert_eq!(results.len(), 1, "{}", run.stdout); @@ -1288,66 +1267,91 @@ fn explain_prints_how_each_partition_is_searched() { } #[test] -fn help_lists_explain() { - let dir = folder("help-lists-explain"); +fn explain_prints_the_path_of_a_statement_and_runs_nothing() { + let dir = folder("explain-prints-the-path"); let store = dir.join("store"); - let made = shell(&dir, &[arg(&store), "--write"], CREATE_NOTES); + let declare = "\ +CREATE TABLE notes (id INTEGER PRIMARY KEY, tag TEXT); +CREATE INDEX notes_tag ON notes (tag); +INSERT INTO notes (id, tag) VALUES (1, 'a'), (2, 'b'); +"; + let made = run_write(&dir, &store, declare); assert_eq!(made.code, Some(0), "{}", made.stderr); - let run = shell(&dir, &[arg(&store)], ".help\n"); - assert_eq!(run.code, Some(0), "{}", run.stderr); + + // The path of a read, in the words the library documents. + let read = run_read( + &dir, + &store, + ".explain SELECT id FROM notes WHERE tag = 'a'\n", + ); + assert_eq!(read.code, Some(0), "{}", read.stderr); + assert_eq!(read.errors(), Vec::<&str>::new()); + for words in ["IndexScan { index: notes_tag }", "predicates_pushed: [tag]"] { + assert!( + read.stdout.contains(words), + "no `{words}` in:\n{}", + read.stdout + ); + } + + // The path of a write is printed and the write is not made, in a session that may write. + let asked = run_write( + &dir, + &store, + ".explain DELETE FROM notes WHERE id = 1\nSELECT COUNT(*) AS n FROM notes;\n", + ); + assert_eq!(asked.code, Some(0), "{}", asked.stderr); + assert_eq!(asked.errors(), Vec::<&str>::new()); assert!( - run.stdout.lines().any(|line| line.starts_with(".explain")), + asked.stdout.contains("IndexScan { index: __pk_id }"), "{}", - run.stdout + asked.stdout ); -} - -#[test] -fn a_read_shell_searches_while_a_writer_holds_the_store() { - let dir = folder("a-read-shell-searches-while-a-writer-holds"); - let store = dir.join("store"); - - // This test is the writer, and holds the store until the end. From [1, 0, 0] row 1 is at - // distance 1 and row 2 at 2. - let writer = Database::open(&store).unwrap(); - for sql in [ - "CREATE TABLE passages (id INTEGER PRIMARY KEY, embedding VECTOR(3))", - "INSERT INTO passages (id, embedding) VALUES (1, [0.0, 1.0, 0.0]), (2, [-1.0, 0.0, 0.0])", - ] { - writer.execute(sql, ¶ms! {}).unwrap(); - } - let search = "SELECT id, embedding <=> [1.0, 0.0, 0.0] AS distance FROM passages \ - ORDER BY distance LIMIT 2;\n"; + let counted = tables(&asked.stdout); + let count = counted.last().expect("the count is printed"); + assert_eq!(count.last().unwrap(), &["2"], "{}", asked.stdout); - // The store really is held: a second writer is refused, naming this process. - let second = shell(&dir, &[arg(&store), "--write"], search); - assert_eq!(second.code, Some(1), "{}", second.stderr); + // The command is listed in the help. + let help = run_read(&dir, &store, ".help\n"); assert!( - second.stderr.contains(&std::process::id().to_string()), + help.stdout.lines().any(|line| line.starts_with(".explain")), "{}", - second.stderr + help.stdout ); +} - // A read shell needs nothing from the writer: it searches and gets the rows. - let run = shell(&dir, &[arg(&store)], search); - assert_eq!(run.code, Some(0), "{}", run.stderr); - let printed = tables(&run.stdout); - assert_eq!(printed.len(), 1, "{}", run.stdout); - assert_eq!(nearest(&printed[0]), [(1, 1.0), (2, 2.0)], "{}", run.stdout); +#[test] +fn a_cell_70000_characters_wide_is_printed_without_a_panic() { + let dir = folder("a-cell-70000-characters-wide"); + let store = dir.join("store"); - // The writer was not held up by it, and the next read shell searches its next commit, in - // which row 3 is the nearest. + // This test is the writer, and holds the store until the end; the shell reads beside it. + let writer = Database::open(&store).unwrap(); writer .execute( - "INSERT INTO passages (id, embedding) VALUES (3, [1.0, 0.0, 0.0])", + "CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT)", ¶ms! {}, ) .unwrap(); - let run = shell(&dir, &[arg(&store)], search); - assert_eq!(run.code, Some(0), "{}", run.stderr); - let printed = tables(&run.stdout); - assert_eq!(printed.len(), 1, "{}", run.stdout); - assert_eq!(nearest(&printed[0]), [(3, 0.0), (1, 1.0)], "{}", run.stdout); + writer + .execute( + "INSERT INTO notes (id, body) VALUES ($id, $body)", + ¶ms! { "id" => 4_242_421_i64, "body" => "x".repeat(70_000) }, + ) + .unwrap(); - writer.close().unwrap(); + // `shell` itself fails the test on a panic; a panic also ends the program with 101. + let run = run_read(&dir, &store, SELECT_NOTES); + assert_eq!(run.code, Some(0), "{}", run.stderr); + assert_eq!(run.errors(), Vec::<&str>::new()); + // The row is printed: its other cell is there, however the wide one is shown. + assert!( + run.stdout.contains("4242421"), + "the row's id is not in the {} bytes printed", + run.stdout.len() + ); + assert!( + run.stdout.contains("(1 row)"), + "no count of rows is printed" + ); } diff --git a/v2/contextdb/Cargo.toml b/v2/contextdb/Cargo.toml index 111a7b5b3..c9c47e173 100644 --- a/v2/contextdb/Cargo.toml +++ b/v2/contextdb/Cargo.toml @@ -13,9 +13,10 @@ lz4_flex = { version = "0.14", default-features = false, features = ["std", "saf pest = "2.8.6" pest_derive = "2.8.6" redb = { package = "contextdb-redb", version = "4.1.0", path = "../redb" } +serde = { version = "1", features = ["derive"] } # Numbers in a stored JSON value are read back exactly as they were written. serde_json = { version = "1", features = ["float_roundtrip"] } -uuid = { version = "1", features = ["v4"] } +uuid = { version = "1", features = ["v4", "serde"] } [lints] workspace = true diff --git a/v2/contextdb/README.md b/v2/contextdb/README.md index bcad79879..9bbeaa06e 100644 --- a/v2/contextdb/README.md +++ b/v2/contextdb/README.md @@ -14,21 +14,23 @@ This is the first version of contextdb 2. What it has: may move through, edges that may not close a cycle, rows that follow a change of another row; - who may see and write a row: Contexts, scope labels and principals; - `ALTER TABLE`, `DROP TABLE` and `DROP INDEX`; -- `INSERT` (also `ON CONFLICT ... DO UPDATE`), `UPDATE`, `DELETE` and `SELECT` over one table; +- `INSERT` (also `ON CONFLICT ... DO UPDATE`), `UPDATE`, `DELETE` and `SELECT`, which joins + tables, groups, takes `WITH`, `UNION`, subqueries, `ROW_NUMBER()` and a pattern over a table + of edges (`GRAPH_TABLE`); - vector search: the rows nearest a vector by cosine distance, each with its distance, over vectors that a column may keep in partitions; exact on request, and through an index that - `run_maintenance_cycle` builds and brings up to date once a column holds many vectors; + `run_maintenance_cycle` builds and brings up to date once a column holds many vectors; a + search can be ranked by a formula the column declares (`USE RANK`); +- `EXPLAIN` of any `SELECT`, `INSERT`, `UPDATE` or `DELETE`, which says how it would be answered; - transactions, whose conflicts are decided when they commit; - one process writing a store while any number of other processes read it; - a memory limit that holds. -What it does not have yet: joins, grouping, graph patterns, ranked search (`USE RANK`) and sync -between machines; the statements that use them are listed under Statements, and each is refused -and changes nothing. Some clauses are accepted, kept and printed back by `.schema`, and nothing -acts on them yet: `RETAIN` (no row expires), `HISTORY`, `SYNC`, `SYNC CONFLICT`, -`DELIVERY MANIFEST`, `EDGE DISCARD` and `RANK_POLICY` (which only keeps `ALTER` from dropping or -renaming a column it reads); so is an index on a JSON field, `CREATE INDEX name ON table ((column -> 'key'))`: -writes to its table are accepted and pass over it, and no query reads it. `table_meta` reports `RETAIN`, `HISTORY`, `SYNC` and `SYNC CONFLICT`. +What it does not have yet: sync between machines, recursive queries, and the SQL named under +Statements as refused; each of those is refused and changes nothing. Some clauses are accepted, +kept and printed back by `.schema`, and nothing acts on them yet: `RETAIN` (no row expires), +`HISTORY`, `SYNC`, `SYNC CONFLICT`, `DELIVERY MANIFEST` and `EDGE DISCARD`. `table_meta` +reports `RETAIN`, `HISTORY`, `SYNC` and `SYNC CONFLICT`. It is not on crates.io yet. Clone and use it from that checkout: @@ -76,7 +78,7 @@ fn main() -> contextdb::Result<()> { It prints `buy oat milk: 0.006` and then `call the plumber: 1.000`. Call `db.close()?` when you are done, as the later programs do: it lets the store go at once, and every later call on the -handle returns `DatabaseClosed`. After writing vectors, a host calls `db.run_maintenance_cycle()?` +handle that can fail returns `DatabaseClosed` (the four that return a plain value panic; see Refusals). After writing vectors, a host calls `db.run_maintenance_cycle()?` again and again (see Upkeep under Vector search), because this version does not do it by itself; a search before that still finds every vector, and reads more to do it. This page is also the crate's documentation, and the documentation tests compile this program as it is written here. @@ -93,12 +95,12 @@ CREATE TABLE [IF NOT EXISTS] name ( [CONTEXT_ID] [SCOPE_LABEL ('label', ...) | SCOPE_LABEL_READ ('label', ...) WRITE ('label', ...)] [ACL REFERENCES table (column)] - [RANK_POLICY (JOIN table ON column, FORMULA 'formula', SORT_KEY key)], + [RANK_POLICY (JOIN table ON column, FORMULA 'formula', SORT_KEY name)], column VECTOR(n) [WITH (quantization = 'F32' | 'SQ8')] -- F32 when left out [PARTITION_KEY (column, ...) [MAX_PARTITIONS m]] -- m is 256 when left out [SEARCH_MODE AUTO | EXACT | INDEXED] - [AUTO_INDEX_AT a] -- a is 100000 when left out - [CONSOLIDATION NONE | CONSOLIDATION (CHANGE_PERCENT = c, TOMBSTONE_PERCENT = t)], + [INDEXING_THRESHOLD a] -- a is 100000 when left out + [COMPACTION NONE | COMPACTION (CHANGE_PERCENT = c, TOMBSTONE_PERCENT = t)], ..., [PRIMARY KEY (column, ...)], [UNIQUE (column, ...)], @@ -126,18 +128,27 @@ ALTER TABLE table SET RETAIN ... | SET HISTORY ... | SET SYNC ... | SET SYNC CON | SET MAINTAIN COUNT ...; ALTER TABLE table DROP RETAIN; ALTER TABLE table ALTER COLUMN column SET MAX_PARTITIONS m | SET SEARCH_MODE mode - | SET AUTO_INDEX_AT a | SET AUTO_INDEX_AT DEFAULT - | SET CONSOLIDATION NONE | SET CONSOLIDATION (CHANGE_PERCENT = c, TOMBSTONE_PERCENT = t) - | SET CONSOLIDATION DEFAULT; + | SET INDEXING_THRESHOLD a | SET INDEXING_THRESHOLD DEFAULT + | SET COMPACTION NONE | SET COMPACTION (CHANGE_PERCENT = c, TOMBSTONE_PERCENT = t) + | SET COMPACTION DEFAULT; DROP TABLE [IF EXISTS] table; DROP INDEX [IF EXISTS] name ON table; INSERT INTO table (column, ...) VALUES (value, ...), (value, ...) [ON CONFLICT (column, ...) DO UPDATE SET column = value, ...]; UPDATE table SET column = value, ... [WHERE condition]; DELETE FROM table [WHERE condition]; -SELECT column, ... | * FROM table [WHERE condition] [ORDER BY column [ASC | DESC], ...] [LIMIT n]; +[WITH name AS (select), ...] +SELECT [DISTINCT] expression [AS name], ... | * [FROM table [alias] + [[INNER | LEFT] JOIN table [alias] ON condition | CROSS JOIN table [alias]] ...] + [WHERE condition] [GROUP BY expression, ...] [HAVING condition] + [UNION [ALL] SELECT ...] + [ORDER BY expression [ASC | DESC], ...] [LIMIT n] [OFFSET m]; +SELECT ... FROM GRAPH_TABLE(edge_table MATCH (a)-[:TYPE]->{1,n}(b) [WHERE condition] + COLUMNS (a.id AS name, b.id AS name, depth AS name)); SELECT column, ... | * FROM table [WHERE condition] - ORDER BY column <=> vector [USE VECTOR AUTO | EXACT | INDEXED] LIMIT k; + ORDER BY column <=> vector [USE VECTOR AUTO | EXACT | INDEXED] [USE RANK name] [LIMIT k] [OFFSET m]; + -- USE RANK needs a LIMIT +EXPLAIN select | insert | update | delete; SET MEMORY_LIMIT 512M; SET MEMORY_LIMIT NONE; SHOW MEMORY_LIMIT; SHOW VECTOR_INDEXES; SHOW VECTOR_PARTITIONS [FOR table.column] [LIMIT count [OFFSET start]]; @@ -145,30 +156,86 @@ SHOW VECTOR_PARTITIONS [FOR table.column] [LIMIT count [OFFSET start]]; - A default is a literal or `NOW()`. A table, column or index name written without quotes is folded to lower case, as in Postgres; a state or an edge type is a value and is kept as written. -- A condition or a value is built from column names, literals, `$name` values, - `= != <> < <= > >=`, `AND`, `OR`, `NOT`, `IS NULL`, `IS NOT NULL`, `+ - * /`, - parentheses and `NOW()`. A comparison with NULL is not true, as in standard SQL. +- A condition or a value is built from column names (`table.column` or `alias.column` when + tables are joined), literals, `$name` values, `= != <> < <= > >=`, `AND`, `OR`, `NOT`, + `IS NULL`, `IS NOT NULL`, `+ - * /`, parentheses, `NOW()` and `COALESCE(a, b, ...)`; no + other function is read. A comparison with NULL is not true, as in standard SQL. + `x LIKE 'a%'` and `NOT LIKE` match text (`%` any run, `_` one character, backslash escapes + either), and `x BETWEEN a AND b` and `NOT BETWEEN` include both ends. A JSON column is read + with `->` (the field as JSON) and `->>` (the field as text). JSON values compare by value, + so `5` equals `5.0`, and sort as Postgres `jsonb` sorts them: null, string, number, boolean, + array, object; an array or an object by its size first; an object's keys shorter first, then + by their bytes. `<` and `>` between JSON values are refused. A statement nests at most 64 + levels of parentheses, `NOT`, unary minus and subqueries; one deeper is a `ParseError`. + An index over a field, `CREATE INDEX name ON table ((column -> 'key'))`, answers a condition on + that field and follows the rows it indexes. - `x IN (a, b, ...)` and `x NOT IN (a, b, ...)` test a value against a list, and `(x, y) IN ((a, b), (c, d), ...)` tests several columns at once, both as standard SQL has - them. A list is written out: `IN (SELECT ...)` is refused. -- `SELECT` also takes `COUNT(*)`, `COUNT(column)`, `SUM`, `MIN` and `MAX` over the rows that - match, and `AS` to name a column of the result. + them. `x IN (SELECT ...)` and `(SELECT ...)` as one value take a subquery that does not read + the outer row; one that does, and `EXISTS`, are refused (`SubqueryNotSupported`). +- `SELECT` takes `COUNT(*)`, `COUNT(column)`, `SUM`, `MIN`, `MAX` and `AVG`, with `GROUP BY` and + `HAVING`, `DISTINCT`, and `AS` to name a column of the result. `ORDER BY` takes any + expression of the select list or the table; `LIMIT` and `OFFSET` take a number or a `$name`. +- `INNER JOIN`, `LEFT JOIN` and `CROSS JOIN` join tables, each table with an optional alias. + `RIGHT JOIN`, `FULL JOIN` and a second table after a comma are refused. `FROM` takes a table + name or a `GRAPH_TABLE`; a subquery there (`FROM (SELECT ...) AS x`) is a `ParseError`, and + `WITH x AS (SELECT ...) SELECT ... FROM x` gives the same rows. +- `UNION` and `UNION ALL` join the answers of several `SELECT`s, and `ORDER BY`, `LIMIT` and + `OFFSET` after the last apply to the whole; `UNION` drops repeated rows and `UNION ALL` keeps them. `INTERSECT` and `EXCEPT` are refused. +- `WITH name AS (select)` names an answer for the statement that follows; `WITH RECURSIVE` is + refused (`RecursiveCteNotSupported`). +- `ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)` is the one window function; any other is + refused (`WindowFunctionNotSupported`). +- **Names in a result.** A column is named by its `AS`; without one, a column by its own name, + a function by its name (`ROW_NUMBER()` is `row_number`, `COUNT(*)` is `count`), and a + subquery that gives one item by that item (`SELECT *` gives `?column?`). A bare `ORDER BY` name that the select list gives is that output column; one that + two different items give, as in `SELECT t.id, id FROM t ORDER BY id`, is refused as ambiguous + (`PlanError`), where Postgres answers. The same `SELECT` item written twice in `GROUP BY`, `DISTINCT` or `ORDER BY` is one expression. +- **A whole number and a REAL** are compared by exact value, not as two doubles: a stored + 9007199254740992.0 is not equal to 9007199254740993, which Postgres calls equal. The two differ only + past 2^53, and equality stays transitive across `UNION`, `GROUP BY` and `DISTINCT`. Text + quoted into a `UUID` or `TIMESTAMP` column is read as one, and any other comparison of unlike + types is refused when the statement is read, whatever the table holds. +- **`GRAPH_TABLE(edge_table MATCH (a)-[:TYPE]->{1,n}(b) ... COLUMNS (...))`** is a pattern over a + table of edges (`source_id`, `target_id`, `edge_type`). With one step and no range it gives a + row for each matching edge; with a range `{m,n}` it walks along matching edges and reports + each node once, at the shallowest `depth` it is reached in, whether the filter names no start + (every node is then a start), one or several (a start a cycle leads back to is reported too); `<-` and `-` (either way) + follow an edge against the arrow or from either end. A walk is at most 10 steps + (`BfsDepthExceeded`); a step with no upper bound is refused (`UnboundedTraversal`), and so is a + label on a node and a pattern with no `COLUMNS`. A pattern stands alone in `FROM`; to join it + to a table, name it in a `WITH` first. +- `ORDER BY ... USE RANK name` orders a search by the formula of the `RANK_POLICY` of the column whose `SORT_KEY` is `name`, + highest first, before the `LIMIT` and `OFFSET`. It needs a vector order and a `LIMIT` + (`UseRankRequiresVectorOrder`, `UseRankRequiresLimit`), and a rank the column does not + declare is refused (`RankPolicyNotFound`). +- `EXPLAIN` before a `SELECT`, `INSERT`, `UPDATE` or `DELETE` prints how it would be answered + and does nothing else: an explained write changes no row. It refuses a statement exactly as + the statement would be refused for what is wrong in the statement itself (an unknown column, + a number of values that does not match the columns, an `ON CONFLICT` rule the table cannot + keep), and not what only its rows would be refused for. A statement with two faults is + refused for either one. A `$name` with no value is refused by name (`no value is bound to + $name`, as a run refuses it), except a search's vector, which needs no value, and a parameter beside a key + column, which gives `partitions: every partition ($name is not bound)`. A bound value of the + wrong type or width, and a table with an access list and no principal (`PrincipalRequired`), + are refused as a run refuses them. + What a similarity search prints is described under [Vector search](#vector-search). - `ORDER BY` puts NULL last ascending and first descending. -- The second `SELECT` is a vector search, and the clauses of a `VECTOR` column and the two - `SHOW` statements are described under [Vector search](#vector-search). +- The vector search form, the clauses of a `VECTOR` column and the two `SHOW` statements are + described under [Vector search](#vector-search). - `--` and `/* */` comments are read past. - The library has one way to run a transaction, `Database::transaction`; its `execute` refuses `BEGIN`, `COMMIT` and `ROLLBACK` by name, which are words of the `contextdb` program. -Not in this version, and refused: `JOIN`, `GROUP BY`, `HAVING`, `DISTINCT`, `LIKE`, `BETWEEN`, -`OFFSET`, `UNION`, `WITH`, subqueries, `INSERT ... SELECT`, graph patterns, `USE RANK`, -`DROP TRIGGER`, `CREATE PROCEDURE` and `CREATE FUNCTION`, table aliases, `CREATE UNIQUE INDEX` +Not in this version, and refused: `INSERT ... SELECT`, `INTERSECT`, `EXCEPT`, `RIGHT` and `FULL` +`JOIN`, recursive `WITH`, `EXISTS`, a subquery that reads the outer row, a window function other +than `ROW_NUMBER`, `DROP TRIGGER`, `CREATE PROCEDURE` and `CREATE FUNCTION`, `CREATE UNIQUE INDEX` (write `UNIQUE` on the column or in the table); and the vector clauses `IVF (...)`, `SEARCH (...)` and `WITH (quantization = 'SQ4')`, which no version reads; the refusal of each says what to write instead. Most are refused by name; this is the sentence the refusal prints: ```text -plan error: LIKE is not supported in this version of the library +plan error: INSERT ... SELECT is not supported in this version of the library ``` ## Column types @@ -226,7 +293,8 @@ CREATE TABLE chunks ( it is set when the row is inserted and never changed. - **`STATE MACHINE (column: from -> [to, ...])`**: an `UPDATE` may move the column only along a listed arrow. A state with no list is a state a row cannot leave. A new row may start in any - state. + state. A state machine over a column that is `IMMUTABLE`, or on a table that is, is refused + when the table is declared, since no update could ever move the state. - **`DAG ('edge_type', ...)`** is for a table of edges, one with `source_id UUID`, `target_id UUID` and `edge_type TEXT`: an edge of a listed type that would close a cycle is refused, by the statement that writes it and again at commit. @@ -451,18 +519,28 @@ A table opts in by declaring a column: What a narrowed handle gets: - A list read (a scan, a range, a count) leaves hidden rows out, and says nothing of them. -- A `SELECT` that names one hidden row whole, by its primary key or a `UNIQUE` rule, is refused +- A `SELECT` that names one hidden row whole, by its primary key or a `UNIQUE` rule (`=` a + value, a `$name` or a `(SELECT ...)`; not `IN` or `OR`), is refused by the rule that hid it: `ContextScopeViolation`, `ScopeLabelViolation`, `AclDenied`, or `PrincipalRequired` for a table that wants a principal and got none. That tells "not yours" from "not there", which is an empty answer; the sentence never carries a value or a number of - the hidden row. + the hidden row. A `GRAPH_TABLE` whose filter names one start node by `id` with `=` (a value, + a `$name` or a `(SELECT ...)`) is refused likewise when the node is hidden; a list of starts + (`IN`, `OR`) leaves the hidden node out and answers the rest, and NULL names no start. - An `UPDATE` or `DELETE` changes no row the handle cannot see, and says it changed none; an `INSERT` or `UPDATE` that would put a row outside the handle's Contexts, labels or grants is refused by the same kinds, and so is a statement whose `PROPAGATE` would move a row the handle may not write. - The statements named above as the unnarrowed handle's reach every Context at once and are refused with `AdminRequired`, naming the statement. - `explain` prints the declaration lines of a search and no record of a partition. + The answer, the refusals and `explain` of a narrowed handle do not depend on the counts, + vectors or index state of data it may not see, so the state of the index is neither printed + nor allowed to refuse it: its `INDEXED` search is answered as + `AUTO` answers it, and its `explain` of a search prints the declaration lines (`requested_mode` + as declared), `filter_path` and `recovery`, and no `resolved_mode`, `key`, `route`, partition, + `small_set` or `refusal` line. The work counters a result carries (`rows_examined`, + `distance_evaluations`) count every row the engine read, hidden ones included, so a host that + serves a narrowed reader should not pass them on. ```rust,no_run use std::collections::BTreeSet; @@ -581,9 +659,9 @@ Error: schema invalid: table 'docs' is referenced by table 'chunks', so it was n - `SET RETAIN`, `SET HISTORY`, `SET SYNC`, `SET SYNC CONFLICT` and `SET MAINTAIN COUNT` replace that clause; `DROP RETAIN` takes `RETAIN` off. No statement removes a `HISTORY` clause: `SET HISTORY ALL` is the way back. A new set of counts is installed whole or not at all. -- `ALTER COLUMN v SET MAX_PARTITIONS m`, `SET SEARCH_MODE mode`, `SET AUTO_INDEX_AT a` and - `SET CONSOLIDATION ...` change a `VECTOR` column; `DEFAULT` after `AUTO_INDEX_AT` or - `CONSOLIDATION` puts back the default. +- `ALTER COLUMN v SET MAX_PARTITIONS m`, `SET SEARCH_MODE mode`, `SET INDEXING_THRESHOLD a` and + `SET COMPACTION ...` change a `VECTOR` column; `DEFAULT` after `INDEXING_THRESHOLD` or + `COMPACTION` puts back the default. - `DROP TABLE` refuses a table another table references, and `DROP INDEX name ON table` names the table, because two tables may use one index name. `IF EXISTS` makes a missing table or index a no-op. @@ -666,14 +744,29 @@ SELECT id, embedding <=> $q AS distance FROM notes ORDER BY distance LIMIT 10; vector is NULL is in no answer. The distance to a vector of all zeros is 1. - How much of the column a search compares with `$q` is the search's mode: `EXACT` compares every stored vector and returns the true nearest rows; `INDEXED` chooses among them through - the column's index; `AUTO`, the default, is `EXACT` until a column is large and then uses the + the column's index (a narrowed handle's `INDEXED` is `AUTO`); `AUTO`, the default, is `EXACT` until a column is large and then uses the index (the paragraph on modes below). -Only `<=>`, cosine, is here: pgvector's `<->` and `<#>` are a parse error. `<=>` has a value -only for the rows of a search, so it is refused everywhere else: in `WHERE`, -in the select list of a statement that does not order by it, in an `INSERT`, `UPDATE` or -`DELETE`, with a vector other than the one the statement orders by, and in an `ORDER BY` that -is `DESC`, has a second item or has no `LIMIT`; a search takes no `OFFSET` either. +Only `<=>`, cosine, is here: pgvector's `<->` and `<#>` are a parse error. A distance is a value +of the row, so `<=>` stands wherever an expression may in a `SELECT`: in `WHERE`, in the select +list, farthest first (`DESC`), as one of several sort keys, between two columns, and with no +`LIMIT`, which orders every row that has a vector. A search takes `OFFSET` after its `LIMIT`. It is +refused in an `UPDATE`'s value and in a `DELETE`'s filter, and on a table that +declares `PROPAGATE ON STATE ... EXCLUDE VECTOR` it is answered only as +`ORDER BY column <=> vector LIMIT n`. `USE VECTOR` on an `ORDER BY` that is not a distance is refused (`UseVectorRequiresVectorOrder`). + +`ORDER BY column <=> vector USE RANK name LIMIT n` orders the rows by the formula of the +column's `RANK_POLICY` instead of by distance, highest rank first, before `LIMIT` and `OFFSET` +are applied. The policy gives each row the row of the table named after `JOIN` that is found +through the column named after `ON` (the joined table needs an index that leads with it): of +the rows found that the reader may see, the one of lowest key; with none, its columns are NULL. +`FORMULA` is numbers and `{column}` names of either table, and `{vector_score}`, which is one +minus the distance, joined by `+` and `*` or written as `coalesce(, )`. A row +with no rank comes last, and rows of one rank in key order. No rank or score column is added to +the answer. The policy is named by its `SORT_KEY`: a column `v VECTOR(2) RANK_POLICY (JOIN +results ON task_id, FORMULA '{confidence} + {vector_score} * coalesce({success}, 1.0)', SORT_KEY +effective_confidence)` is searched by `ORDER BY v <=> [1.0, 0.0] USE RANK effective_confidence +LIMIT 6`. **Upkeep.** Beside every stored vector the engine keeps a one-byte copy of each of its numbers and packs the copies of many vectors into a block, which a search screens quickly to rule most @@ -692,7 +785,7 @@ built, each step in a commit of its own: begin, ten rounds that find the centres vectors under them, pack the groups into blocks, measure (twice), and put the new grouping in force. A partition is grouped again when the vectors written, removed or changed since reach `CHANGE_PERCENT` of its grouping (20 when left out) or the removed or changed ones reach -`TOMBSTONE_PERCENT` (10); `CONSOLIDATION NONE` never groups it again. The call returns a +`TOMBSTONE_PERCENT` (10); `COMPACTION NONE` never groups it again. The call returns a `MaintenanceReport`, and its `vector` field says what is left: `maintenance_vectors_done` and `maintenance_vectors_remaining` (vectors), `remaining_partitions` (partitions with a grouping due or being built) and `stalled_partitions` (those whose last step @@ -732,24 +825,26 @@ the statement's, else the column's, else `AUTO`. - `INDEXED` searches the waiting vectors of each selected partition and, of the rest, only the vectors the index chooses (the paragraph on the index below). A partition with no grouping, or with a grouping of one group, has nothing to choose among, and is searched as `EXACT` - searches it. `INDEXED` is refused, before anything is read, when a selected partition's - writes are far ahead of upkeep (for a partition with no grouping or a grouping of one group, - the vectors outside its grouping number at least twice `AUTO_INDEX_AT`; for one with more - groups, at least twice what makes it due to be grouped again, which under - `CONSOLIDATION NONE` is never), and when a filter on rows leaves it nothing to choose among, as the - paragraph on filters below says. + searches it. For the unnarrowed handle `INDEXED` is refused, before anything is read, where + no index can answer: when a + selected partition's writes are far ahead of upkeep (for a partition with no grouping or a + grouping of one group, the vectors outside its grouping number at least twice + `INDEXING_THRESHOLD`; for one with more groups, at least twice what makes it due to be grouped + again, which under `COMPACTION NONE` is never), whatever the filter is, even a + key; and when a filter on rows leaves it nothing to choose among, as the paragraph on filters + below says. - `AUTO`, which is the default, adds up the vectors of the partitions the statement selects. - Below `AUTO_INDEX_AT` it is `EXACT`. From there on each selected partition that has a + Below `INDEXING_THRESHOLD` it is `EXACT`. From there on each selected partition that has a grouping and is not far behind is searched as `INDEXED` searches it, and every other partition as `EXACT` does. `AUTO` is never refused for a grouping. -`AUTO_INDEX_AT` is 100,000 when not written. Until a column holds that many vectors in all its +`INDEXING_THRESHOLD` is 100,000 when not written. Until a column holds that many vectors in all its partitions together (or declares `SEARCH_MODE INDEXED`), no centre, sketch or mean is written, and `durable_index_bytes` is 0 unless removed or changed rows (10% by default) have given a partition a grouping of one group, which takes 28 bytes. In a column that has reached it, a partition is grouped once it holds a hundredth of it, 1,000 vectors when nothing is written, so a store of many middling partitions is indexed too; a partition of a few hundred vectors is not cut into groups. A -declared `AUTO_INDEX_AT` of any size is served. A column that should never be grouped declares +declared `INDEXING_THRESHOLD` of any size is served. A column that should never be grouped declares one it will not reach. **The index.** An indexed search of a partition that has groups compares the search vector with @@ -772,13 +867,25 @@ kinds, rows written after the build that are unlike the rows the build saw, and other than ten are not what the measure was taken on. `USE VECTOR EXACT` or `SEARCH_MODE EXACT` is exact. -A search with a filter on rows uses the index too. The filter is asked of each row the search -visits, and the search widens until it holds as many allowed rows as were asked for: a filter -that passes most rows costs what the unfiltered search costs, and one that passes few costs -more, up to the work of `EXACT`. `INDEXED` is refused by name only when a filter passes too few -rows for the index to choose among, because being sure of the answer would mean asking the filter -of the whole table under the index's name; `AUTO` does that work and returns every row there -is. +A search with a filter on rows is answered one of two ways, and which is decided by counting. +When the filter reaches rows through an index or a key (`filter_path` in `EXPLAIN`, below; ranges joined by `OR` give no single range and read every row), the +engine first counts the rows that path reaches, from the index entries or the keys alone and +reading no row, and stops counting one past the bound. If there are at most as many as a 128th of +the vectors of the selected partitions that an index with several groups answers plus a 16th of +the vectors of the others, and never fewer than the rows the statement asks for (`LIMIT` plus +`OFFSET`, one more for a second sort key), those rows are read and compared with the search +vector one by one, whatever the mode: the answer is exact, and no index is searched. A row the +reader may not see still counts. A filter that reads the whole table, or no index or key, is +never counted so, and neither is one that reaches more rows than the bound. Otherwise the search +goes through the index, or exactly, and the filter is asked of each row it visits; the search +widens until it holds as many allowed rows as were asked for: a filter that passes most rows +costs what the unfiltered search costs, and one that passes few costs more, up to the work of +`EXACT`. For the unnarrowed handle `INDEXED` is refused by name only when a filter passes too few rows for the index to +choose among, because being sure of the answer would mean asking the filter of the whole table +under the index's name; `AUTO` does that work and returns every row there is. `EXPLAIN` prints +`small_set: yes` when the filter reaches few enough rows to be compared one by one, and `no` +when it reaches more; the line is left out when the filter has no index or key to read by, and +then `recovery:` names the index to create. ```text notes.embedding cannot be searched INDEXED for this statement now: its index is behind its writes, or the statement's filter leaves the index nothing to choose among; run a maintenance cycle, or use EXACT or AUTO @@ -790,7 +897,8 @@ the rows whose distance it worked out. It is an exact count, the same on every r same store, and 0 for any other statement. An indexed search usually counts far fewer than an exact one, and can count more when it leaves few groups out, because it estimates a sketch of every vector it keeps; each of those counts an eighth of the bytes. `Database::explain`, and -`ReadSession::explain`, return what a similarity search would do, without running it. This +`ReadSession::explain`, return what a statement would do, without running it (the `EXPLAIN` +statement under Statements gives the same lines as the rows of a `QUERY PLAN` column). This program builds a store of 2,000 vectors, runs upkeep as above, and searches it both ways: ```rust,no_run @@ -815,7 +923,7 @@ fn vector(id: u64) -> Vec { fn main() -> contextdb::Result<()> { let db = Database::open("./notes-index")?; db.execute( - "CREATE TABLE notes (id INTEGER PRIMARY KEY, embedding VECTOR(8) AUTO_INDEX_AT 1000)", + "CREATE TABLE notes (id INTEGER PRIMARY KEY, embedding VECTOR(8) INDEXING_THRESHOLD 1000)", ¶ms! {}, )?; let tx = db.transaction()?; @@ -864,7 +972,7 @@ INDEXED: 225 distance evaluations the same ten rows: true requested_mode: AUTO resolved_mode: AUTO -effective_auto_index_at: 1000 +effective_indexing_threshold: 1000 aggregate_allowed_vectors: 2000 partition_key_columns: [] partitions: 1 @@ -873,18 +981,32 @@ partition: {} lists: 45 probes: 8 live_rows: 2000 - outside_grouping: 0 + unindexed_rows: 0 refusal: none ``` `lists` is the groups of the grouping in force and `probes` the most of them a search scanned -for the questions its build made, `outside_grouping` the slots in blocks written since (stale ones +for the questions its build made, `unindexed_rows` the slots in blocks written since (stale ones included) plus the vectors still waiting, and `route` is `exact` or `indexed`; `refusal` is `none` or, for INDEXED over a partition that is behind its writes, the sentence the search would be refused with (the refusal for a filter is -known only when the search runs). A statement that names a partition with a `$name` has nothing to select -with, since `explain` binds nothing: it lists every partition of the column and says so, -`partitions: every partition ($t is not bound)`. `explain` of a statement that is not a -similarity search is refused as a later version's. +known only when the search runs); a narrowed handle is given no `refusal` line. A statement that names a partition with a `$name` has nothing to select +with, when `Database::explain` is given no value for it: it lists every partition of the column and says so, +`partitions: every partition ($t is not bound)`. + +When the search has a filter on rows whose every name has a value, the lines before `refusal` +also say how the filter is read: `filter_path:` with the index or key it goes through, or `none`; the +`predicates_pushed` and `indexes_considered` lines of any other statement; `small_set: yes` or +`no` (the paragraph on filters above), only when the filter has a path; and, when no index +serves, `recovery:` with the `CREATE INDEX` statement that would. Of a statement that is not a +similarity search, `explain` says the path each table is read by: `IndexScan { index: name }` with the +columns it pushes into the index and why each other index was passed over, or `Scan`; a join +says it for each table; a grouped count says `maintained count: used (...)` when a count the +table keeps serves it and otherwise `maintained count: not declared` with the `ALTER TABLE ... SET +MAINTAIN COUNT` that would. An `INSERT`, `UPDATE` or `DELETE` is explained as it would run +and changes nothing. What is wrong with the statement itself (an unknown column, a +value count that does not match the columns, a conflict rule the table cannot keep) is refused +as the statement is, before anything is read; what is wrong only with the rows it would meet +(a subquery that gives several rows where one is wanted) is not. **Quantization.** `WITH (quantization = 'SQ8')` on a column keeps each vector as one scale and one whole number from -127 to 127 for each of its numbers, so a vector of `n` numbers takes @@ -914,8 +1036,8 @@ quantization: F32 vector_count: 2000 … search_mode: AUTO -declared_auto_index_at: 1000 -effective_auto_index_at: 1000 +declared_indexing_threshold: 1000 +effective_indexing_threshold: 1000 … durable_vector_bytes: 32000 durable_index_bytes: 7856 @@ -932,7 +1054,7 @@ table: notes column: embedding partition_key: {} live_rows: 2000 -pending_inserts: 0 +pending_tuples: 0 tombstones: 0 durable_vector_bytes: 32000 durable_index_bytes: 7856 @@ -948,13 +1070,14 @@ probes: 8 recovery_action: none ``` -`.explain ` in the shell prints what `Database::explain` returns, the text shown above. +`.explain ` in the shell prints what `Database::explain` returns, the text shown above. A +statement with two faults may be refused for either. Inspection tells the groups a partition has (`lists`) and the most groups a search scanned while the index was measured (`probes`); it does not print the measured distance or width. A column with no `PARTITION_KEY` has one row in `SHOW VECTOR_PARTITIONS`, with `partition_key` `{}`, and a partitioned column with no vector has none. A partition's `maintenance_state` is `idle`, `pending` (a grouping is due and not begun), -`building` or `stalled`, and its `maintenance_reason` says why upkeep has work: `first_grouping`, +`building` or `stalled`, and its `maintenance_reason` says why upkeep has work: `unindexed`, `changes`, `tombstones`, `damaged` or `memory_limit`. For `pending` and `building` the `recovery_action` is `run a maintenance cycle`, and for `stalled` it is `raise the memory limit`. @@ -1103,8 +1226,7 @@ A statement ends at `;`. `BEGIN;`, `COMMIT;` and `ROLLBACK;` run a transaction, `--write`; a `BEGIN` inside a transaction, and a `COMMIT` or `ROLLBACK` outside one, change nothing, answer `ok` and print a `warning:` line on the error stream; `.tables` lists the tables, `.schema
` prints a table's declaration, `.explain ` prints how a -similarity search would be answered without running it (anything else it refuses like a statement -of a later version), and `.help` lists the commands. With +statement would be answered without running it, and `.help` lists the commands. With statements piped in there is no prompt, and a refusal does not stop what comes after it. A refused statement or command is one line on the error stream, `Error: ` and then the refusal's sentence, or the program's own sentence where one of its options is the way on; a line that @@ -1123,7 +1245,10 @@ options, the exit statuses and the JSON forms. ## Numbers -Measured at one commit by `v2/numbers.sh`, which prints them again on any machine: a release +Measured at one commit, `4b31bf214`, by `v2/numbers.sh`, which prints them again on any machine. +That commit is before the joins, grouping, graph patterns and the other SQL above were added, so +the two counts below are of that engine; `docs/performance/README.md` has the bars the engine is +held to and the newest figure against each. A release build on a 16-core AMD Ryzen 9 9955HX with 64 GB of memory and an NVMe drive, running Linux and nothing else. Every search time is the 95th percentile of 100 questions asked one after the other by one thread, in a read session under a 1 GiB memory limit unless a row says 64 MiB, in @@ -1152,11 +1277,11 @@ how many of the 100 questions got all ten. | Lines that differ from redb 4.1.0 in the storage library under the engine, which is redb 4.1.0 with the changes listed in `v2/redb/README.md` | 626 | Searches for the ten nearest, indexed beside exact from the same run. Where a store is below -`AUTO_INDEX_AT` nothing is grouped and an indexed search is the exact one. +`INDEXING_THRESHOLD` nothing is grouped and an indexed search is the exact one. | Search | Indexed | Exact | Recall, questions with all ten | |---|---|---|---| -| 10,000 generated vectors, one partition, 100 groups (`AUTO_INDEX_AT 1000`) | 0.544 ms | 1.194 ms | 0.9960, 96 of 100 | +| 10,000 generated vectors, one partition, 100 groups (`INDEXING_THRESHOLD 1000`) | 0.544 ms | 1.194 ms | 0.9960, 96 of 100 | | 100,008 real passages, eight partitions, 884 groups: one partition | 0.696 ms | 1.407 ms | 1.0000, 100 of 100 | | the same: several partitions | 1.568 ms | 3.829 ms | 0.9990, 99 of 100 | | the same: all eight | 4.115 ms | 10.904 ms | 0.9990, 99 of 100 | @@ -1179,3 +1304,14 @@ With `WITH (quantization = 'SQ8')` the same two stores of real passages take 0.4 100,008). Searched exactly, the same ten rows come back as from the full-precision store on 88, 84 and 79 questions of 100 in the 11,588 (one, several, all partitions) and on 86, 83 and 85 in the 100,008. + +## Questions + +**Do a row, its relationships and its vectors commit together?** Yes. A relationship is a row in +a table of edges (`source_id`, `target_id`, `edge_type`) and a vector is a column of a row, so +all three are rows of tables, and one commit writes every row of it, the values kept beside +them, the index entries, the counts, the schema records and the vector part's records in one +storage transaction: after a kill either all of it is there or none. A statement run on its own +is a commit of its own; to write a row, its edges and its vector together, run the statements in +one `Database::transaction` and call `commit`, and a transaction dropped or rolled back writes +none of them. diff --git a/v2/contextdb/examples/measure.rs b/v2/contextdb/examples/measure.rs index e1fbded17..32606cdc5 100644 --- a/v2/contextdb/examples/measure.rs +++ b/v2/contextdb/examples/measure.rs @@ -25,7 +25,7 @@ //! eight directions of its own for its appearance, tracks of ten sightings whose appearance //! drifts, a little noise on every number; 100 questions, eighty new sightings of stored //! subjects and twenty of subjects never stored. Each case loads two stores, 500 rows to a -//! commit: one whose column declares `AUTO_INDEX_AT 1000000000`, so that nothing is grouped, +//! commit: one whose column declares `INDEXING_THRESHOLD 1000000000`, so that nothing is grouped, //! sealed and searched under EXACT; and one that declares nothing, with every maintenance //! cycle run, opened and searched once in a new process (`measure first ...`, which the //! program starts itself as) and then searched, in one read session under 1 GiB, under @@ -517,7 +517,7 @@ fn index( std::fs::create_dir_all(folder)?; let store = folder.join("sealed"); let ((db, questions), load) = { - let (filled, load) = timed(|| filled(&store, " AUTO_INDEX_AT 1000000000", rows)); + let (filled, load) = timed(|| filled(&store, " INDEXING_THRESHOLD 1000000000", rows)); (filled?, load) }; line(&format!("{prefix}load"), seconds(load), "s"); diff --git a/v2/contextdb/examples/passages.rs b/v2/contextdb/examples/passages.rs index 55c1a8b7d..f34e84ae9 100644 --- a/v2/contextdb/examples/passages.rs +++ b/v2/contextdb/examples/passages.rs @@ -7,7 +7,7 @@ //! dump, declared as Context Graph declares its table. Lines `passages__...`. //! - `passages single `: the first 10,000 passages, in dump order, of //! the dump's (Context, generation) pair of index 1, in a table whose vector column also -//! declares `AUTO_INDEX_AT 1000`. Lines `single__...`. +//! declares `INDEXING_THRESHOLD 1000`. Lines `single__...`. //! - `passages first single|store `: what the program starts //! itself as, to open a built store in a new process and run one search. //! @@ -24,7 +24,7 @@ //! What it does, in order, each store loaded 500 passages to a commit with no memory limit //! and every read session opened under 1 GiB unless a line's name says another limit: //! -//! 1. `sealed`: a store whose column declares `AUTO_INDEX_AT 1000000000`, so that no partition +//! 1. `sealed`: a store whose column declares `INDEXING_THRESHOLD 1000000000`, so that no partition //! is ever grouped. One search of every question with every vector still waiting; cycles //! until nothing waits; its size; EXACT in each scope (`exact_before`). //! 2. `built`: the store as its case declares it. Cycles until nothing remains; what @@ -77,7 +77,7 @@ const DIMENSIONS: usize = 768; const PER_COMMIT: usize = 500; const ROUNDS: usize = 5; /// The clause of a column no partition of which is ever grouped. -const NEVER_GROUPED: &str = " AUTO_INDEX_AT 1000000000"; +const NEVER_GROUPED: &str = " INDEXING_THRESHOLD 1000000000"; struct Passage { id: Uuid, @@ -208,7 +208,7 @@ impl<'a> Case<'a> { } /// The first 10,000 passages of the pair of index 1, in a column that declares - /// `AUTO_INDEX_AT 1000`. + /// `INDEXING_THRESHOLD 1000`. fn single(dump: &'a Dump) -> Case<'a> { let places = 0..dump.passages.len(); let of_pair = places.filter(|at| dump.passages[*at].pair == 1); @@ -217,7 +217,7 @@ impl<'a> Case<'a> { dump, prefix: format!("single_{}_", loaded.len()), loaded, - declared: " AUTO_INDEX_AT 1000", + declared: " INDEXING_THRESHOLD 1000", scopes: vec![("", vec![dump.pair(1)])], answers: None, } @@ -697,8 +697,8 @@ fn reduced(case: &Case<'_>, store: &Path, sealed: u64, exact: &[Asked]) -> Falli fn measure(case: &Case<'_>, folder: &Path, extras: &str) -> Fallible<()> { support::must_be_empty(folder); std::fs::create_dir_all(folder)?; - if case.declared == " AUTO_INDEX_AT 1000" { - line(&case.name("auto_index_at"), 1000, "vectors"); + if case.declared == " INDEXING_THRESHOLD 1000" { + line(&case.name("indexing_threshold"), 1000, "vectors"); } let (held, sealed_bytes, exact) = sealed(case, &folder.join("sealed"))?; built(case, folder, held, sealed_bytes)?; diff --git a/v2/contextdb/src/database/mod.rs b/v2/contextdb/src/database/mod.rs index 1c929647c..96c7ae8f4 100644 --- a/v2/contextdb/src/database/mod.rs +++ b/v2/contextdb/src/database/mod.rs @@ -129,7 +129,7 @@ struct Staged { } fn planned(sql: &str) -> Result { - sql::plan(&sql::parse(sql)?) + sql::plan(sql::parse(sql)?) } /// Refuses `statement`, by its name, to a handle that declared a narrowing. @@ -545,10 +545,7 @@ impl Database { /// /// On a handle that was closed, with the message "database handle is closed". pub fn table_names(&self) -> Vec { - let open = self.must_be_open(); - let newest = locked(&open.newest); - let tables = newest.catalog.tables().into_iter(); - tables.map(|table| table.name.clone()).collect() + locked(&self.must_be_open().newest).catalog.table_names() } /// A table's declaration as SQL text, as of the newest commit: the `CREATE TABLE` statement @@ -562,10 +559,7 @@ impl Database { /// [`crate::Error::DatabaseClosed`] on a handle that was closed. The answer is not read /// from the disk, so no other error is returned. pub fn declaration(&self, table: &str) -> Result { - let open = self.opened()?; - let newest = locked(&open.newest); - let found = newest.catalog.table(table).map(schema::render); - found.ok_or_else(|| Error::TableNotFound(table.to_owned())) + locked(&self.opened()?.newest).catalog.declaration(table) } /// The number of the newest commit on disk: 0 for a store nothing was ever committed to, @@ -599,7 +593,8 @@ impl Database { let open = self.opened()?; let (view, catalog) = open.newest()?; let now = system::now_millis(&*open.clock); - query::explain(&plan, &catalog, &view, &self.reader, &open.budget, now) + let (reader, budget) = (&self.reader, &open.budget); + query::explain(&plan, &HashMap::new(), &catalog, &view, reader, budget, now) } /// Runs one cycle of upkeep and returns what it did. @@ -810,14 +805,14 @@ impl Transaction<'_> { op: BinOp::Eq, right: Box::new(Expr::Parameter("key".to_owned())), }; + let params = HashMap::from([("key".to_owned(), key_value.clone())]); let asked = query::Asked { table: found, filter: Some(&filter), assigned: &[], needed: &needed, reader: &self.db.reader, - params: &HashMap::from([("key".to_owned(), key_value.clone())]), - now: 0, + ctx: query::EvalContext::new(¶ms, 0), }; let rows = query::rows_for_write(&asked, None, &catalog, &staged.changes, &open.budget)?; let Some((key, cells)) = rows.and_then(|(rows, _)| rows.into_iter().next()) else { diff --git a/v2/contextdb/src/database/tests.rs b/v2/contextdb/src/database/tests.rs index 7913820de..48115214e 100644 --- a/v2/contextdb/src/database/tests.rs +++ b/v2/contextdb/src/database/tests.rs @@ -1,119 +1,78 @@ -//! What the commit function does for a transaction that another commit overtook, and what a -//! closed handle answers. +//! What a handle and a transaction promise the compiler, and what a lookup does with a damaged +//! index. use std::collections::HashMap; use super::{Database, Transaction}; use crate::types::{Error, Value}; -/// Runs a test on a fresh store in a folder of its own, which is removed when the test passes. -fn with_store(name: &str, test: impl FnOnce(&Database)) { - let folder = std::env::temp_dir().join(format!("contextdb-{name}-{}", std::process::id())); +fn shared() {} +fn sent() {} + +/// No test may start a thread, so what "calls may be made from many threads" rests on is +/// checked here by the compiler. +#[test] +fn a_handle_is_shared_between_threads_and_a_transaction_moves_to_one() { + shared::(); + sent::>(); +} + +/// An index entry whose row is not in the table is damage of the store, never an empty answer: +/// a lookup through the index reads the row it names, and a row that is not there means the +/// store disagrees with itself. No public call makes such an entry, so it is staged through +/// the store's own write, as a commit of a store that was damaged would have left it. +#[test] +fn an_index_entry_with_no_row_is_refused_as_damage_by_a_lookup_through_it() { + use crate::memory::Budget; + use crate::schema::Catalog; + use crate::store::{ChangeSet, Key, Store}; + + let folder = + std::env::temp_dir().join(format!("contextdb-orphan-entry-{}", std::process::id())); let db = Database::open(&folder).expect("open a fresh store"); for sql in [ "CREATE TABLE t (id INTEGER PRIMARY KEY, tag INTEGER)", + "CREATE INDEX t_tag ON t (tag)", "INSERT INTO t (id, tag) VALUES (1, 7)", ] { db.execute(sql, &HashMap::new()).expect(sql); } - test(&db); drop(db); - std::fs::remove_dir_all(&folder).expect("remove the test's folder"); -} - -fn rows(db: &Database, sql: &str) -> Vec> { - db.execute(sql, &HashMap::new()).expect(sql).rows().to_vec() -} -fn ints(numbers: [i64; N]) -> Vec> { - numbers.map(|number| vec![Value::Int64(number)]).to_vec() -} - -#[test] -fn transactions_that_each_declare_a_table_commit_with_a_number_each() { - with_store("declare-side-by-side", |db| { - let declaring = [ - "CREATE TABLE a (id INTEGER PRIMARY KEY)", - "CREATE TABLE b (id INTEGER PRIMARY KEY)", - "CREATE TABLE a (id INTEGER PRIMARY KEY, more TEXT)", - ]; - // All three begin from the same tables. - let [first, second, third] = declaring.map(|sql| { - let tx = db.transaction().expect("begin"); - tx.execute(sql, &HashMap::new()).expect(sql); - tx - }); - first.commit().expect("the first declaration commits"); - second.commit().expect("a table of another name commits"); - // The name was free when the third declared it and is taken now. - assert!(matches!(third.commit(), Err(Error::SchemaInvalid { .. }))); - assert_eq!(db.table_names(), ["a", "b", "t"]); - - // A row of one table is no row of the other. - db.execute("INSERT INTO a (id) VALUES (1)", &HashMap::new()) - .expect("insert into a"); - assert_eq!(rows(db, "SELECT COUNT(*) FROM a"), ints([1])); - assert_eq!(rows(db, "SELECT COUNT(*) FROM b"), ints([0])); - assert!(rows(db, "SELECT id FROM b").is_empty()); - }); -} - -#[test] -fn a_new_index_has_the_rows_committed_while_its_transaction_was_open() { - with_store("index-overtaken", |db| { - let tx = db.transaction().expect("begin"); - tx.execute("CREATE INDEX t_tag ON t (tag)", &HashMap::new()) - .expect("declare the index"); - db.execute("INSERT INTO t (id, tag) VALUES (2, 7)", &HashMap::new()) - .expect("insert while the index is being declared"); - tx.commit().expect("commit the index"); - assert_eq!( - rows(db, "SELECT id FROM t WHERE tag = 7 ORDER BY id"), - ints([1, 2]) - ); - }); -} - -#[test] -fn rows_staged_before_an_index_was_declared_are_not_committed_without_its_entries() { - with_store("rows-overtaken", |db| { - let tx = db.transaction().expect("begin"); - tx.execute("INSERT INTO t (id, tag) VALUES (2, 7)", &HashMap::new()) - .expect("insert in the transaction"); - db.execute("CREATE INDEX t_tag ON t (tag)", &HashMap::new()) - .expect("declare an index beside the transaction"); - assert!(matches!(tx.commit(), Err(Error::SchemaInvalid { .. }))); - assert_eq!(rows(db, "SELECT id FROM t WHERE tag = 7"), ints([1])); - }); -} - -#[test] -fn a_closed_handle_refuses_by_name() { - with_store("closed-handle", |db| { - let tx = db.transaction().expect("begin"); - db.close().expect("close"); - db.close().expect("close a second time"); - let select = "SELECT id FROM t"; - assert!(matches!( - db.execute(select, &HashMap::new()), - Err(Error::DatabaseClosed) - )); - assert!(matches!( - tx.execute(select, &HashMap::new()), - Err(Error::DatabaseClosed) - )); - assert!(matches!(tx.commit(), Err(Error::DatabaseClosed))); - assert!(matches!(db.transaction(), Err(Error::DatabaseClosed))); - }); -} - -fn shared() {} -fn sent() {} + { + let budget = Budget::new(None).expect("a budget"); + let store = Store::open_for_writing(&folder, &budget, None).expect("open the store"); + let view = store.view().expect("a view"); + let catalog = Catalog::load(&view).expect("the tables"); + let table = catalog.table("t").expect("table t"); + // Place 0 is the index behind the primary key; `t_tag` is place 1, the one `tag = 9` walks. + let entry = table + .entry_shape(1) + .entry(&[Value::Int64(9)]) + .expect("an entry for tag 9"); + let absent = Key::from_values(&[Value::Int64(99)], &[]).expect("a key"); + let mut changes = ChangeSet::new(view, &budget).expect("begin"); + changes + .put_index(table.index_ids[1], entry, absent) + .expect("stage the entry"); + store.commit(changes).expect("commit"); + } -/// No test may start a thread, so what "calls may be made from many threads" rests on is -/// checked here by the compiler. -#[test] -fn a_handle_is_shared_between_threads_and_a_transaction_moves_to_one() { - shared::(); - sent::>(); + let db = Database::open(&folder).expect("open the store again"); + let found = db + .execute("SELECT id FROM t WHERE tag = 7", &HashMap::new()) + .expect("a lookup through an entry with its row"); + assert_eq!( + found.rows(), + [vec![Value::Int64(1)]], + "an entry with its row is found" + ); + let found = db.execute("SELECT id FROM t WHERE tag = 9", &HashMap::new()); + assert!( + matches!(found, Err(Error::StoreCorrupted { .. })), + "an index entry naming a row that is not there must be refused as damage, not skipped \ + into an empty answer: {found:?}" + ); + drop(db); + std::fs::remove_dir_all(&folder).expect("remove the test's folder"); } diff --git a/v2/contextdb/src/lib.rs b/v2/contextdb/src/lib.rs index 609a246c2..603efaa43 100644 --- a/v2/contextdb/src/lib.rs +++ b/v2/contextdb/src/lib.rs @@ -19,8 +19,10 @@ pub use read::{ReadSession, ReadSessionOptions}; pub use store::{StorageBackend, WrapStorage}; pub use system::Clock; pub use types::{ - ColumnType, ContextId, Error, Principal, Result, ScopeLabel, TableMeta, TxId, Uuid, Value, - VectorIndexRef, VectorPartitionDeclarationIssue, VectorPolicyDeclarationIssue, + ColumnDef, ColumnDefault, ColumnType, ConflictPolicy, ContextId, Error, History, IndexDecl, + KeptCounts, Principal, Result, Retain, RetainUnit, ScopeLabel, SortDirection, StateMachine, + SyncDirection, TableMeta, TxId, Uuid, Value, VectorIndexRef, VectorPartitionDeclarationIssue, + VectorPolicyDeclarationIssue, }; pub use upkeep::{MaintenanceReport, VectorMaintenanceReport}; diff --git a/v2/contextdb/src/memory/tests.rs b/v2/contextdb/src/memory/tests.rs index 03ea151e3..7d7dc0bcd 100644 --- a/v2/contextdb/src/memory/tests.rs +++ b/v2/contextdb/src/memory/tests.rs @@ -10,22 +10,6 @@ fn budget_with_room(room: u64) -> (Budget, u64) { (budget, baseline) } -#[test] -fn bytes_are_counted_while_held_and_given_back_when_released() { - let (budget, baseline) = budget_with_room(100); - let mut held = budget.reserve(60, "sort").expect("60 of 100"); - held.grow(30).expect("30 of the 40 left"); - assert_eq!((held.bytes(), budget.used()), (90, baseline + 90)); - held.shrink(50); - assert_eq!((held.bytes(), budget.used()), (40, baseline + 40)); - // Another handle is the same budget. - let other = budget.clone().reserve(60, "result").expect("60 of 60"); - assert_eq!(budget.used(), baseline + 100); - drop(held); - drop(other); - assert_eq!(budget.used(), baseline); -} - #[test] fn a_refusal_names_what_was_asked_and_what_was_left_and_counts_nothing() { let (budget, baseline) = budget_with_room(100); @@ -46,17 +30,6 @@ fn a_refusal_names_what_was_asked_and_what_was_left_and_counts_nothing() { held.grow(40).expect("exactly what was left"); } -#[test] -fn with_no_limit_every_reservation_succeeds_and_is_counted() { - let budget = Budget::new(None).expect("no ceiling"); - assert_eq!(budget.limit(), None); - let baseline = budget.used(); - let held = budget.reserve(1 << 50, "result").expect("no ceiling"); - assert_eq!(budget.used(), baseline + (1 << 50)); - drop(held); - assert_eq!(budget.used(), baseline); -} - #[test] fn a_limit_below_what_is_in_use_is_refused_and_the_old_one_stays() { assert!(Budget::new(Some(ALLOWANCE - 1)).is_err()); diff --git a/v2/contextdb/src/query/aggregate.rs b/v2/contextdb/src/query/aggregate.rs new file mode 100644 index 000000000..5ef90bf19 --- /dev/null +++ b/v2/contextdb/src/query/aggregate.rs @@ -0,0 +1,573 @@ +//! GROUP BY, the aggregates and HAVING: one row for each set of grouping values, in the order +//! of those values, and for a statement of aggregates with no GROUP BY one row over every row +//! of its input. + +use std::cmp::Ordering; +use std::collections::BTreeMap; +use std::collections::HashMap; +use std::collections::btree_map::Entry; +use std::ops::Bound; + +use super::bind::{bind, kind}; +use super::counts::{names, undeclared, used}; +use super::expression::{ + Arithmetic, EvalContext, Scope, arithmetic, compare, eval, most_bytes, reads, +}; +use super::plan::{Each, Filter, Source, hand_on, listed}; +use super::row_overhead; +use super::sort::Key; +use super::table::collect; +use super::visible::Reader; +use crate::memory::Reservation; +use crate::schema::Table; +use crate::sql::ast::{BinOp, ColumnRef, Literal}; +use crate::sql::plan::{ProjectColumn, SelectPlan, SortKey}; +use crate::sql::{AGGREGATES, Expr, inside_mut, not_supported}; +use crate::store::{self, CountId, Read}; +use crate::types::heap_bytes; +use crate::types::{ColumnDef, ColumnType, Error, Result, SortDirection, Value}; + +/// How a grouped statement is answered: what its rows are grouped by, the aggregates it +/// writes, and its HAVING, ORDER BY and select list written over a row of one group, which +/// holds the grouping values and then the answer of each aggregate. +pub(super) struct Groups { + keys: Vec, + /// For each grouping value, whether its groups leave greatest first. + descending: Vec, + calls: Vec, + /// The columns of a group's row. Each is found by its name; no type of theirs is read. + columns: Vec, + having: Option, + order: Vec, + list: Vec, +} + +/// One aggregate as it was written. +struct Call { + function: Function, + /// What is counted, added or compared; `None` for `COUNT(*)`. + of: Option, +} + +#[derive(Clone, Copy, PartialEq)] +enum Function { + Count, + Sum, + Min, + Max, + Avg, +} + +impl Function { + /// The aggregate called `name`, from the one list of them the planner has. + fn named(name: &str) -> Option { + let mut names = AGGREGATES.iter(); + let at = names.position(|known| known.eq_ignore_ascii_case(name))?; + let functions = [Self::Count, Self::Sum, Self::Min, Self::Max, Self::Avg]; + Some(functions[at]) + } +} + +/// A column that a stage makes for the stages above it, and the expression that reads it. +pub(super) fn made(table: Option<&str>, name: &str) -> (ColumnDef, Expr) { + let column = ColumnDef { + name: name.to_owned(), + column_type: ColumnType::Integer, + nullable: true, + primary_key: false, + unique: false, + default: None, + }; + let read = Expr::Column(ColumnRef { + table: table.map(str::to_owned), + column: name.to_owned(), + }); + (column, read) +} + +impl Groups { + /// The grouping of a SELECT that has GROUP BY, HAVING or an aggregate; `None` for any + /// other. Everything it names is bound against `scope`, the columns of the rows it reads, + /// and each column it reads is marked in `wanted`. An item that is neither a grouping + /// expression nor inside an aggregate is refused here, whatever rows there are. + /// + /// Groups leave in the order of their grouping values, each going up unless a count list + /// of `table` declares that column DESC, NULL last. + pub(super) fn of( + select: &SelectPlan, + scope: &Scope, + table: Option<&Table>, + params: &HashMap, + wanted: &mut [bool], + ) -> Result> { + let mut groups = Groups { + keys: select.group_by.clone(), + descending: Vec::new(), + calls: Vec::new(), + columns: Vec::new(), + having: select.having.clone(), + order: select.order_by.clone(), + list: select.columns.clone(), + }; + for key in &groups.keys { + reads(key, scope, params, wanted)?; + let at = match key { + Expr::Column(column) => Some(scope.find(column)?.0), + _ => None, + }; + let lists = table.into_iter().flat_map(|table| &table.rules.counts); + let mut declared = lists.flat_map(|count| &count.columns); + let declared = declared.find(|(column, _)| Some(*column) == at); + let descending = declared.is_some_and(|(_, way)| *way == SortDirection::Desc); + groups.descending.push(descending); + } + let written: Vec = groups.keys.iter().map(|key| spelled(key, scope)).collect(); + // What stands outside every group is refused only once the statement is known to be + // grouped: an aggregate may be written after it. + let mut outside = None; + let mut over = |expr: &mut Expr| { + let calls = &mut groups.calls; + over_group(expr, &written, calls, (scope, params), wanted, &mut outside) + }; + groups.having.iter_mut().try_for_each(&mut over)?; + let order = groups.order.iter_mut().map(|key| &mut key.expr); + let list = groups.list.iter_mut().map(|column| &mut column.expr); + order.chain(list).try_for_each(&mut over)?; + if groups.keys.is_empty() && groups.calls.is_empty() && groups.having.is_none() { + return Ok(None); + } + outside.map_or(Ok(()), Err)?; + // What is written over the groups is bound as it was written, each aggregate as a + // value of the type of its answer: a comparison of types that do not compare is + // refused here. + let order = select.order_by.iter().map(|key| &key.expr); + let list = select.columns.iter().map(|column| &column.expr); + for expr in select.having.iter().chain(order).chain(list) { + let mut expr = expr.clone(); + typed(&mut expr); + bind(&expr, scope, params)?; + } + let width = groups.keys.len() + groups.calls.len(); + groups.columns = (0..width).map(|at| made(None, &at.to_string()).0).collect(); + Ok(Some(groups)) + } + + /// True when the answer is known from the number of rows alone: no GROUP BY, and every + /// aggregate a `COUNT(*)`. + pub(super) fn counts_every_row(&self) -> bool { + let every_row = self.calls.iter().all(|call| call.of.is_none()); + self.keys.is_empty() && every_row && !self.calls.is_empty() + } + + /// The kept count of `table` that holds one record for each group, when there is one and + /// its records are the answer: every aggregate is `COUNT(*)`, the grouping expressions are + /// the last columns of the count's list, and `filter` gives one value that is not NULL for + /// each column before them and says nothing else. + /// + /// `None` when the rows have to be read: for a reader that is not shown every row, for a + /// table the transaction has staged a row of, and for a list that declares a column DESC, + /// whose records do not give their values back. + pub(super) fn kept<'a>( + &self, + table: &Table, + scope: &Scope, + filter: Option<&Expr>, + reader: &Reader, + ctx: &EvalContext, + read: &'a dyn Read, + ) -> Result>> { + let counted = self.calls.iter().all(|call| call.of.is_none()); + if self.keys.is_empty() || !counted || !reader.is_admin() { + return Ok(None); + } + let mut grouped = Vec::new(); + for key in &self.keys { + let Expr::Column(column) = key else { + return Ok(None); + }; + grouped.push(scope.find(column)?.0); + } + let mut terms = Vec::new(); + if let Some(filter) = filter + && !collect(table, scope, filter, ctx, &mut terms)? + { + return Ok(None); + } + let mut staged = false; + read.staged(table.id, &mut |_| { + staged = true; + Ok(false) + })?; + let say = |line: &dyn Fn() -> String| ctx.said.map(|said| said.borrow_mut().push(line())); + // The one value the filter gives a column, when it gives it nothing else. + let given = |column: usize| { + let mut of = terms.iter().filter(|term| term.column == column); + match (of.next(), of.next()) { + (Some(term), None) if term.op == BinOp::Eq => match term.values.as_slice() { + [value] if *value != Value::Null => Some(value.clone()), + _ => None, + }, + _ => None, + } + }; + for count in &table.rules.counts { + let Some(given_for) = count.columns.len().checked_sub(grouped.len()) else { + continue; + }; + let (first, last) = count.columns.split_at(given_for); + let values: Option> = first.iter().map(|column| given(column.0)).collect(); + let places = grouped + .iter() + .map(|at| last.iter().position(|column| column.0 == *at)); + let places: Option> = places.collect(); + let places = places.filter(|places| (0..places.len()).all(|at| places.contains(&at))); + let ascending = count + .columns + .iter() + .all(|column| column.1 == SortDirection::Asc); + let pinned = terms + .iter() + .all(|term| first.iter().any(|column| column.0 == term.column)); + if let (Some(values), Some(places), true, true, false) = + (values, places, ascending, pinned, staged) + { + say(&|| used(table, &count.columns)); + return Ok(Some(Kept { + read, + count: count.id, + given: store::Key::from_values(&values, &[])?, + places: places.into_iter().map(|at| given_for + at).collect(), + })); + } + } + let wanted = terms.iter().map(|term| term.column).chain(grouped); + say(&|| undeclared(table, &names(table, wanted.clone()))); + Ok(None) + } +} + +/// The records of a kept count that are the groups of a statement. +pub(super) struct Kept<'a> { + read: &'a dyn Read, + count: CountId, + /// What every record of these groups begins with: the values the filter gives. + given: store::Key, + /// For each grouping value, where it is among the values of a record. + places: Vec, +} + +/// How a written expression is told from another: a column by where it sits in a row, whatever +/// qualifier it was written with, and anything else by how it is written. +pub(super) fn spelled(expr: &Expr, scope: &Scope) -> String { + let at = match expr { + Expr::Column(column) => scope.find(column).ok(), + _ => None, + }; + at.map_or_else(|| format!("{expr:?}"), |(at, _)| format!("#{at}")) +} + +/// Puts in place of each aggregate inside `expr` something of the type of its answer, so that +/// what is written over the groups binds as any expression does. +pub(super) fn typed(expr: &mut Expr) { + let function = match expr { + Expr::FunctionCall { name, .. } => Function::named(name), + _ => None, + }; + *expr = match (function, &mut *expr) { + (Some(Function::Count), _) => Expr::Literal(Literal::Integer(0)), + (Some(Function::Avg), _) => Expr::Literal(Literal::Real(0.0)), + (Some(_), Expr::FunctionCall { args, .. }) if args.len() == 1 => args.remove(0), + (_, other) => return inside_mut(other).into_iter().for_each(typed), + }; +} + +/// Writes `expr` over a group's row: a grouping expression becomes the column of its value, +/// and an aggregate, which joins `calls`, the column of its answer. `AVG` is the sum of the +/// values as REALs over the count of those that are not NULL. The refusal of the first thing +/// that is neither, a column or a window, becomes `outside`. +fn over_group( + expr: &mut Expr, + keys: &[String], + calls: &mut Vec, + (scope, params): (&Scope, &HashMap), + wanted: &mut [bool], + outside: &mut Option, +) -> Result<()> { + if let Some(at) = keys.iter().position(|key| *key == spelled(expr, scope)) { + *expr = made(None, &at.to_string()).1; + return Ok(()); + } + let function = match expr { + Expr::FunctionCall { name, .. } => Function::named(name), + _ => None, + }; + let (function, name, args) = match (function, &mut *expr) { + (Some(function), Expr::FunctionCall { name, args }) => (function, name, args), + (_, Expr::Column(column)) => { + outside.get_or_insert_with(|| { + Error::PlanError(format!( + "the column {} must be in GROUP BY or inside an aggregate", + column.column + )) + }); + return Ok(()); + } + (_, Expr::RowNumber { .. }) => { + outside.get_or_insert_with(|| { + not_supported("ROW_NUMBER() OVER beside GROUP BY or an aggregate") + }); + return Ok(()); + } + (_, other) => { + let mut inner = inside_mut(other).into_iter(); + let given = (scope, params); + return inner + .try_for_each(|inner| over_group(inner, keys, calls, given, wanted, outside)); + } + }; + let [of] = args.as_slice() else { + return Err(Error::PlanError(format!("{name} takes one argument"))); + }; + let every_row = + function == Function::Count && matches!(of, Expr::Column(column) if column.column == "*"); + if !every_row { + reads(of, scope, params, wanted)?; + } + // A SUM over a column that does not hold numbers is refused whatever rows there are. + if let (Function::Sum | Function::Avg, Expr::Column(column)) = (function, of) + && !matches!( + scope.find(column)?.1, + ColumnType::Integer | ColumnType::Real + ) + { + return Err(Error::PlanError(format!( + "{} needs numbers, and the column {} holds none", + name.to_uppercase(), + column.column + ))); + } + if let Function::Min | Function::Max = function + && let Some(ColumnType::Vector(_)) = kind(of, scope, params)? + { + let refused = format!("function {}(vector) does not exist", name.to_lowercase()); + return Err(Error::PlanError(refused)); + } + let of = (!every_row).then(|| of.clone()); + let mut call = |function, of| { + calls.push(Call { function, of }); + made(None, &(keys.len() + calls.len() - 1).to_string()).1 + }; + *expr = match function { + Function::Avg => { + let operator = |name: &str, args| Expr::FunctionCall { + name: name.to_owned(), + args, + }; + let real = |of| operator("__mul", vec![of, Expr::Literal(Literal::Real(1.0))]); + let sum = call(Function::Sum, of.clone().map(real)); + operator("__div", vec![sum, call(Function::Count, of)]) + } + function => call(function, of), + }; + Ok(()) +} + +/// The rows of a grouped statement: its input, whose columns are `scope`, taken into one entry +/// for each group, then HAVING, ORDER BY and the select list over the groups. Reads every row +/// of its input and holds the row it is taking in and, for each group, its grouping values and +/// each aggregate's answer so far. With `counted`, the number of rows the input has, or `kept`, +/// the count records that are its groups, the input is not read. +pub(super) struct Grouped<'a> { + pub(super) input: Box, + pub(super) scope: Scope<'a>, + pub(super) groups: Groups, + pub(super) ctx: &'a EvalContext<'a>, + pub(super) counted: Option, + pub(super) kept: Option>, + /// How many rows can leave, as [`Sort`](super::sort::Sort) has it. + pub(super) most: usize, +} + +impl Source for Grouped<'_> { + fn rows(&self, reservation: &mut Reservation, each: &mut Each<'_>) -> Result { + let groups = &self.groups; + let (scope, ctx) = (Scope::of("", &groups.columns), self.ctx); + let mut rows: Box = Box::new(Entries(self)); + if let Some(filter) = &groups.having { + let scope = scope.clone(); + rows = Box::new(Filter { + input: rows, + scope, + filter, + ctx, + }); + } + let written = (groups.order.as_slice(), groups.list.as_slice()); + listed(rows, scope, written, ctx, self.most).rows(reservation, each) + } +} + +/// One row for each group of a grouped statement, in the order of the grouping values: those +/// values, then the answer of each aggregate. +struct Entries<'s, 'a>(&'s Grouped<'a>); + +impl Source for Entries<'_, '_> { + fn rows(&self, reservation: &mut Reservation, each: &mut Each<'_>) -> Result { + let Grouped { + input, + scope, + groups, + ctx, + counted, + kept, + .. + } = self.0; + let fresh = |seen| -> Vec { + let calls = groups.calls.iter(); + calls.map(|_| Running::seen(seen)).collect() + }; + // What a group holds before any least or greatest value: its row and its entry here. + let entry = row_overhead(groups.columns.len()) + size_of::<(Key<'_, ()>, Held)>() as u64; + let mut held: BTreeMap, Held> = BTreeMap::new(); + let mut examined = 0; + if let Some(kept) = kept { + let damaged = || { + kept.read + .damaged("a kept count's record does not hold its values") + }; + let end = kept.given.prefix_end(); + let end = end.as_ref().map_or(Bound::Unbounded, Bound::Excluded); + for record in kept + .read + .kept(kept.count, Bound::Included(&kept.given), end)? + { + let (key, rows) = record?; + let values = key.values().ok_or_else(damaged)?; + let places = kept.places.iter(); + let values: Option> = + places.map(|at| values.get(*at).cloned()).collect(); + let values = values.ok_or_else(damaged)?; + let beside = entry + values.iter().map(heap_bytes).sum::(); + reservation.grow(beside)?; + held.insert( + Key(values, &groups.descending, ()), + (fresh(rows as i64), beside), + ); + } + } else if counted.is_none() { + examined = input.rows(reservation, &mut |row, bytes, reservation| { + let keys = groups.keys.iter(); + let most = keys.map(|key| most_bytes(key, scope, &row, ctx)); + let beside = entry + most.sum::(); + reservation.grow(beside)?; + let keys = groups.keys.iter(); + let values = keys + .map(|key| eval(key, scope, &row, ctx)) + .collect::>>()?; + let (running, _) = match held.entry(Key(values, &groups.descending, ())) { + Entry::Vacant(new) => new.insert((fresh(0), beside)), + Entry::Occupied(found) => { + reservation.shrink(beside); + found.into_mut() + } + }; + for (call, running) in groups.calls.iter().zip(running) { + running.add(call, scope, &row, ctx, reservation)?; + } + reservation.shrink(bytes); + Ok(true) + })?; + } + // Without GROUP BY every row is in the one group, which is there with no row too. + if groups.keys.is_empty() && held.is_empty() { + reservation.grow(entry)?; + let seen = counted.unwrap_or(0) as i64; + held.insert(Key(Vec::new(), &[], ()), (fresh(seen), entry)); + } + let rows = held + .into_iter() + .map(|(Key(mut row, _, ()), (running, beside))| { + let values = running.iter().map(|running| running.held); + let bytes = beside + values.sum::(); + row.extend(groups.calls.iter().zip(running).map(Running::answer)); + (row, bytes, 0) + }); + hand_on(rows, reservation, each)?; + Ok(examined) + } +} + +/// What is held for one group beside its grouping values: each aggregate's answer so far, and +/// the bytes of the statement's reservation that the group's entry holds. +type Held = (Vec, u64); + +/// The answer of one aggregate over the rows of one group seen so far. +struct Running { + /// How many rows took part: every row for `COUNT(*)`, otherwise those where the value is + /// not NULL. + seen: i64, + /// The sum, the least or the greatest so far; NULL until a row takes part. + value: Value, + /// The bytes of the statement's reservation that `value` holds. + held: u64, +} + +impl Running { + fn seen(seen: i64) -> Running { + Running { + seen, + value: Value::Null, + held: 0, + } + } + + /// Takes one row into the answer. A NULL takes no part in any aggregate but `COUNT(*)`. + /// The memory of the value is asked for before it is made, and given back unless the value + /// is kept as the least or the greatest so far. + fn add( + &mut self, + call: &Call, + scope: &Scope, + row: &[Value], + ctx: &EvalContext, + reservation: &mut Reservation, + ) -> Result<()> { + if let Some(of) = &call.of { + let most = most_bytes(of, scope, row, ctx); + reservation.grow(most)?; + let value = eval(of, scope, row, ctx)?; + if value == Value::Null { + reservation.shrink(most); + return Ok(()); + } + let first = self.value == Value::Null; + let better = match call.function { + Function::Count | Function::Avg => None, + Function::Sum => { + let so_far = if first { &Value::Int64(0) } else { &self.value }; + self.value = arithmetic(Arithmetic::Add, so_far, &value)?; + None + } + Function::Min => Some(Ordering::Less), + Function::Max => Some(Ordering::Greater), + }; + if better.is_some_and(|better| first || compare(&value, &self.value) == Some(better)) { + reservation.shrink(self.held); + (self.value, self.held) = (value, most); + } else { + reservation.shrink(most); + } + } + self.seen += 1; + Ok(()) + } + + /// The answer over the rows taken: a count of nothing is zero, and every other aggregate of + /// nothing is NULL. + fn answer((call, running): (&Call, Running)) -> Value { + match call.function { + Function::Count => Value::Int64(running.seen), + _ => running.value, + } + } +} diff --git a/v2/contextdb/src/query/bind.rs b/v2/contextdb/src/query/bind.rs index 0f83e4631..759d898f3 100644 --- a/v2/contextdb/src/query/bind.rs +++ b/v2/contextdb/src/query/bind.rs @@ -4,8 +4,8 @@ use std::collections::HashMap; use super::expression::{Scalar, Scope, refused, scalar, unbound}; -use crate::sql::Expr; use crate::sql::ast::{BinOp, Literal, UnaryOp}; +use crate::sql::{Expr, not_supported}; use crate::types::{ColumnType, Error, Result, Value}; /// Refuses what no row could answer: a column no table in reach has, a `$name` nothing is bound @@ -17,17 +17,16 @@ pub(crate) fn bind(expr: &Expr, scope: &Scope, params: &HashMap) /// The type of an expression's value, or `None` where it is not known before a row is read: /// NULL, a row value, and arithmetic over either. -fn kind(expr: &Expr, scope: &Scope, params: &HashMap) -> Result> { +pub(super) fn kind( + expr: &Expr, + scope: &Scope, + params: &HashMap, +) -> Result> { let kind = |expr: &Expr| kind(expr, scope, params); // The types of one side of IN: those of a row value, or the one type of anything else. - let side = |expr: &Expr| -> Result> { - match expr { - Expr::Row(items) => items.iter().map(kind).collect(), - one => Ok(vec![kind(one)?]), - } - }; + let side = |expr: &Expr| expr.sides().iter().map(kind).collect::>>(); Ok(match expr { - Expr::Column(column) => Some(scope.find(column)?.1), + Expr::Column(column) => Some(scope.one(column)?.1), Expr::Literal(literal) => match literal { Literal::Null => None, Literal::Bool(_) => Some(ColumnType::Boolean), @@ -36,6 +35,7 @@ fn kind(expr: &Expr, scope: &Scope, params: &HashMap) -> Result Some(ColumnType::Text), Literal::Vector(vector) => Some(ColumnType::Vector(vector.len())), }, + Expr::Parameter(name) if scope.open.contains(name) => None, Expr::Parameter(name) => match params.get(name).ok_or_else(|| unbound(name))? { Value::Null => None, Value::Bool(_) => Some(ColumnType::Boolean), @@ -49,9 +49,23 @@ fn kind(expr: &Expr, scope: &Scope, params: &HashMap) -> Result Some(ColumnType::TxId), }, Expr::BinaryOp { left, op, right } => { - let (left, right) = (kind(left)?, kind(right)?); + let (left, right) = (side(left)?, side(right)?); + let equality = matches!(op, BinOp::Eq | BinOp::Neq); + if left.len() != right.len() { + return Err(Error::PlanError( + "a row value needs as many values as the one it is compared with".to_owned(), + )); + } + if !equality && left.len() > 1 { + return Err(not_supported("< and > between row values")); + } if !matches!(op, BinOp::And | BinOp::Or) { - comparable(left, right)?; + for (left, right) in left.into_iter().zip(right) { + comparable(left, right)?; + if !equality && [left, right].contains(&Some(ColumnType::Json)) { + return Err(not_supported("< and > between JSON values")); + } + } } Some(ColumnType::Boolean) } @@ -94,17 +108,63 @@ fn kind(expr: &Expr, scope: &Scope, params: &HashMap) -> Result { - kind(left)?; - kind(right)?; + comparable(kind(left)?, Some(ColumnType::Vector(0)))?; + comparable(kind(right)?, Some(ColumnType::Vector(0)))?; Some(ColumnType::Real) } + Expr::Like { expr, pattern, .. } => { + comparable(kind(expr)?, Some(ColumnType::Text))?; + comparable(kind(pattern)?, Some(ColumnType::Text))?; + Some(ColumnType::Boolean) + } + Expr::Between { + expr, low, high, .. + } => { + let middle = kind(expr)?; + comparable(middle, kind(low)?)?; + comparable(middle, kind(high)?)?; + Some(ColumnType::Boolean) + } + Expr::Field { json, key, as_text } => { + let of_json = matches!(kind(json)?, None | Some(ColumnType::Json)); + let key = kind(key)?; + if !of_json || !matches!(key, None | Some(ColumnType::Text | ColumnType::Integer)) { + return Err(Error::PlanError( + "-> and ->> take a JSON value, then a field's name or a place in an array" + .to_owned(), + )); + } + Some(if *as_text { + ColumnType::Text + } else { + ColumnType::Json + }) + } + // What a subquery gives is known once its own statement is bound. + Expr::Subquery(query) => query.gives.0.get().copied(), + Expr::InSubquery { expr, query, .. } => { + comparable(kind(expr)?, query.gives.0.get().copied())?; + Some(ColumnType::Boolean) + } + Expr::RowNumber { + partition_by, + order_by, + } => { + for expr in partition_by + .iter() + .chain(order_by.iter().map(|key| &key.expr)) + { + kind(expr)?; + } + Some(ColumnType::Integer) + } }) } /// Whether values of the two types compare: the same type, or one that converts to the other /// as a write converts it (quoted text to a UUID, TIMESTAMP, JSON or VECTOR, an INTEGER to a /// REAL). A type that is not known compares with any. -fn comparable(left: Option, right: Option) -> Result<()> { +pub(super) fn comparable(left: Option, right: Option) -> Result<()> { use ColumnType::{Integer, Json, Real, Text, Timestamp, Uuid, Vector}; let (Some(left), Some(right)) = (left, right) else { return Ok(()); diff --git a/v2/contextdb/src/query/counts.rs b/v2/contextdb/src/query/counts.rs index 590e20ab9..229a86321 100644 --- a/v2/contextdb/src/query/counts.rs +++ b/v2/contextdb/src/query/counts.rs @@ -2,25 +2,28 @@ use std::ops::Bound; -use super::expression::EvalContext; +use super::expression::{EvalContext, Scope}; use super::table::collect; use super::visible::Reader; use crate::schema::Table; use crate::sql::Expr; use crate::sql::ast::BinOp; -use crate::store::{Key, Read}; -use crate::types::{Result, Value}; +use crate::store::{Key, Keys, Read}; +use crate::types::{Result, SortDirection, Value}; /// The number of rows of `table` that pass `filter`, when it is known with no row read: the /// table's own count with no filter; one kept number when the filter gives one value for each /// column of a kept count; otherwise the number of entries of the one index range the filter /// gives, when it gives one value for each of an index's leading columns and nothing else. /// +/// When the statement is explained the choice is said and no number is read: the number is 0. +/// /// `None` when the rows have to be read: for a reader that is not shown every row, for a /// filter that says more, for a table the transaction has staged a row of, and for a value too /// long for its index entry, which is there as a digest. pub(crate) fn count_without_rows( table: &Table, + scope: &Scope, filter: Option<&Expr>, reader: &Reader, ctx: &EvalContext, @@ -29,11 +32,15 @@ pub(crate) fn count_without_rows( if !reader.is_admin() { return Ok(None); } + let said = |line: &dyn Fn() -> String| ctx.said.map(|said| said.borrow_mut().push(line())); + let counted = |line: &dyn Fn() -> String, of: &dyn Fn() -> Result| { + said(line).map_or_else(of, |()| Ok(0)).map(Some) + }; let Some(filter) = filter else { - return read.count(table.id).map(Some); + return counted(&|| used(table, &[]), &|| read.count(table.id)); }; let mut terms = Vec::new(); - if !collect(table, filter, ctx, &mut terms)? { + if !collect(table, scope, filter, ctx, &mut terms)? { return Ok(None); } // Each column the filter names is given one value, once. @@ -70,9 +77,11 @@ pub(crate) fn count_without_rows( if let Some(values) = values.filter(|values| values.len() == pins.len()) { let directions: Vec<_> = count.columns.iter().map(|column| column.1).collect(); let key = Key::from_values(&values, &directions)?; - let mut kept = read.kept(count.id, Bound::Included(&key), Bound::Included(&key))?; - // A group with no row has no record. - return Ok(Some(kept.next().transpose()?.map_or(0, |(_, rows)| rows))); + return counted(&|| used(table, &count.columns), &|| { + let mut kept = read.kept(count.id, Bound::Included(&key), Bound::Included(&key))?; + // A group with no row has no record. + Ok(kept.next().transpose()?.map_or(0, |(_, rows)| rows)) + }); } } let columns = &table.meta.columns; @@ -89,15 +98,42 @@ pub(crate) fn count_without_rows( if entry.cut.is_some() { return Ok(None); } - let to = entry.key.prefix_end(); - let to = to.as_ref().map_or(Bound::Unbounded, Bound::Excluded); - let mut entries = 0; - for found in read.index(table.index_ids[at], Bound::Included(&entry.key), to)? { - found?; - entries += 1; - } - return Ok(Some(entries)); + let given = names(table, pins.iter().map(|pin| pin.0)); + said(&|| format!("IndexScan {{ index: {} }}", index.name)); + said(&|| format!(" predicates_pushed: [{given}]")); + return counted(&|| undeclared(table, &given), &|| { + let (id, to) = (table.index_ids[at], entry.key.prefix_end()); + let to = to.as_ref().map_or(Bound::Unbounded, Bound::Excluded); + read.counted(Keys::Index(id), Bound::Included(&entry.key), to, usize::MAX) + }); } } Ok(None) } + +/// The names of `columns` of `table`, between commas. +pub(super) fn names(table: &Table, columns: impl Iterator) -> String { + let names: Vec<&str> = columns + .map(|at| table.meta.columns[at].name.as_str()) + .collect(); + names.join(", ") +} + +/// The line of an explanation for a count the kept count over `columns` answers. +pub(super) fn used(table: &Table, columns: &[(usize, SortDirection)]) -> String { + let columns = names(table, columns.iter().map(|column| column.0)); + format!("maintained count: used ({columns})") +} + +/// The line of an explanation for a count that no kept count answers: the statement that would +/// declare one with the columns `wanted`, beside the lists the table keeps already. +pub(super) fn undeclared(table: &Table, wanted: &str) -> String { + let kept = table.rules.counts.iter().map(|count| { + let columns = names(table, count.columns.iter().map(|column| column.0)); + format!("({columns}), ") + }); + let (name, kept) = (&table.name, kept.collect::()); + format!( + "maintained count: not declared \u{2014} ALTER TABLE {name} SET MAINTAIN COUNT {kept}({wanted}) makes this O(1)" + ) +} diff --git a/v2/contextdb/src/query/expression.rs b/v2/contextdb/src/query/expression.rs index 66e985efa..e92806b58 100644 --- a/v2/contextdb/src/query/expression.rs +++ b/v2/contextdb/src/query/expression.rs @@ -1,32 +1,46 @@ //! The expression evaluator, and how two values compare and sort. +use std::cell::RefCell; use std::cmp::Ordering; -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; + +use serde_json::{Number, Value as Json}; use super::bind::bind; use crate::schema::Table; -use crate::sql::Expr; -use crate::sql::ast::{BinOp, ColumnRef, Literal, UnaryOp}; +use crate::sql::ast::{BinOp, ColumnRef, Literal, Select, UnaryOp}; +use crate::sql::{Expr, Plan, not_supported}; use crate::types::{ - ColumnDef, ColumnType, Error, Result, Uuid, Value, heap_bytes, timestamp_millis, + ColumnDef, ColumnType, Error, Result, Value, heap_bytes, timestamp_millis, vector_from_text, }; -#[cfg(test)] -mod tests; - /// The columns an expression has in reach: for each table of the statement, in the order their /// values stand in a row, the name that qualifies its columns and the columns themselves. -#[derive(Default)] +#[derive(Default, Clone)] pub(crate) struct Scope<'a> { relations: Vec<(&'a str, &'a [ColumnDef])>, + /// Whether the statement's own names meet here, so a name two columns answer to is refused. + pub(super) checked: bool, + /// The `$name`s an explained search binds nothing to, each of no known type. + pub(super) open: Vec, } impl<'a> Scope<'a> { /// The scope of one table's columns. pub(crate) fn of(qualifier: &'a str, columns: &'a [ColumnDef]) -> Self { - Scope { - relations: vec![(qualifier, columns)], - } + Scope::default().and(qualifier, columns) + } + + /// This scope with one more relation after it: the columns of a row of both, those of + /// the new relation last. + pub(crate) fn and(mut self, qualifier: &'a str, columns: &'a [ColumnDef]) -> Self { + self.relations.push((qualifier, columns)); + self + } + + /// Every column in reach, in the order their values stand in a row. + pub(super) fn columns(&self) -> impl Iterator { + self.relations.iter().flat_map(|(_, columns)| *columns) } /// Where a column sits in a row, and its type. A name no table in reach has is @@ -49,6 +63,20 @@ impl<'a> Scope<'a> { Err(self.missing(column)) } + /// As `find`, for binding: where the statement's own names can clash, a name that more than + /// one column in reach answers to is refused, as Postgres refuses it. + pub(super) fn one(&self, column: &ColumnRef) -> Result<(usize, ColumnType)> { + let (table, name) = (column.table.as_deref(), &column.column); + let reached = self.relations.iter(); + let reached = reached.filter(|(at, _)| table.is_none_or(|table| table == *at)); + let named = reached.flat_map(|(_, columns)| columns.iter()); + if self.checked && named.filter(|declared| declared.name == *name).count() > 1 { + let refused = format!("column reference \"{name}\" is ambiguous"); + return Err(Error::PlanError(refused)); + } + self.find(column) + } + /// The refusal of a column that is not in reach, under the qualifier it was written with or /// else the first table. fn missing(&self, column: &ColumnRef) -> Error { @@ -66,12 +94,16 @@ impl<'a> Scope<'a> { } /// What an expression is worked out with beside its row: the values the statement bound, the -/// statement's one time in milliseconds, which `NOW()` answers with, and the row's distance -/// when a similarity search found it. +/// statement's one time in milliseconds, which `NOW()` answers with, and the values of the +/// statement's subqueries, each worked out once before any row; and, when the statement is +/// explained and not run, the list each choice it makes is said into and the statement. +#[derive(Clone, Copy)] pub(crate) struct EvalContext<'a> { - params: &'a HashMap, + pub(super) params: &'a HashMap, now: i64, - distance: Option, + subqueries: &'a [(usize, Vec)], + pub(super) said: Option<&'a RefCell>>, + pub(super) explained: Option<&'a Plan>, } impl<'a> EvalContext<'a> { @@ -79,14 +111,30 @@ impl<'a> EvalContext<'a> { EvalContext { params, now, - distance: None, + subqueries: &[], + said: None, + explained: None, } } - /// The context for a row a similarity search found at this distance: every `<=>` in an - /// expression is that number as it is. - pub(super) fn found(self, distance: Option) -> Self { - EvalContext { distance, ..self } + /// The statement's one time in milliseconds. + pub(crate) fn now(&self) -> i64 { + self.now + } + + /// The context of a statement whose subqueries gave these values, each under the place its + /// text begins in the statement: one value for each row of each. + pub(crate) fn over(self, subqueries: &'a [(usize, Vec)]) -> Self { + EvalContext { subqueries, ..self } + } + + /// The values of one subquery of the statement, found by its place, which every copy of + /// it keeps. + pub(super) fn subquery(&self, query: &Select) -> Result<&'a [Value]> { + let found = self.subqueries.iter().find(|(at, _)| *at == query.at.0); + found.map(|(_, values)| values.as_slice()).ok_or_else(|| { + Error::PlanError("a subquery has values only where its statement runs it".to_owned()) + }) } } @@ -96,8 +144,8 @@ impl<'a> EvalContext<'a> { /// between values that do not compare, is unknown: it gives NULL, and a filter keeps a row /// only for TRUE. /// -/// A distance, `column <=> vector`, has no value of its own here: only a similarity search -/// gives a row one, through the context, so without one it is refused by name. +/// A distance, `left <=> right`, is worked out from the two vectors as the vector part works it +/// out, so a row's distance is the same number wherever it is written; NULL when either side is. pub(crate) fn eval(expr: &Expr, scope: &Scope, row: &[Value], ctx: &EvalContext) -> Result { let value = |expr: &Expr| eval(expr, scope, row, ctx); Ok(match expr { @@ -117,6 +165,14 @@ pub(crate) fn eval(expr: &Expr, scope: &Scope, row: &[Value], ctx: &EvalContext) Expr::Parameter(name) => ctx.params.get(name).cloned().ok_or_else(|| unbound(name))?, Expr::BinaryOp { left, op, right } => { let holds: fn(Ordering) -> bool = match op { + BinOp::Eq | BinOp::Neq + if matches!((&**left, &**right), (Expr::Row(_), _) | (_, Expr::Row(_))) => + { + let equal = rows_equal(&side(left, value)?, &side(right, value)?); + return Ok(equal.map_or(Value::Null, |equal| { + Value::Bool(equal == (*op == BinOp::Eq)) + })); + } BinOp::And | BinOp::Or => { // The value that decides the answer alone: FALSE for AND, TRUE for OR. let settles = *op == BinOp::Or; @@ -175,48 +231,171 @@ pub(crate) fn eval(expr: &Expr, scope: &Scope, row: &[Value], ctx: &EvalContext) list, negated, } => { - // TRUE when an item equals the left side, else unknown when any equality was. - let left = side(expr, value)?; - let mut found = Some(false); - for item in list { - let item = side(item, value)?; - if item.len() != left.len() { - return Err(Error::PlanError( - "a row value beside IN needs as many values as its partner".to_owned(), - )); - } - match rows_equal(&left, &item) { - Some(true) => { - found = Some(true); - break; - } - Some(false) => {} - None => found = None, + let items = list.iter().map(|item| side(item, value)); + among(&side(expr, value)?, items, *negated)? + } + Expr::InSubquery { + expr, + query, + negated, + } => { + let items = ctx.subquery(query)?.iter().map(std::slice::from_ref); + among(&[value(expr)?], items.map(Ok), *negated)? + } + // A subquery that found no row is NULL. + Expr::Subquery(query) => ctx.subquery(query)?.first().cloned().unwrap_or(Value::Null), + Expr::Row(_) => { + return Err(Error::PlanError( + "a row value, (a, b), stands only on either side of =, <> or IN".to_owned(), + )); + } + Expr::Distance { left, right } => match (numbers(value(left)?)?, numbers(value(right)?)?) { + (Some(left), Some(right)) if left.len() == right.len() => { + Value::Float64(crate::vector::distance(&left, &right)) + } + (Some(_), Some(_)) => { + return Err(Error::PlanError( + "<=> needs two vectors of one length".to_owned(), + )); + } + _ => Value::Null, + }, + Expr::Like { + expr, + pattern, + negated, + } => match (value(expr)?, value(pattern)?) { + (Value::Text(text), Value::Text(pattern)) => { + Value::Bool(like(&text, &pattern) != *negated) + } + _ => Value::Null, + }, + Expr::Between { + expr, + low, + high, + negated, + } => { + let middle = value(expr)?; + let above = compare(&middle, &value(low)?).map(Ordering::is_ge); + let below = compare(&middle, &value(high)?).map(Ordering::is_le); + match (above, below) { + (Some(false), _) | (_, Some(false)) => Value::Bool(*negated), + (Some(true), Some(true)) => Value::Bool(!*negated), + _ => Value::Null, + } + } + Expr::Field { json, key, as_text } => { + let field = match (value(json)?, value(key)?) { + (Value::Json(json), Value::Text(key)) => json.get(key.as_str()).cloned(), + (Value::Json(json), Value::Int64(place)) => { + let place = usize::try_from(place).ok(); + place.and_then(|place| json.get(place).cloned()) } + _ => None, + }; + match field { + None => Value::Null, + Some(field) if !*as_text => Value::Json(field), + Some(serde_json::Value::Null) => Value::Null, + Some(serde_json::Value::String(text)) => Value::Text(text), + Some(field) => Value::Text(field.to_string()), } - found.map_or(Value::Null, |found| Value::Bool(found != *negated)) } - Expr::Row(_) => { + Expr::RowNumber { .. } => { return Err(Error::PlanError( - "a row value, (a, b), stands only on either side of IN".to_owned(), + "ROW_NUMBER() has a value only for the rows its window numbered".to_owned(), )); } - Expr::Distance { .. } => Value::Float64(ctx.distance.ok_or_else(|| { - Error::PlanError( - "<=> has a value only for the rows of a similarity search, SELECT ... ORDER BY \ - column <=> vector LIMIT k, and in that statement's select list" - .to_owned(), - ) - })?), }) } +/// Whether `left` is among `items`: TRUE when one of them equals it, else unknown when any +/// equality was. +fn among>( + left: &[Value], + items: impl Iterator>, + negated: bool, +) -> Result { + let mut found = Some(false); + for item in items { + let item = item?; + if item.as_ref().len() != left.len() { + return Err(Error::PlanError( + "a row value beside IN needs as many values as its partner".to_owned(), + )); + } + match rows_equal(left, item.as_ref()) { + Some(true) => return Ok(Value::Bool(!negated)), + Some(false) => {} + None => found = None, + } + } + Ok(found.map_or(Value::Null, |found| Value::Bool(found != negated))) +} + +/// Whether a text matches a LIKE pattern: `%` stands for any run of characters, `_` for any +/// one, and the character after a backslash for itself. +fn like(text: &str, pattern: &str) -> bool { + let (mut text, mut pattern) = (text.chars(), pattern.chars()); + // The pattern after its last `%` so far, and the text that `%` has not yet taken. + let mut retry: Option<(std::str::Chars, std::str::Chars)> = None; + loop { + let (mut after, mut rest) = (pattern.clone(), text.clone()); + let matched = match after.next() { + Some('%') => { + retry = Some((after.clone(), text.clone())); + pattern = after; + continue; + } + None if rest.next().is_none() => return true, + None => false, + Some('_') => rest.next().is_some(), + Some(written) => { + let exact = if written == '\\' { after.next() } else { None }; + rest.next() == Some(exact.unwrap_or(written)) + } + }; + if matched { + (pattern, text) = (after, rest); + } else { + // The last `%` takes one more character, if the text has one. + let Some((after, from)) = &mut retry else { + return false; + }; + if from.next().is_none() { + return false; + } + (pattern, text) = (after.clone(), from.clone()); + } + } +} + +/// Whether `expr`, or an expression inside it, is one `is` answers true for. +pub(super) fn holds(expr: &Expr, is: fn(&Expr) -> bool) -> bool { + let inner = crate::sql::inside(expr); + is(expr) || inner.into_iter().any(|inner| holds(inner, is)) +} + +/// The numbers of a side of `<=>`: a vector, or a text that spells one, such as '[1, 0]'; `None` +/// for NULL. Anything else is refused. +pub(super) fn numbers(value: Value) -> Result>> { + let vector = match value { + Value::Null => return Ok(None), + Value::Vector(vector) => Some(vector), + Value::Text(text) => vector_from_text(&text), + _ => None, + }; + let refused = "<=> needs a vector on both sides: write [1.0, 0.0], its text '[1, 0]', or a \ + $name bound to a vector"; + vector + .map(Some) + .ok_or_else(|| Error::PlanError(refused.to_owned())) +} + /// The values of one side of IN: those of a row value, or the one value of anything else. fn side(expr: &Expr, value: impl Fn(&Expr) -> Result) -> Result> { - match expr { - Expr::Row(items) => items.iter().map(value).collect(), - one => Ok(vec![value(one)?]), - } + expr.sides().iter().map(value).collect() } /// Whether two row values of one length are equal, as standard SQL has it: FALSE as soon as one @@ -236,12 +415,7 @@ fn rows_equal(left: &[Value], right: &[Value]) -> Option { /// The most memory the value of an expression can take outside its own cell. It is known /// before the expression is worked out, so the memory is asked for before the value is made. -pub(super) fn most_bytes( - expr: &Expr, - scope: &Scope, - row: &[Value], - params: &HashMap, -) -> u64 { +pub(super) fn most_bytes(expr: &Expr, scope: &Scope, row: &[Value], ctx: &EvalContext) -> u64 { match expr { Expr::Column(column) => { let at = scope.find(column).ok(); @@ -249,52 +423,43 @@ pub(super) fn most_bytes( } Expr::Literal(Literal::Text(text)) => text.len() as u64, Expr::Literal(Literal::Vector(vector)) => size_of_val(vector.as_slice()) as u64, - Expr::Parameter(name) => params.get(name).map_or(0, heap_bytes), + Expr::Parameter(name) => ctx.params.get(name).map_or(0, heap_bytes), Expr::FunctionCall { name, args } if matches!(scalar(name), Some(Scalar::Coalesce)) => { - let each = args.iter().map(|arg| most_bytes(arg, scope, row, params)); + let each = args.iter().map(|arg| most_bytes(arg, scope, row, ctx)); each.max().unwrap_or(0) } + Expr::Subquery(query) => { + let first = ctx.subquery(query).ok().and_then(|found| found.first()); + first.map_or(0, heap_bytes) + } + // A field is no larger than the JSON value it is taken from. + Expr::Field { json, .. } => most_bytes(json, scope, row, ctx), // Everything else gives a number, a truth, a time or NULL. _ => 0, } } -/// Binds the expression against the table, then marks in `read` each column it reads. The -/// column on the left of a distance is not marked: the search gives a row's distance. +/// Binds the expression against the scope, then marks in `read`, which has one place for each +/// column of the scope, each column it reads. pub(crate) fn reads( expr: &Expr, - table: &Table, + scope: &Scope, params: &HashMap, read: &mut [bool], ) -> Result<()> { - let scope = table.scope(); - bind(expr, &scope, params)?; - mark(expr, &scope, read); + bind(expr, scope, params)?; + mark(expr, scope, read); Ok(()) } -fn mark(expr: &Expr, scope: &Scope, read: &mut [bool]) { - let mut all = |items: &[Expr]| items.iter().for_each(|item| mark(item, scope, read)); - match expr { - Expr::Column(column) => { - if let Ok((at, _)) = scope.find(column) { - read[at] = true; - } - } - Expr::Literal(_) | Expr::Parameter(_) => {} - Expr::BinaryOp { left, right, .. } => { - mark(left, scope, read); - mark(right, scope, read); - } - Expr::UnaryOp { operand, .. } - | Expr::IsNull { expr: operand, .. } - | Expr::Distance { right: operand, .. } => mark(operand, scope, read), - Expr::FunctionCall { args: items, .. } | Expr::Row(items) => all(items), - Expr::InList { expr, list, .. } => { - all(list); - mark(expr, scope, read); - } +pub(super) fn mark(expr: &Expr, scope: &Scope, read: &mut [bool]) { + if let Expr::Column(column) = expr + && let Ok((at, _)) = scope.find(column) + { + read[at] = true; } + let inner = crate::sql::inside(expr).into_iter(); + inner.for_each(|inner| mark(inner, scope, read)); } /// Where a column sits in a row of its table. @@ -310,16 +475,9 @@ fn out_of_range() -> Error { Error::PlanError("integer out of range".to_owned()) } -/// The refusal of something this version of the library does not do, by its name. -pub(super) fn unsupported(what: &str) -> Error { - Error::PlanError(format!( - "{what} is not supported in this version of the library" - )) -} - /// The refusal of a call [`eval`] does not work out. pub(super) fn refused(name: &str) -> Error { - unsupported(&format!("the function {name}")) + not_supported(&format!("the function {name}")) } /// A function that gives one value for one row. @@ -409,37 +567,92 @@ fn truth(value: &Value) -> Option { /// /// A REAL has one rule for `=`, ORDER BY and the bytes of a key: the two zeros are one value, /// and every NaN is one value, equal to itself and above positive infinity. A whole number -/// compares with a REAL as a REAL, and a UUID or a TIMESTAMP with the text that spells one. +/// compares with a REAL by exact value, and a UUID, a TIMESTAMP or a JSON value with the text that +/// spells one; two JSON values compare as [`json`] says. Two vectors compare number by number, +/// the shorter first when it is the other's beginning, as pgvector compares them; a vector +/// compares with the text that spells one. pub(super) fn compare(left: &Value, right: &Value) -> Option { + // Each pair of two types is written one way round; the other way round is its reverse. + ordered(left, right).or_else(|| Some(ordered(right, left)?.reverse())) +} + +fn ordered(left: &Value, right: &Value) -> Option { let reals = |left: f64, right: f64| { let unordered = || left.is_nan().cmp(&right.is_nan()); left.partial_cmp(&right).unwrap_or_else(unordered) }; + // NaN above all, then the whole parts as 128-bit numbers (the cast saturates), then the rest. + let mixed = |whole: i64, real: f64| { + let parts = (real.is_nan(), real.trunc() as i128); + let rest = || reals(0.0, real.fract()); + (false, i128::from(whole)).cmp(&parts).then_with(rest) + }; Some(match (left, right) { (Value::Int64(left), Value::Int64(right)) => left.cmp(right), (Value::Float64(left), Value::Float64(right)) => reals(*left, *right), - (Value::Int64(left), Value::Float64(right)) => reals(*left as f64, *right), - (Value::Float64(left), Value::Int64(right)) => reals(*left, *right as f64), + (Value::Int64(left), Value::Float64(right)) => mixed(*left, *right), (Value::Text(left), Value::Text(right)) => left.cmp(right), (Value::Bool(left), Value::Bool(right)) => left.cmp(right), (Value::Timestamp(left), Value::Timestamp(right)) => left.cmp(right), (Value::TxId(left), Value::TxId(right)) => left.cmp(right), (Value::Uuid(left), Value::Uuid(right)) => left.cmp(right), (Value::Uuid(left), Value::Text(right)) => left.cmp(&right.parse().ok()?), - (Value::Text(left), Value::Uuid(right)) => left.parse::().ok()?.cmp(right), (Value::Timestamp(left), Value::Text(right)) => left.cmp(×tamp_millis(right)?), - (Value::Text(left), Value::Timestamp(right)) => timestamp_millis(left)?.cmp(right), + (Value::Json(left), Value::Json(right)) => json(left, right), + (Value::Json(left), Value::Text(right)) => json(left, &serde_json::from_str(right).ok()?), + (Value::Vector(left), Value::Vector(right)) => left.partial_cmp(right)?, + (Value::Vector(left), Value::Text(right)) => left.partial_cmp(&vector_from_text(right)?)?, _ => return None, }) } +/// How two JSON values compare, as Postgres compares `jsonb`: null, then a string, a number, a +/// boolean, an array and an object; arrays and objects by their size, then item by item or pair +/// by pair, a key by its bytes; numbers by exact value however written, so `5` is `5.0`. +fn json(left: &Json, right: &Json) -> Ordering { + let number = |n: &Number| n.as_i64().map(Value::Int64); + let number = |n: &Number| number(n).unwrap_or(Value::Float64(n.as_f64().unwrap_or_default())); + // What tells apart whole numbers that are one 64-bit real: their exact value. + let exact = |n: &Number| n.as_i128().or(Some(n.as_f64()? as i128)); + // A kind's rank, going down. + let kind = |j: &Json| (j.is_null(), j.is_string(), j.is_number(), j.is_boolean()); + let kind = |j: &Json| (kind(j), j.is_array()); + match (left, right) { + (Json::Number(l), Json::Number(r)) => { + sort_order(&number(l), &number(r)).then(exact(l).cmp(&exact(r))) + } + (Json::String(l), Json::String(r)) => l.cmp(r), + (Json::Bool(l), Json::Bool(r)) => l.cmp(r), + (Json::Array(l), Json::Array(r)) => l.len().cmp(&r.len()).then_with(|| { + let mut items = l.iter().zip(r).map(|(l, r)| json(l, r)); + items.find(|order| order.is_ne()).unwrap_or(Ordering::Equal) + }), + (Json::Object(l), Json::Object(r)) => l.len().cmp(&r.len()).then_with(|| { + // Pairs in the order Postgres stores them, a shorter key first. + let [l, r] = [l, r].map(|pairs| { + let pairs = pairs.iter().map(|(key, value)| ((key.len(), key), value)); + pairs.collect::>() + }); + let pairs = l.iter().zip(&r); + let mut pairs = pairs.map(|(l, r)| l.0.1.cmp(r.0.1).then_with(|| json(l.1, r.1))); + pairs.find(|order| order.is_ne()).unwrap_or(Ordering::Equal) + }), + _ => kind(right).cmp(&kind(left)), + } +} + /// How two values sort going up: as they compare, with NULL after every value. Going down is -/// the reverse, which puts NULL first. +/// the reverse, which puts NULL first. Two values that do not compare are the same only when +/// they are equal; any others are told apart by how each is written, so two different values +/// never sort as one. pub(super) fn sort_order(left: &Value, right: &Value) -> Ordering { match (left, right) { (Value::Null, Value::Null) => Ordering::Equal, (Value::Null, _) => Ordering::Greater, (_, Value::Null) => Ordering::Less, - _ => compare(left, right).unwrap_or(Ordering::Equal), + _ => compare(left, right).unwrap_or_else(|| match left == right { + true => Ordering::Equal, + false => format!("{left:?}").cmp(&format!("{right:?}")), + }), } } diff --git a/v2/contextdb/src/query/expression/tests.rs b/v2/contextdb/src/query/expression/tests.rs deleted file mode 100644 index 74cd7f2d3..000000000 --- a/v2/contextdb/src/query/expression/tests.rs +++ /dev/null @@ -1,51 +0,0 @@ -//! The evaluator itself, over expressions that read no column. - -use std::collections::HashMap; - -use super::eval; -use crate::query::{EvalContext, Scope}; -use crate::sql::Expr; -use crate::sql::ast::{BinOp, Literal, UnaryOp}; -use crate::types::Value; - -/// An expression that reads no column, worked out. -fn worked_out(expr: &Expr) -> Value { - let bound = HashMap::new(); - eval(expr, &Scope::default(), &[], &EvalContext::new(&bound, 0)) - .expect("an expression of literals") -} - -fn joined(left: Literal, op: BinOp, right: Literal) -> Expr { - Expr::BinaryOp { - left: Box::new(Expr::Literal(left)), - op, - right: Box::new(Expr::Literal(right)), - } -} - -#[test] -fn null_is_unknown_unless_the_other_side_settles_the_answer() { - let (null, yes, no) = (Literal::Null, Literal::Bool(true), Literal::Bool(false)); - let and = |left: &Literal, right: &Literal| { - worked_out(&joined(left.clone(), BinOp::And, right.clone())) - }; - let or = |left: &Literal, right: &Literal| { - worked_out(&joined(left.clone(), BinOp::Or, right.clone())) - }; - assert_eq!(and(&null, &no), Value::Bool(false)); - assert_eq!(and(&no, &null), Value::Bool(false)); - assert_eq!(and(&null, &yes), Value::Null); - assert_eq!(and(&yes, &yes), Value::Bool(true)); - assert_eq!(or(&null, &yes), Value::Bool(true)); - assert_eq!(or(&yes, &null), Value::Bool(true)); - assert_eq!(or(&null, &no), Value::Null); - assert_eq!(or(&no, &no), Value::Bool(false)); - - let not_null = Expr::UnaryOp { - op: UnaryOp::Not, - operand: Box::new(Expr::Literal(Literal::Null)), - }; - assert_eq!(worked_out(¬_null), Value::Null); - let null_equals_null = joined(Literal::Null, BinOp::Eq, Literal::Null); - assert_eq!(worked_out(&null_equals_null), Value::Null); -} diff --git a/v2/contextdb/src/query/for_write.rs b/v2/contextdb/src/query/for_write.rs index ce265893b..b0278b2ee 100644 --- a/v2/contextdb/src/query/for_write.rs +++ b/v2/contextdb/src/query/for_write.rs @@ -1,8 +1,6 @@ //! The rows an UPDATE or DELETE acts on, handed over a batch at a time. -use std::collections::HashMap; - -use super::expression::reads; +use super::expression::{EvalContext, reads}; use super::table::Source; use super::visible::{Reader, Visible}; use crate::memory::{Budget, Reservation}; @@ -23,8 +21,8 @@ pub(crate) struct Asked<'a> { /// cell it is stored as and never loaded. pub needed: &'a [bool], pub reader: &'a Reader, - pub params: &'a HashMap, - pub now: i64, + /// What the filter is worked out with: the statement's time and the values of its SELECTs. + pub ctx: EvalContext<'a>, } /// The most rows one batch holds. @@ -54,13 +52,13 @@ pub(crate) fn rows_for_write( let Asked { table, filter, .. } = *asked; let mut filtered = vec![false; table.meta.columns.len()]; if let Some(filter) = filter { - reads(filter, table, asked.params, &mut filtered)?; + reads(filter, &table.scope(), asked.ctx.params, &mut filtered)?; } // What the reader's filter holds is given back when the batch is found. let mut seeing = budget.reserve(0, "query")?; let visible = Visible::new(table, catalog, asked.reader, &mut seeing)?; - let source = Source::new(table, filter, asked.params, asked.now, read, visible) - .reading(filtered, asked.needed); + let source = + Source::new(table, filter, &asked.ctx, read, visible).reading(filtered, asked.needed); let mut path = source.choose(&[], asked.assigned)?; path.one = false; let mut reservation = budget.reserve(0, "query")?; diff --git a/v2/contextdb/src/query/graph.rs b/v2/contextdb/src/query/graph.rs new file mode 100644 index 000000000..dc3eafb09 --- /dev/null +++ b/v2/contextdb/src/query/graph.rs @@ -0,0 +1,663 @@ +//! A graph pattern: the rows `GRAPH_TABLE(...)` gives over a table of edges. +//! +//! One step followed once is a single hop: one match for each edge. Anything longer is a walk, +//! breadth first: a node is reached once, at the shallowest depth, from the start that comes +//! first, and a start is reached again when a cycle within the range comes back to it. What the +//! reader may not see is taken out before anything is matched: an edge is followed only when +//! the reader may see its row and the nodes at both its ends. Every edge and every row that +//! carries a node is read through the one table source, with the reader's filter in it. + +use std::borrow::Cow; +use std::cell::{Cell, RefCell}; +use std::collections::btree_map::Entry; +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::iter::once; +use std::sync::LazyLock; + +use super::bind::bind; +use super::expression::{EvalContext, Scope, eval, reads}; +use super::plan::{self, Each, Given}; +use super::row_overhead; +use super::table::{Source, as_key, equal, known}; +use super::visible::Visible; +use crate::memory::Reservation; +use crate::schema::Table; +use crate::sql::Expr; +use crate::sql::ast::{BinOp, ColumnRef}; +use crate::sql::plan::{EdgeDirection, EdgeStep, GraphTable, NodePattern}; +use crate::types::{ColumnDef, ColumnType, Error, IndexDecl, Result, Uuid, Value}; + +/// The columns that hold the two ends of an edge: where it leaves, then where it arrives. +const ENDS: [&str; 2] = ["source_id", "target_id"]; + +/// The bytes a walk is counted for each node it remembers: the node's id, and beside it the +/// node's place among the nodes met and among those still to follow. +const NODE: u64 = 16 + 24; + +/// What qualifies the columns of a pattern in a refusal: a pattern has no name of its own. +const PATTERN: &str = "GRAPH_TABLE"; + +/// What every match has: the id of its last node, and how many edges lead to that node from +/// the first. The first of the two is also what each node the pattern names has. +static REACHED: LazyLock<[ColumnDef; 2]> = LazyLock::new(|| { + let column = |name: &str, column_type| ColumnDef { + name: name.to_owned(), + column_type, + nullable: false, + primary_key: false, + unique: false, + default: None, + }; + [ + column("id", ColumnType::Uuid), + column("depth", ColumnType::Integer), + ] +}); + +/// What takes the matches of a pattern: the nodes of one match in the order the pattern names +/// them, and how many edges lead from the first to the last. Answers false when it wants no +/// more. +type Match<'e> = dyn FnMut(&[Uuid], u32, &mut Reservation) -> Result + 'e; + +/// What takes the nodes one step reaches: the start, the node reached and its depth. +type Reached<'e> = dyn FnMut(Uuid, Uuid, u32, &mut Reservation) -> Result + 'e; + +/// What takes the edges at a node: the near end of one, then its far end. +type Ends<'e> = dyn FnMut(Uuid, Uuid, &mut Reservation) -> Result + 'e; + +/// What takes the rows of one read. +type Rows<'e> = dyn FnMut(&[Value], &mut Reservation) -> Result + 'e; + +/// One pattern over one table of edges, for one reader. +pub(super) struct Graph<'a> { + given: &'a Given<'a>, + edges: &'a Table, + /// Where the columns of `ENDS` are in a row of `edges`, and where its `edge_type` is. + ends: [usize; 2], + typed: usize, + steps: &'a [EdgeStep], + /// The nodes the pattern's filter names for its first node, in the order it names them. + /// `None` when it names none: then every node is a start. + starts: Option>, + /// True when they are the one node an `=` names: one the reader may not see is then the + /// refusal of the rule that hides it, where a hidden node of a list is left out. + one: bool, + /// A single hop whose filter names its second node and not its first is matched from the + /// second: the edges at a node are read from there, the other way round. + reversed: bool, + /// The tables that can hide a node from the reader: those with an `id UUID` column whose + /// rows the reader's filter is asked about. + nodes: Vec<&'a Table>, + /// The tables with an `id UUID` column whose rows need a grant, for a reader with no + /// principal that can hold one, each without that rule: a row of one that carries a node + /// and that the reader's other rules let through is `PrincipalRequired`. + closed: Vec
, + /// The columns of a match before COLUMNS: `REACHED`, then the id of each node the + /// pattern names, which are the nodes at these places in a match. + scope: Scope<'a>, + named: Vec, + filter: Option<&'a Expr>, + /// For each item of COLUMNS, the column of `scope` it gives. + picks: Vec, + /// Whether the reader may see each node met so far. Empty when no table can hide one. + seen: RefCell>, + /// The stored rows read so far. + examined: Cell, +} + +impl<'a> Graph<'a> { + /// The pattern as one statement matches it, and the scope of the rows it gives. Refuses, + /// before any row is read: a table that is not there or holds no edges, a step that cannot + /// be followed, a reader the edge table cannot answer, a table that carries nodes with no + /// key or index that begins with `id`, and a WHERE or a COLUMNS that reads anything but + /// `id`, `depth` and the id of a node the pattern names. + pub(super) fn new( + pattern: &'a GraphTable, + given: &'a Given<'a>, + ) -> Result<(Graph<'a>, Scope<'a>)> { + let (catalog, reader, budget) = (given.catalog, given.reader, given.budget); + let name = &pattern.edge_table; + let edges = catalog + .table(name) + .ok_or_else(|| Error::TableNotFound(name.clone()))?; + let column = |table: &Table, name: &str, column_type: ColumnType| { + let mut columns = table.meta.columns.iter(); + columns.position(|column| column.name == name && column.column_type == column_type) + }; + let (Some(source), Some(target), Some(typed)) = ( + column(edges, ENDS[0], ColumnType::Uuid), + column(edges, ENDS[1], ColumnType::Uuid), + column(edges, "edge_type", ColumnType::Text), + ) else { + return Err(Error::PlanError(format!( + "{name} holds no edges: a graph pattern needs a table with source_id UUID, \ + target_id UUID and edge_type TEXT" + ))); + }; + for step in &pattern.steps { + if step.min == 0 || step.min > step.max { + return Err(Error::PlanError(format!( + "a step of a graph pattern is followed at least once, and its lower bound \ + is not above its upper bound: {{{},{}}} cannot be followed", + step.min, step.max + ))); + } + } + let mut seeing = budget.reserve(0, "query")?; + let visible = Visible::new(edges, catalog, reader, &mut seeing)?; + + let (mut nodes, mut closed) = (Vec::new(), Vec::new()); + for table in catalog.tables() { + let Some(id) = column(table, "id", ColumnType::Uuid) else { + continue; + }; + let mut asked = vec![false; table.meta.columns.len()]; + let mut seeing = budget.reserve(0, "query")?; + let needs_principal = match Visible::new(table, catalog, reader, &mut seeing) { + Ok(visible) => { + visible.reads(&mut asked); + false + } + Err(Error::PrincipalRequired { .. }) => true, + Err(other) => return Err(other), + }; + if !needs_principal && !asked.contains(&true) { + continue; + } + let leads = |index: &IndexDecl| { + let first = index.columns.first(); + index.json_path.is_empty() && first.is_some_and(|(name, _)| name == "id") + }; + if table.key.first() != Some(&id) && !table.meta.indexes.iter().any(leads) { + return Err(Error::PlanError(format!( + "a graph pattern asks {} which nodes this handle may see, and needs a key \ + or an index that begins with its id", + table.name + ))); + } + if needs_principal { + let mut open = table.clone(); + open.rules.acl = None; + closed.push(open); + } else { + nodes.push(table); + } + } + + // What a match is: its last node and depth, then each node the pattern names. + let all = std::iter::once(&pattern.start).chain(pattern.steps.iter().map(|step| &step.to)); + let aliases = all.map(|node| node.alias.as_deref()); + let named: Vec<(usize, &str)> = aliases + .enumerate() + .filter_map(|(at, alias)| Some((at, alias?))) + .collect(); + let mut scope = Scope::of(PATTERN, &REACHED[..]); + for (_, alias) in &named { + scope = scope.and(alias, &REACHED[..1]); + } + let filter = pattern.filter.as_ref(); + if let Some(filter) = filter { + bind(filter, &scope, given.params)?; + } + let mut picks = Vec::new(); + let mut given_as = Vec::new(); + for column in &pattern.columns { + let Expr::Column(named) = &column.expr else { + return Err(Error::PlanError( + "COLUMNS gives id, depth and the id of a node the pattern names, and works \ + nothing out of them" + .to_owned(), + )); + }; + let (at, column_type) = scope.find(named).map_err(|_| { + let of = named.table.as_ref().map(|node| format!("{node}.")); + let (of, column) = (of.unwrap_or_default(), &named.column); + Error::PlanError(format!("project column not found: {of}{column}")) + })?; + given_as.push(ColumnDef { + name: column.name(), + column_type, + ..REACHED[0].clone() + }); + picks.push(at); + } + let gives = Scope::of(PATTERN, pattern.output.0.get_or_init(|| given_as)); + + let hop = matches!(pattern.steps.as_slice(), [step] if step.max == 1); + let names = |node: &NodePattern| match (filter, &node.alias) { + (Some(filter), Some(alias)) => named_by(filter, alias, &given.ctx), + _ => Ok(None), + }; + let mut starts = names(&pattern.start)?; + let mut reversed = false; + if hop && starts.is_none() { + starts = names(&pattern.steps[0].to)?; + reversed = starts.is_some(); + } + // Explained, the first step reads the edges at each start, or every edge. + if let Some(said) = given.ctx.said { + let read = Source::new(edges, None, &given.ctx, given.read, visible); + let way = (pattern.steps[0].direction == EdgeDirection::Incoming) != reversed; + let near = starts.as_ref().map(|_| [source, target][usize::from(way)]); + read.say(near.as_slice(), &[], &[])?; + let unpinned = format!(" {}: no pinned vertex", edges.name); + said.borrow_mut() + .extend(starts.is_none().then_some(unpinned)); + } + let graph = Graph { + given, + edges, + ends: [source, target], + typed, + steps: &pattern.steps, + one: starts.as_ref().is_some_and(|(_, one)| *one), + starts: starts.map(|(starts, _)| starts), + reversed, + nodes, + closed, + scope, + named: named.into_iter().map(|(at, _)| at).collect(), + filter, + picks, + seen: RefCell::new(BTreeMap::new()), + examined: Cell::new(0), + }; + Ok((graph, gives)) + } + + /// Matches the steps from the one at `at` on, from `starts` or from every node; `path` + /// holds the nodes matched before them, `depth` edges from the first. Answers false once + /// `each` wants no more. + fn walk( + &self, + at: usize, + starts: Option<&[Uuid]>, + path: &mut Vec, + depth: u32, + reservation: &mut Reservation, + each: &mut Match<'_>, + ) -> Result { + let step = &self.steps[at]; + let reached: &mut Reached<'_> = &mut |start, far, deep, reservation| { + path.truncate(at); + path.extend([start, far]); + match self.steps.len() - at { + 1 => each(path, depth + deep, reservation), + _ => self.walk(at + 1, Some(&[far]), path, depth + deep, reservation, each), + } + }; + match starts { + Some(starts) => self.from(step, starts, reservation, reached), + None => self.every_node(step, reservation, reached), + } + } + + /// One step from `starts`, breadth first: hands `each` every node some start reaches within + /// the step's range, once, at the least such depth and with that start, the starts taking + /// turns in their order. Each start walks on its own, so a node one start reaches too soon + /// is still reached from another. A start is reached when an edge comes back to it. + /// Remembers every node met from each start, asked of `reservation` before it is remembered. + fn from( + &self, + step: &EdgeStep, + starts: &[Uuid], + reservation: &mut Reservation, + each: &mut Reached<'_>, + ) -> Result { + // Every node met from each start, and whether it has been reached: a start is met + // before it is; and every node handed on. + let (mut met, mut told) = (BTreeMap::new(), BTreeSet::new()); + let mut frontier = Vec::new(); + for start in starts { + reservation.grow(NODE)?; + met.insert((*start, *start), false); + frontier.push((*start, *start)); + } + let mut more = true; + for depth in 1..=step.max { + let mut next = Vec::new(); + for (node, start) in frontier { + let reached: &mut Ends<'_> = &mut |_, far, reservation| { + match met.get_mut(&(start, far)) { + Some(true) => return Ok(true), + // A start the walk has come back to: its edges are followed already. + Some(reached) => *reached = true, + None => { + reservation.grow(NODE)?; + met.insert((start, far), true); + next.push((far, start)); + } + } + match depth < step.min || told.contains(&far) { + true => Ok(true), + false => { + reservation.grow(NODE)?; + told.insert(far); + each(start, far, depth, reservation) + } + } + }; + more = more && self.edges(step, Some(node), reservation, reached)?; + } + if !more { + break; + } + frontier = next; + } + reservation.shrink(NODE * (met.len() + told.len()) as u64); + Ok(more) + } + + /// One step from every node. Each node with an edge is a start, so whatever the step + /// reaches is one edge from a start, and of the starts as near the smallest id wins: hands + /// `each` the far end of every edge once, with the smallest near end. Reads each edge + /// once and remembers each far end, asked of `reservation` before it is remembered. A step + /// of more than one edge is walked from each node with an edge, in the order of their ids. + fn every_node( + &self, + step: &EdgeStep, + reservation: &mut Reservation, + each: &mut Reached<'_>, + ) -> Result { + if step.min > 1 { + let mut starts = BTreeSet::new(); + self.edges(step, None, reservation, &mut |near, _, reservation| { + reservation.grow(NODE * u64::from(starts.insert(near)))?; + Ok(true) + })?; + let starts: Vec = starts.into_iter().collect(); + let more = self.from(step, &starts, reservation, each); + reservation.shrink(NODE * starts.len() as u64); + return more; + } + let mut nearest = BTreeMap::new(); + self.edges(step, None, reservation, &mut |near, far, reservation| { + match nearest.entry(far) { + Entry::Vacant(new) => { + reservation.grow(NODE)?; + new.insert(near); + } + Entry::Occupied(mut held) => { + if near < *held.get() { + held.insert(near); + } + } + } + Ok(true) + })?; + let held = NODE * nearest.len() as u64; + let mut more = true; + for (far, near) in nearest { + more = more && each(near, far, 1, reservation)?; + } + reservation.shrink(held); + Ok(more) + } + + /// Hands `each` the two ends of every edge of the step that the reader may follow, the + /// near end first: the edges at `near`, read through the index that begins with that end, + /// or with no node every edge of the table. An edge is followed when its row passes the + /// reader's filter and the reader may see both its ends. An edge from a node to itself is + /// one edge whichever way it is followed. Answers false once `each` wants no more. + fn edges( + &self, + step: &EdgeStep, + near: Option, + reservation: &mut Reservation, + each: &mut Ends<'_>, + ) -> Result { + // Which end is the near one: the first of `ENDS`, the second, or each in turn. + let ways: &[usize] = match (step.direction, self.reversed) { + (EdgeDirection::Both, _) => &[0, 1], + (EdgeDirection::Outgoing, false) | (EdgeDirection::Incoming, true) => &[0], + _ => &[1], + }; + let typed = step.edge_type.clone().map(Value::Text); + let mut give = |row: &[Value], way: usize, reservation: &mut Reservation| -> Result { + let ends = (&row[self.ends[way]], &row[self.ends[1 - way]]); + let (Value::Uuid(near), Value::Uuid(far)) = ends else { + return Ok(true); + }; + let seen = + self.sees(*near, false, reservation)? && self.sees(*far, false, reservation)?; + Ok(!seen || each(*near, *far, reservation)?) + }; + let Some(node) = near else { + let either: &mut Rows<'_> = &mut |row, reservation| { + let own = row[self.ends[0]] == row[self.ends[1]]; + for way in ways.iter().take(if own { 1 } else { 2 }) { + if !give(row, *way, reservation)? { + return Ok(false); + } + } + Ok(true) + }; + let every = typed.map(|edge_type| equal(self.edges, &[self.typed], &[edge_type])); + return self.read(self.edges, every.as_ref(), &self.ends, reservation, either); + }; + for (turn, way) in ways.iter().enumerate() { + let values: Vec = once(Value::Uuid(node)).chain(typed.clone()).collect(); + let at = [self.ends[*way], self.typed]; + let at = equal(self.edges, &at[..values.len()], &values); + // The second way round, an edge from the node to itself has been followed. + let row: &mut Rows<'_> = &mut |row, reservation| { + let own = row[self.ends[0]] == row[self.ends[1]]; + Ok((turn == 1 && own) || give(row, *way, reservation)?) + }; + if !self.read(self.edges, Some(&at), &self.ends, reservation, row)? { + return Ok(false); + } + } + Ok(true) + } + + /// Whether the reader may see a node, looked up when the node is first met and remembered + /// from then on, asked of `reservation` before it is. A node that is hidden and `named` by + /// the pattern's filter is the refusal of the rule that hides it. + fn sees(&self, node: Uuid, named: bool, reservation: &mut Reservation) -> Result { + if self.nodes.is_empty() && self.closed.is_empty() { + return Ok(true); + } + if let Some(seen) = self.seen.borrow().get(&node) { + return Ok(*seen); + } + reservation.grow(NODE)?; + match self.hidden(node, reservation)? { + Some(refusal) if named => Err(refusal), + hidden => { + self.seen.borrow_mut().insert(node, hidden.is_none()); + Ok(hidden.is_none()) + } + } + } + + /// The refusal of the rule that hides a node from the reader: some table that can hide a + /// node has a row with the node's id that the reader may not see. `None` for a node the + /// reader may see, as one that no row carries is. + fn hidden(&self, node: Uuid, reservation: &mut Reservation) -> Result> { + let open = self.nodes.iter().map(|table| (*table, false)); + for (table, closed) in open.chain(self.closed.iter().map(|table| (table, true))) { + let id = table + .meta + .columns + .iter() + .position(|column| column.name == "id"); + let carries = equal(table, &[id.expect("a node's id")], &[Value::Uuid(node)]); + let mut carried = false; + let row: &mut Rows<'_> = &mut |_, _| { + carried = true; + Ok(true) + }; + match self.read(table, Some(&carries), &[], reservation, row) { + Err( + refusal @ (Error::ContextScopeViolation { .. } + | Error::ScopeLabelViolation { .. } + | Error::AclDenied { .. }), + ) => { + // The row that hides the node was read. + self.examined.set(self.examined.get() + 1); + return Ok(Some(refusal)); + } + read => read?, + }; + if closed && carried { + let table = table.name.clone(); + return Err(Error::PrincipalRequired { table }); + } + } + Ok(None) + } + + /// Reads through the table source the rows of `table` that `filter` passes, with its + /// parameters bound, and hands `each` every one the reader may see, with its `wanted` + /// columns. With no column wanted the rows are those that carry one node, and one the + /// reader may not see is the refusal of the rule that hides it. Answers false once `each` + /// wants no more. + fn read( + &self, + table: &Table, + filter: Option<&(Expr, HashMap)>, + wanted: &[usize], + reservation: &mut Reservation, + each: &mut Rows<'_>, + ) -> Result { + let none = HashMap::new(); + let (filter, params) = + filter.map_or((None, &none), |(filter, bound)| (Some(filter), bound)); + let width = table.meta.columns.len(); + let (mut filtered, mut taken) = (vec![false; width], vec![false; width]); + if let Some(filter) = filter { + reads(filter, &table.scope(), params, &mut filtered)?; + } + for column in wanted { + taken[*column] = true; + } + // What the reader's filter holds for this read is given back with it. + let (given, ctx) = (self.given, EvalContext::new(params, 0)); + let mut seeing = given.budget.reserve(0, "query")?; + let visible = Visible::new(table, given.catalog, given.reader, &mut seeing)?; + let source = + Source::new(table, filter, &ctx, given.read, visible).reading(filtered, &taken); + let mut path = source.choose(&[], &[])?; + path.one = wanted.is_empty(); + let mut more = true; + let examined = source.walk(&path, reservation, |_, row, bytes, reservation| { + more = each(&row, reservation)?; + reservation.shrink(bytes); + Ok(more) + })?; + self.examined.set(self.examined.get() + examined); + Ok(more) + } +} + +impl plan::Source for Graph<'_> { + /// A row for every match the pattern's filter passes: what COLUMNS names. The one start an + /// `=` names, when the reader may not see it, is the refusal of the rule that hides it. + fn rows(&self, reservation: &mut Reservation, each: &mut Each<'_>) -> Result { + let starts = self.starts.iter().flatten(); + for start in starts.clone() { + reservation.grow(NODE)?; + self.sees(*start, self.one, reservation)?; + } + let matched: &mut Match<'_> = &mut |path, depth, reservation| { + let mut row = vec![ + Value::Uuid(path[path.len() - 1]), + Value::Int64(depth.into()), + ]; + row.extend(self.named.iter().map(|at| Value::Uuid(path[*at]))); + if let Some(filter) = self.filter + && eval(filter, &self.scope, &row, &self.given.ctx)? != Value::Bool(true) + { + return Ok(true); + } + row = self.picks.iter().map(|at| row[*at].clone()).collect(); + let bytes = row_overhead(row.len()); + reservation.grow(bytes)?; + each(row, bytes, reservation) + }; + match self.steps { + [hop] if hop.max == 1 => { + let give: &mut Ends<'_> = &mut |near, far, reservation| match self.reversed { + true => matched(&[far, near], 1, reservation), + false => matched(&[near, far], 1, reservation), + }; + match &self.starts { + None => { + self.edges(hop, None, reservation, give)?; + } + Some(starts) => { + for start in starts { + if !self.edges(hop, Some(*start), reservation, give)? { + break; + } + } + } + } + } + _ => { + let starts = self.starts.as_deref(); + self.walk(0, starts, &mut Vec::new(), 0, reservation, matched)?; + } + } + let seen = std::mem::take(&mut *self.seen.borrow_mut()); + reservation.shrink(NODE * (seen.len() + starts.count()) as u64); + Ok(self.examined.take()) + } +} + +/// The nodes a filter names for the node of a pattern called `alias`, each once and in the +/// order it names them, and whether they are the one an `=` names: the values of the first +/// `alias.id = value` or `alias.id IN (...)` among the terms joined by AND at its top, a value +/// or list a SELECT works out included, and of both sides of an OR that each name some. NULL +/// names no node. `None` when it names none that way. +fn named_by(filter: &Expr, alias: &str, ctx: &EvalContext) -> Result, bool)>> { + let id = |expr: &Expr| { + matches!(expr, Expr::Column(ColumnRef { table: Some(table), column }) + if table == alias && column == "id") + }; + let worked = |value: &Expr| eval(value, &Scope::default(), &[], ctx); + // A SELECT's values are read where they are held, never copied. + let (values, one): (Cow<[Value]>, bool) = match filter { + Expr::BinaryOp { left, op, right } => match op { + BinOp::And => { + let left = named_by(left, alias, ctx)?; + return left.map_or_else(|| named_by(right, alias, ctx), |left| Ok(Some(left))); + } + BinOp::Or => match (named_by(left, alias, ctx)?, named_by(right, alias, ctx)?) { + (Some((left, _)), Some((right, _))) => ( + Cow::Owned(left.into_iter().chain(right).map(Value::Uuid).collect()), + false, + ), + _ => return Ok(None), + }, + BinOp::Eq if id(left) && known(right, ctx) => (vec![worked(right)?].into(), true), + BinOp::Eq if id(right) && known(left, ctx) => (vec![worked(left)?].into(), true), + _ => return Ok(None), + }, + Expr::InList { + expr, + list, + negated: false, + } if id(expr) && list.iter().all(|value| known(value, ctx)) => ( + Cow::Owned(list.iter().map(worked).collect::>()?), + false, + ), + // The values of a SELECT after IN are worked out before the pattern is matched. + Expr::InSubquery { + expr, + query, + negated: false, + } if id(expr) => (ctx.subquery(query)?.into(), false), + _ => return Ok(None), + }; + let (mut nodes, mut once) = (Vec::new(), BTreeSet::new()); + for value in values.iter().filter(|value| **value != Value::Null) { + // A value that is no node's id names no node, and the filter is asked of every match. + let Some(Value::Uuid(node)) = as_key(ColumnType::Uuid, value.clone()) else { + return Ok(None); + }; + nodes.extend(once.insert(node).then_some(node)); + } + Ok(Some((nodes, one))) +} diff --git a/v2/contextdb/src/query/inspect.rs b/v2/contextdb/src/query/inspect.rs index ba6e5eb71..594e33bd8 100644 --- a/v2/contextdb/src/query/inspect.rs +++ b/v2/contextdb/src/query/inspect.rs @@ -1,17 +1,21 @@ //! Inspection of VECTOR columns: what `SHOW VECTOR_INDEXES` and `SHOW VECTOR_PARTITIONS` return -//! and what explaining a similarity search says. All three read the vector part's small records -//! and no block, no centre and no row, and none changes anything. +//! and what explaining a statement says. All three read the vector part's small records and no +//! block, no centre and no row, and none changes anything. -use std::cell::Cell; +use std::cell::{Cell, RefCell}; use std::collections::HashMap; use serde_json::json; -use super::search::Scope; -use super::{QueryResult, Reader}; +use super::expression::EvalContext; +use super::plan::{self, Given}; +use super::search::{Scope, Search, small}; +use super::{QueryResult, Reader, Visible}; +use super::{subquery, table}; use crate::memory::Budget; -use crate::schema::{Catalog, Consolidation, Quantization, Table, VectorColumn}; -use crate::sql::{Plan, not_supported}; +use crate::schema::{Catalog, Compaction, Quantization, Table, VectorColumn}; +use crate::sql::ast::BinOp; +use crate::sql::{Expr, Plan, not_supported}; use crate::store::{Key, Read, VectorNumber}; use crate::types::{Error, Result, Value, VectorIndexRef, VectorSearchMode}; use crate::vector::{self, Inspected, Nearest, Route, State}; @@ -27,15 +31,15 @@ const INDEX_FIELDS: [&str; 31] = [ "max_partitions", "live_partitions", "search_mode", - "declared_auto_index_at", - "effective_auto_index_at", - "declared_consolidation_mode", - "declared_consolidation_change_percent", - "declared_consolidation_tombstone_percent", - "effective_consolidation_mode", - "effective_consolidation_change_percent", - "effective_consolidation_tombstone_percent", - "pending_inserts", + "declared_indexing_threshold", + "effective_indexing_threshold", + "declared_compaction_mode", + "declared_compaction_change_percent", + "declared_compaction_tombstone_percent", + "effective_compaction_mode", + "effective_compaction_change_percent", + "effective_compaction_tombstone_percent", + "pending_tuples", "tombstones", "durable_vector_bytes", "durable_index_bytes", @@ -55,7 +59,7 @@ const PARTITION_FIELDS: [&str; 18] = [ "column", "partition_key", "live_rows", - "pending_inserts", + "pending_tuples", "tombstones", "durable_vector_bytes", "durable_index_bytes", @@ -215,12 +219,12 @@ fn index_row(table: &Table, column: &VectorColumn, parts: &[Inspected]) -> Vec bool| parts.iter().filter(|part| of(part)).count() as u64; let optional = |number: Option| number.map_or(Value::Null, whole); let percent = |number: Option| optional(number.map(u64::from)); - let (declared, change, tombstone) = match column.consolidation { + let (declared, change, tombstone) = match column.compaction { None => (Value::Null, None, None), - Some(Consolidation::None) => (text("NONE"), None, None), - Some(Consolidation::Percent { change, tombstone }) => (text("PERCENT"), change, tombstone), + Some(Compaction::None) => (text("NONE"), None, None), + Some(Compaction::Percent { change, tombstone }) => (text("PERCENT"), change, tombstone), }; - let in_force = column.consolidation(); + let in_force = column.compaction(); let state = parts.iter().map(|part| part.state).max(); let state = state.unwrap_or(State::Idle); let (slot_bytes, index_bytes) = (sum(|part| part.slot_bytes), sum(|part| part.index_bytes)); @@ -240,7 +244,7 @@ fn index_row(table: &Table, column: &VectorColumn, parts: &[Inspected]) -> Vec 0)), text(mode_name(column.mode())), - optional(column.auto_index_at), + optional(column.indexing_threshold), whole(column.index_at()), declared, percent(change), @@ -272,7 +276,7 @@ fn partition_row(table: &Table, column: &VectorColumn, part: &Inspected) -> Vec< _ if part.damage.is_some() => "damaged", State::Idle => "none", State::Stalled => "memory_limit", - _ if part.groups == 0 => "first_grouping", + _ if part.groups == 0 => "unindexed", _ if part.left_behind => "tombstones", _ => "changes", }; @@ -302,86 +306,113 @@ fn partition_row(table: &Table, column: &VectorColumn, part: &Inspected) -> Vec< ] } -/// What a statement would do, as text of one `name: value` to a line. For a similarity search: -/// the mode asked for and the one in force, the column's `AUTO_INDEX_AT`, how many partitions -/// the filter selects, and for each of them how it is searched; then what refuses the search, -/// or `none`. The search is not run. A partition named through a `$name` has no value here: -/// every partition is then listed, and the line of their count says so. +/// What a statement would do, as text of one `name: value` to a line, made ready as running +/// it makes it with `params` and no row read. For a similarity search: the mode asked for and +/// the one in force, the column's `INDEXING_THRESHOLD`, how many partitions the filter selects, and +/// for each of them how it is searched; the path of the filter; then what refuses the search, +/// or `none`. A partition named through a `$name` with no value is not known: every partition +/// is then listed, and the line of their count says so. A narrowed handle is told no count. +/// For any other statement: the path each table is read by, and each count read from a kept +/// number. pub(crate) fn explain( plan: &Plan, + params: &HashMap, catalog: &Catalog, read: &dyn Read, reader: &Reader, budget: &Budget, now: i64, ) -> Result { - let plan = match plan { - Plan::Project { input, .. } => &**input, - plan => plan, + let said = RefCell::new(Vec::new()); + let mut ctx = EvalContext::new(params, now); + (ctx.said, ctx.explained) = (Some(&said), Some(plan)); + let given = Given { + params, + catalog, + read, + reader, + budget, + ctx, + evaluations: &Cell::default(), + named: None, + bound: None, }; - let Plan::VectorSearch { - table, - column, - k, - filter, - mode, - .. - } = plan - else { + let mut seeing = budget.reserve(0, "query")?; + match plan { + Plan::Select(select) => { + drop(plan::select(select, &given, &mut seeing)?); + } + Plan::Insert(insert) => { + let table = catalog.table(&insert.table); + let table = table.ok_or_else(|| Error::TableNotFound(insert.table.clone()))?; + table.insert(insert)?; + said.borrow_mut() + .push(format!("Insert(table={})", table.name)); + } + Plan::Delete(delete) => path(&given, &delete.table, delete.where_clause.as_ref(), &[])?, + Plan::Update(update) => { + let filter = update.where_clause.as_ref(); + path(&given, &update.table, filter, &update.assignments)?; + } + _ => {} + } + subquery::written(plan, &given, &mut seeing)?; + let said = said.take(); + if said.is_empty() { return Err(not_supported("explaining this statement")); - }; - let table = catalog - .table(table) - .ok_or_else(|| Error::TableNotFound(table.clone()))?; - let index = VectorIndexRef { - table: table.name.clone(), - column: column.clone(), - }; - let Some(vector) = table.vector(column) else { - return Err(Error::UnknownVectorIndex { index }); - }; + } + Ok(said.join("\n")) +} + +/// Says the path the rows of the table `name` that pass `filter` are read by, with no index +/// over a column `set` assigns walked. +fn path(given: &Given, name: &str, filter: Option<&Expr>, set: &[(String, Expr)]) -> Result<()> { + let table = given.catalog.table(name); + let table = table.ok_or_else(|| Error::TableNotFound(name.to_owned()))?; + let set = table.targets(set.iter().map(|(name, _)| name))?; + let mut seeing = given.budget.reserve(0, "query")?; + let visible = Visible::new(table, given.catalog, given.reader, &mut seeing)?; + let source = table::Source::new(table, filter, &given.ctx, given.read, visible); + source.say(&[], &[], &set) +} + +/// The explanation of a similarity search, as it is planned. +pub(super) fn searched(search: &Search) -> Result { + let (table, vector, select, given) = (search.table, search.vector, search.select, search.given); + let further = usize::from(select.order_by.len() > 1); + let k = search.most.saturating_add(further); + let (filter, mode, reader) = (&select.filter, &select.use_vector, given.reader); let mode = mode.unwrap_or_else(|| vector.mode()); - let key = vector.partition_key.iter(); - let key = key.filter_map(|name| table.meta.columns.iter().position(|c| c.name == *name)); - let scope = Scope { - table, - key: key.collect(), - params: &HashMap::new(), - now, - unbound: Cell::default(), + let scope = Scope::new(table, vector, given); + // A narrowed handle is told nothing the state of the index decides: no partition is planned. + let narrowed = !reader.is_admin(); + let mut lines = vec![ + format!("requested_mode: {}", mode_name(mode)), + format!("effective_indexing_threshold: {}", vector.index_at()), + format!("partition_key_columns: {}", key_columns(vector)), + ]; + let keys = scope.keys(filter.as_ref())?; + let every = scope.unbound.take().pop(); + // The list is let go with the text made from it; a reader with no partition plans none. + let mut reservation = given.budget.reserve(0, "query")?; + let planned = match &keys { + Some(scope) if !narrowed => { + let nearest = Nearest { + table: table.id, + vector: vector.id, + column: vector, + mode, + scope, + query: &[], + k, + // Whether rows are turned away is known only when the search runs. + filtered: false, + ranked: false, + }; + vector::plan(&nearest, given.read, &mut reservation)? + } + _ => Vec::new(), }; - // A narrowed handle is told what the statement and the declaration say: no partition - // record is read for it, as one names its Context's values and counts its vectors. - if !reader.is_admin() { - let lines = [ - format!("requested_mode: {}", mode_name(mode)), - format!("effective_auto_index_at: {}", vector.index_at()), - format!("partition_key_columns: {}", key_columns(vector)), - ]; - return Ok(lines.join("\n")); - } - let mut keys = scope.keys(filter.as_ref())?; - let every = scope.unbound.take(); - if every.is_some() { - keys.clear(); - } - // The list is let go with the text made from it. - let mut reservation = budget.reserve(0, "query")?; - let planned = vector::plan( - &Nearest { - table: table.id, - vector: vector.id, - column: vector, - mode, - scope: &keys, - query: &[], - k: usize::try_from(*k).unwrap_or(usize::MAX), - // Whether rows are turned away is known only when the search runs. - filtered: false, - }, - read, - &mut reservation, - )?; let indexed = mode == VectorSearchMode::Indexed; let allowed: u64 = planned.iter().map(|partition| partition.live).sum(); @@ -390,17 +421,15 @@ pub(crate) fn explain( VectorSearchMode::Auto if allowed < vector.index_at() => VectorSearchMode::Exact, mode => mode, }; - let mut lines = vec![ - format!("requested_mode: {}", mode_name(mode)), - format!("resolved_mode: {}", mode_name(resolved)), - format!("effective_auto_index_at: {}", vector.index_at()), - format!("aggregate_allowed_vectors: {allowed}"), - format!("partition_key_columns: {}", key_columns(vector)), - match every { + // A narrowed handle is told no count of vectors or partitions. + if !narrowed { + lines.insert(1, format!("resolved_mode: {}", mode_name(resolved))); + lines.insert(3, format!("aggregate_allowed_vectors: {allowed}")); + lines.push(match &every { None => format!("partitions: {}", planned.len()), Some(name) => format!("partitions: every partition (${name} is not bound)"), - }, - ]; + }); + } for partition in &planned { let route = match partition.route { Route::Exact => "exact", @@ -410,25 +439,54 @@ pub(crate) fn explain( 0 => "none".to_owned(), _ => number.to_string(), }; + let key = key_object(vector, &partition.tuple); lines.extend([ - format!("partition: {}", key_object(vector, &partition.tuple)), + format!("partition: {key}"), format!(" route: {route}"), format!(" lists: {}", grouping(partition.groups)), format!(" probes: {}", grouping(partition.probes)), format!(" live_rows: {}", partition.live), - format!(" outside_grouping: {}", partition.tail + partition.pending), + format!(" unindexed_rows: {}", partition.tail + partition.pending), ]); } + // The path the filter is read by, as its table source says it, when every name has a value. + if let Some(filter) = filter.as_ref().filter(|_| every.is_none()) { + let mut seeing = given.budget.reserve(0, "query")?; + let visible = Visible::new(table, given.catalog, reader, &mut seeing)?; + let source = table::Source::new(table, Some(filter), &given.ctx, given.read, visible); + source.say(&[], &[], &[])?; + let said = given.ctx.said.map(|said| said.take()).unwrap_or_default(); + let mut said = said.iter().map(|line| line.trim_start()); + let path = said.next().filter(|path| *path != "Scan"); + lines.push(format!("filter_path: {}", path.unwrap_or("none"))); + lines.extend(said.map(str::to_owned)); + // Rows a path reaches are compared one by one, and no partition searched, when few. + if !narrowed && path.is_some() { + let few = source.few(&source.choose(&[], &[])?, small(&planned, k))?; + lines.push(format!("small_set: {}", if few { "yes" } else { "no" })); + } + // For a filter no index serves: the index that would, by the columns it gives a value + // then the one it gives a range. + let mut terms = Vec::new(); + table::collect(table, &table.scope(), filter, &given.ctx, &mut terms)?; + terms.sort_by_key(|term| term.op != BinOp::Eq); + let ranged = terms.iter().position(|term| term.op != BinOp::Eq); + let wanted = terms[..ranged.map_or(terms.len(), |at| at + 1)].iter(); + let mut wanted: Vec<&str> = (wanted.filter_map(|term| table.meta.columns.get(term.column))) + .map(|column| column.name.as_str()) + .collect(); + wanted.dedup(); + if path.is_none() && !wanted.is_empty() { + let (name, list) = (&table.name, wanted.join(", ")); + let index = format!("{name}_{}_idx", wanted.join("_")); + lines.push(format!("recovery: CREATE INDEX {index} ON {name} ({list})")); + } + } // A search under INDEXED with a partition that is not usable is refused whole. - lines.push( - if indexed && planned.iter().any(|partition| !partition.usable) { - format!( - "refusal: {}", - Error::VectorIndexedRouteUnavailable { index } - ) - } else { - "refusal: none".to_owned() - }, - ); + let index = table.vector_ref(vector); + let refused = indexed && planned.iter().any(|partition| !partition.usable); + let refused = refused.then(|| Error::VectorIndexedRouteUnavailable { index }.to_string()); + let refused = refused.as_deref().unwrap_or("none"); + lines.extend((!narrowed && keys.is_some()).then(|| format!("refusal: {refused}"))); Ok(lines.join("\n")) } diff --git a/v2/contextdb/src/query/join.rs b/v2/contextdb/src/query/join.rs new file mode 100644 index 000000000..aba21666a --- /dev/null +++ b/v2/contextdb/src/query/join.rs @@ -0,0 +1,566 @@ +//! FROM over more than one relation, or over a WITH name: the relations joined in the order +//! they are written. For each row of the left side the right table is read through the key +//! or index that the equalities of ON give values for; when none serves, the right side is +//! read once and its rows kept, asked for before each is kept. + +use std::cell::Cell; +use std::cmp::Ordering; + +use super::expression::{EvalContext, Scope, compare, eval, mark, reads}; +use super::plan::{self, Cut, Each, Given, Rows, Source}; +use super::row_overhead; +use super::subquery::Named; +use super::table::{self, as_key}; +use super::visible::Visible; +use crate::memory::Reservation; +use crate::schema::Table; +use crate::sql::ast::{BinOp, Literal}; +use crate::sql::plan::{FromItem, SelectPlan, SortKey}; +use crate::sql::{Expr, not_supported}; +use crate::types::heap_bytes; +use crate::types::{ColumnDef, Error, Result, Value}; + +/// What FROM gives a SELECT: the joined rows, their columns, and what of WHERE is still to be +/// applied to them. +pub(super) struct From<'a> { + pub(super) rows: Box, + pub(super) scope: Scope<'a>, + pub(super) filter: Option<&'a Expr>, +} + +/// One relation of FROM under the name the statement gives it. +struct Relation<'c> { + qualifier: &'c str, + columns: &'c [ColumnDef], + of: Of<'c>, +} + +/// What a relation is: a stored table, or a WITH name of the statement. +#[derive(Clone, Copy)] +enum Of<'c> { + Table(&'c Table), + Named(&'c Named<'c>), +} + +/// What the sources of a FROM borrow while its rows are read. +pub(super) struct Held<'c> { + relations: Vec>, + /// For each relation, the parts of WHERE that read it alone, which its table source + /// applies before the join. + filters: Vec>, + /// For each relation, what the reader's filter of its table holds. + seeing: Vec, + /// Of each column of a joined row: whether a part of WHERE its table source applies reads + /// it, and whether the statement reads it above the sources. + read: (Vec, Vec), + /// Whether a part of WHERE is left for the joined rows. + rest: bool, +} + +/// Looks up the relations of FROM, a missing table refused first, and binds WHERE against +/// them. `None` for a FROM `plan::one` answers alone: nothing, a pattern, or one stored table. +pub(super) fn held<'c>(select: &'c SelectPlan, given: &Given<'c>) -> Result>> { + let items = select.from.iter(); + let mut relations = Vec::new(); + for item in items.chain(select.joins.iter().map(|join| &join.item)) { + let FromItem::Table { name, alias } = item else { + return match select.joins.is_empty() { + true => Ok(None), + false => Err(not_supported("GRAPH_TABLE beside a JOIN")), + }; + }; + let qualifier = alias.as_ref().unwrap_or(name); + let mut before = relations + .iter() + .map(|relation: &Relation| relation.qualifier); + if before.any(|before| before == *qualifier) { + let refused = format!("table name \"{qualifier}\" specified more than once"); + return Err(Error::PlanError(refused)); + } + let of = match Named::find(given, name) { + Some(named) => Of::Named(named), + None => { + let table = given.catalog.table(name); + Of::Table(table.ok_or_else(|| Error::TableNotFound(name.clone()))?) + } + }; + let columns = match of { + Of::Named(named) => &named.columns, + Of::Table(table) => &table.meta.columns, + }; + relations.push(Relation { + qualifier, + columns, + of, + }); + } + if let [] + | [ + Relation { + of: Of::Table(_), .. + }, + ] = relations.as_slice() + { + return Ok(None); + } + + let mut scope = Scope::default(); + scope.checked = true; + let scope = relations.iter().fold(scope, |scope, relation| { + scope.and(relation.qualifier, relation.columns) + }); + let mut filters: Vec> = relations.iter().map(|_| None).collect(); + let (mut parts, mut rest) = (Vec::new(), false); + let mut filtered = vec![false; scope.columns().count()]; + if let Some(filter) = &select.filter { + joined(filter, BinOp::And, &mut parts); + } + for part in parts { + let mut read = vec![false; scope.columns().count()]; + reads(part, &scope, given.params, &mut read)?; + // The relation that holds every column the part reads. Its table source applies the + // part unless the relation is the right side of a LEFT JOIN, whose unmatched rows + // WHERE sees as NULL. + let mut start = 0; + let home = relations.iter().position(|relation| { + let here = start..start + relation.columns.len(); + start = here.end; + let elsewhere = read + .iter() + .enumerate() + .any(|(at, read)| *read && !here.contains(&at)); + !elsewhere && read[here].contains(&true) + }); + let stored = |at: &usize| matches!(relations[*at].of, Of::Table(_)); + match home.filter(stored) { + Some(at) if at == 0 || !select.joins[at - 1].left_outer => { + (filtered.iter_mut().zip(&read)).for_each(|(filtered, read)| *filtered |= read); + filters[at] = Some(match filters[at].take() { + None => part.clone(), + Some(so_far) => Expr::BinaryOp { + left: Box::new(so_far), + op: BinOp::And, + right: Box::new(part.clone()), + }, + }); + } + _ => rest = true, + } + } + let seeing = relations.iter().map(|_| given.budget.reserve(0, "query")); + Ok(Some(Held { + seeing: seeing.collect::>()?, + read: (filtered, wanted(select, &scope)), + relations, + filters, + rest, + })) +} + +/// The columns of `scope` a SELECT reads of its rows above their sources: every one for `*`, +/// else those its list, ON, WHERE, GROUP BY, HAVING and ORDER BY name. +fn wanted(select: &SelectPlan, scope: &Scope) -> Vec { + let mut wanted = vec![plan::list(select).is_none(); scope.columns().count()]; + let mut mark = |expr: &Expr| mark(expr, scope, &mut wanted); + select.columns.iter().for_each(|column| mark(&column.expr)); + select.order_by.iter().for_each(|key| mark(&key.expr)); + let on = select.joins.iter().filter_map(|join| join.on.as_ref()); + on.chain(&select.filter).for_each(&mut mark); + select.group_by.iter().chain(&select.having).for_each(mark); + wanted +} + +/// The parts of a condition that `by`, AND or OR, joins at its top. +fn joined<'e>(condition: &'e Expr, by: BinOp, parts: &mut Vec<&'e Expr>) { + match condition { + Expr::BinaryOp { left, op, right } if *op == by => { + joined(left, by, parts); + joined(right, by, parts); + } + part => parts.push(part), + } +} + +/// The source of the relations looked up in `held`, joined in written order, each ON bound +/// against the relations written so far; a WITH name among them is read `depth` deep. +pub(super) fn from<'a, 'c: 'a>( + select: &'a SelectPlan, + given: &'a Given<'a>, + held: &'a mut Held<'c>, + depth: usize, +) -> Result> { + let (relations, filters, rest) = (&held.relations, &held.filters, held.rest); + let (mut scope, mut rows) = (Scope::default(), None::>); + scope.checked = true; + let sides = relations.iter().zip(filters).zip(&mut held.seeing); + for (at, ((relation, filter), seeing)) in sides.enumerate() { + let start = scope.columns().count(); + let width = relation.columns.len(); + scope = scope.and(relation.qualifier, relation.columns); + let right = match relation.of { + Of::Table(table) => { + let (filtered, wanted) = (&held.read.0[start..], &held.read.1[start..]); + let visible = Visible::new(table, given.catalog, given.reader, seeing)?; + let table = + table::Source::new(table, filter.as_ref(), &given.ctx, given.read, visible); + // What the statement reads of a joined row is settled above the join. + let table = table.named(relation.qualifier); + Side::Table(Box::new(table.reading(filtered[..width].to_vec(), wanted))) + } + // A statement that reads nothing but the name hands its WHERE to the name. + Of::Named(named) => { + let alone = relations.len() == 1; + let bound = select.filter.as_ref().filter(|_| alone); + Side::Named(named, given, bound, depth + select.joins.len()) + } + }; + let Some(left) = rows else { + if let Side::Table(table) = &right { + table.say(&[], &[], &[])?; + } + rows = Some(Box::new(right)); + continue; + }; + let join = &select.joins[at - 1]; + // The columns of the right side that ON says equal a column of the left row. + let mut pins = Vec::new(); + if let Some(on) = &join.on { + reads(on, &scope, given.params, &mut vec![false; start + width])?; + let mut parts = Vec::new(); + joined(on, BinOp::And, &mut parts); + for part in parts { + if let Expr::BinaryOp { + left, + op: BinOp::Eq, + right, + } = part + && let (Expr::Column(left), Expr::Column(right)) = (&**left, &**right) + { + let (left, right) = (scope.find(left)?.0, scope.find(right)?.0); + if left.max(right) >= start && left.min(right) < start { + pins.push((left.max(right) - start, left.min(right))); + } + } + } + } + if let Side::Table(table) = &right { + table.say(&pins.iter().map(|pin| pin.0).collect::>(), &[], &[])?; + } + rows = Some(Box::new(Join { + left, + right, + on: join.on.as_ref(), + outer: join.left_outer, + scope: scope.clone(), + width, + pins, + ctx: &given.ctx, + })); + } + let filter = select.filter.as_ref().filter(|_| rest); + let from = rows.map(|rows| From { + rows, + scope, + filter, + }); + from.ok_or_else(|| not_supported("a FROM that names no table")) +} + +/// One relation as a join reads it: a stored table through its source, or a WITH name. +enum Side<'a> { + Table(Box>), + Named(&'a Named<'a>, &'a Given<'a>, Option<&'a Expr>, usize), +} + +impl Source for Side<'_> { + fn rows(&self, reservation: &mut Reservation, each: &mut Each<'_>) -> Result { + match self { + Side::Table(table) => { + let path = table.choose(&[], &[])?; + table.walk(&path, reservation, |_, row, bytes, reservation| { + each(row, bytes, reservation) + }) + } + Side::Named(named, given, bound, depth) => { + named.rows(given, *bound, *depth, reservation, each) + } + } + } +} + +/// The rows of `left`, each put beside every row of `right` that ON holds for; for a LEFT JOIN +/// a left row that nothing matches is put beside NULLs. Holds the left row and the row it is +/// handing on, and the rows of the right side when no key or index of it serves ON. +struct Join<'a> { + left: Box, + right: Side<'a>, + /// `None` for CROSS JOIN. + on: Option<&'a Expr>, + outer: bool, + /// The columns of both sides, the right side's last. + scope: Scope<'a>, + /// How many columns the right side has. + width: usize, + /// For each equality of ON between the two sides: the column of the right side, and where + /// its partner stands in a left row. + pins: Vec<(usize, usize)>, + ctx: &'a EvalContext<'a>, +} + +impl Source for Join<'_> { + fn rows(&self, reservation: &mut Reservation, each: &mut Each<'_>) -> Result { + // How many leading columns the right table's own filter gives its best path. A path + // serves the join when a left row's values give it more, or its whole key. + let served = match &self.right { + Side::Table(table) if !self.pins.is_empty() => { + Some((table, table.choose(&[], &[])?.pinned)) + } + _ => None, + }; + let mut kept: Option>> = None; + let (mut read, mut held) = (0, 0); + let room = size_of::>() as u64; + let left = self + .left + .rows(reservation, &mut |left, took, reservation| { + let (matched, mut more) = (Cell::new(false), true); + let mut pair = + |right: &[Value], on: Option<&Expr>, reservation: &mut Reservation| { + let values = left.iter().chain(right); + let bytes = row_overhead(left.len() + right.len()) + + values.map(heap_bytes).sum::(); + reservation.grow(bytes)?; + let row = [left.as_slice(), right].concat(); + if let Some(on) = on + && eval(on, &self.scope, &row, self.ctx)? != Value::Bool(true) + { + reservation.shrink(bytes); + return Ok(true); + } + matched.set(true); + each(row, bytes, reservation) + }; + let given: Vec<(usize, Option<&Value>)> = (self.pins.iter()) + .map(|&(column, at)| (column, Some(&left[at]))) + .collect(); + let path = match served { + Some((table, own)) if kept.is_none() => { + let path = table.given(&given, &[], &[])?; + path.serves(own).then_some((table, path)) + } + _ => None, + }; + // Nothing equals NULL: such a left row has no partner, and reads none. + if given.iter().all(|(_, value)| *value != Some(&Value::Null)) { + if let Some((table, path)) = path { + read += + table.walk(&path, reservation, |_, right, bytes, reservation| { + more = pair(&right, self.on, reservation)?; + reservation.shrink(bytes); + Ok(more) + })?; + } else { + if kept.is_none() { + let mut rows = Vec::new(); + read += + self.right + .rows(reservation, &mut |row, bytes, reservation| { + reservation.grow(room)?; + held += bytes + room; + rows.push(row); + Ok(true) + })?; + kept = Some(rows); + } + for right in kept.iter().flatten() { + more = pair(right, self.on, reservation)?; + if !more { + break; + } + } + } + } + if self.outer && !matched.get() { + more = pair(&vec![Value::Null; self.width], None, reservation)?; + } + reservation.shrink(took); + Ok(more) + })?; + reservation.shrink(held); + Ok(left + read) + } +} + +/// What reading only the first rows of each partition of a window borrows. +pub(super) struct Firsts<'c> { + table: &'c Table, + qualifier: &'c str, + /// The window's ORDER BY, and the columns the SELECT reads. + order: &'c [SortKey], + wanted: Vec, + /// For each partition asked for: the SELECT's filter with the partition's value, how + /// many of its rows are asked for, and what the reader's filter of its source holds. + parts: Vec<(Expr, usize, Reservation)>, +} + +/// For the SELECT of a WITH name that numbers the rows of one stored table in partitions of +/// one column: the partitions that `bound`, the WHERE of the statement reading the name, asks +/// for, when every row it can pass is in a partition it names by `=` and has a number it +/// bounds by `<=`. `None` for any other SELECT or bound: then every row is numbered. +pub(super) fn firsts<'c>( + select: &'c SelectPlan, + bound: &Expr, + given: &Given<'c>, +) -> Result>> { + let [FromItem::Table { name, alias }] = select.from.as_slice() else { + return Ok(None); + }; + let cut = select.limit.is_some() || select.offset.is_some(); + let cut = cut || select.limit_name.is_some() || select.offset_name.is_some(); + let more = cut || select.distinct || !select.group_by.is_empty() || select.having.is_some(); + let mut windows = select + .columns + .iter() + .filter_map(|column| match &column.expr { + Expr::RowNumber { + partition_by, + order_by, + } => Some((column, partition_by.as_slice(), order_by.as_slice())), + _ => None, + }); + let (Some((numbered, [Expr::Column(partition)], order)), None, false, Some(table)) = ( + windows.next(), + windows.next(), + more || !select.joins.is_empty(), + given + .catalog + .table(name) + .filter(|_| Named::find(given, name).is_none()), + ) else { + return Ok(None); + }; + // The names the reading statement knows the number and the partition's column by. + let number = numbered.name(); + let listed = select.columns.iter().find_map(|column| match &column.expr { + Expr::Column(named) if named.column == partition.column => Some(column.name()), + _ => None, + }); + let Some(listed) = listed else { + return Ok(None); + }; + + // `bound` is one or more alternatives joined by OR, each of parts joined by AND. + let mut alternatives = Vec::new(); + joined(bound, BinOp::Or, &mut alternatives); + let qualifier = alias.as_ref().unwrap_or(name); + let kind = Scope::of(qualifier, &table.meta.columns).find(partition)?.1; + let mut asked: Vec<(Value, &Expr, usize)> = Vec::new(); + for alternative in alternatives { + let mut parts = Vec::new(); + joined(alternative, BinOp::And, &mut parts); + let beside = |name: &str, wanted: BinOp| { + parts.iter().find_map(|part| match part { + Expr::BinaryOp { left, op, right } if *op == wanted => match &**left { + Expr::Column(named) if named.column == name => Some(&**right), + _ => None, + }, + _ => None, + }) + }; + let ( + Some(value @ (Expr::Literal(_) | Expr::Parameter(_))), + Some(Expr::Literal(Literal::Integer(most))), + ) = (beside(&listed, BinOp::Eq), beside(&number, BinOp::Lte)) + else { + return Ok(None); + }; + let most = usize::try_from(*most).unwrap_or(0); + // A partition is one value of its column's type, however it is written. + let Some(key) = as_key(kind, eval(value, &Scope::default(), &[], &given.ctx)?) else { + return Ok(None); + }; + let same = + |(asked, ..): &(Value, &Expr, usize)| compare(asked, &key) == Some(Ordering::Equal); + match asked.iter().position(same) { + Some(at) => asked[at].2 = asked[at].2.max(most), + None => asked.push((key, value, most)), + } + } + let parts = asked.into_iter().map(|(_, value, most)| { + // The partition's value first: it is the one value the path reads the column at. + let mut filter = Expr::BinaryOp { + left: Box::new(Expr::Column(partition.clone())), + op: BinOp::Eq, + right: Box::new(value.clone()), + }; + if let Some(inner) = &select.filter { + filter = Expr::BinaryOp { + left: Box::new(filter), + op: BinOp::And, + right: Box::new(inner.clone()), + }; + } + Ok((filter, most, given.budget.reserve(0, "query")?)) + }); + Ok(Some(Firsts { + table, + qualifier, + order, + wanted: wanted(select, &Scope::of(qualifier, &table.meta.columns)), + parts: parts.collect::>()?, + })) +} + +/// The rows `firsts` asks for: of each partition, the first rows in the window's order, read +/// through a key or index that gives that order. `None` when a partition has none that does. +pub(super) fn first<'a, 'c: 'a>( + firsts: &'a mut Firsts<'c>, + given: &'a Given<'a>, +) -> Result>> { + let (table, qualifier, order) = (firsts.table, firsts.qualifier, firsts.order); + let scope = Scope::of(qualifier, &table.meta.columns); + let width = table.meta.columns.len(); + let mut parts: Vec> = Vec::new(); + for (filter, most, seeing) in &mut firsts.parts { + let filter: &'a Expr = filter; + let mut filtered = vec![false; width]; + reads(filter, &scope, given.params, &mut filtered)?; + let visible = Visible::new(table, given.catalog, given.reader, seeing)?; + let table = table::Source::new(table, Some(filter), &given.ctx, given.read, visible); + let table = table.named(qualifier).reading(filtered, &firsts.wanted); + let path = table.choose(order, &[])?; + if !path.in_order { + return Ok(None); + } + table.say(&[], order, &[])?; + parts.push(Box::new(Cut { + input: Box::new(Rows { table, path }), + offset: 0, + limit: *most, + })); + } + Ok(Some(From { + rows: Box::new(Parts(parts)), + scope, + filter: None, + })) +} + +/// The rows of one source after another's. Holds nothing. +pub(super) struct Parts<'a>(pub(super) Vec>); + +impl Source for Parts<'_> { + fn rows(&self, reservation: &mut Reservation, each: &mut Each<'_>) -> Result { + let (mut read, mut more) = (0, true); + for part in &self.0 { + if !more { + break; + } + read += part.rows(reservation, &mut |row, bytes, reservation| { + more = each(row, bytes, reservation)?; + Ok(more) + })?; + } + Ok(read) + } +} diff --git a/v2/contextdb/src/query/mod.rs b/v2/contextdb/src/query/mod.rs index 9f929f4cb..20d8adf44 100644 --- a/v2/contextdb/src/query/mod.rs +++ b/v2/contextdb/src/query/mod.rs @@ -1,41 +1,47 @@ -//! query: answers a SELECT from one table: which rows to read and through which index, the -//! filter, the select list, COUNT, SUM, MIN and MAX, ORDER BY and LIMIT, and a similarity -//! search, whose rows the vector part finds. It holds the one expression evaluator, and counts -//! exactly the rows it reads. +//! query: answers a SELECT from one table or from none: which rows to read and through which +//! index, the filter, the select list, GROUP BY with COUNT, SUM, MIN, MAX and AVG, HAVING, +//! ROW_NUMBER, DISTINCT, ORDER BY, LIMIT and OFFSET, and a similarity search, whose rows the +//! vector part finds. It holds the one expression evaluator, and counts exactly the rows it +//! reads. //! //! It never changes anything. +mod aggregate; mod bind; mod counts; mod expression; mod for_write; +mod graph; mod inspect; +mod join; +mod plan; +mod rank; mod search; +mod sort; +mod subquery; mod table; #[cfg(test)] mod tests; +mod union; mod visible; +mod window; -use std::cmp::Ordering; +use std::cell::Cell; use std::collections::HashMap; use std::fmt; pub(crate) use expression::{EvalContext, Scope, eval, reads}; pub(crate) use for_write::{Asked, rows_for_write}; pub(crate) use inspect::explain; +pub(crate) use table::equal; pub(crate) use visible::{Reader, Visible}; use crate::memory::{Budget, Reservation}; -use crate::schema::{Catalog, Table}; -use crate::sql::ast::SortDirection; -use crate::sql::plan::{ProjectColumn, SortKey}; -use crate::sql::{Expr, Plan}; +use crate::schema::Catalog; +use crate::sql::{Plan, not_supported}; use crate::store::Read; -use crate::types::{ColumnType, Error, Result, Value}; -use expression::{ - Arithmetic, arithmetic, column_index, compare, most_bytes, sort_order, unsupported, -}; -use table::Source; +use crate::types::{Result, Value}; +use plan::Given; /// What a statement returned: the column names and rows of a SELECT, or the number of rows a /// write affected. Its rows stay counted against the memory limit until it is dropped. @@ -150,15 +156,18 @@ pub(crate) fn memory_limit_shown(budget: &Budget, opened_under: Option) -> /// Answers one planned SELECT from one store, for one reader. /// -/// Every row comes from the table source, which picks an index when the plan's filter can use -/// one and scans otherwise, and hands on only the rows `reader` may see. A `COUNT(*)` is -/// answered with no row read when a kept number or the entries of one index range give it. -/// Loads a value kept beside its row only when a selected or filtered column needs it. The -/// result, and any sort or grouping on the way to it, grows through reservations on `budget` -/// and refuses with `MemoryBudgetExceeded` before it grows. +/// The statement is answered by the row sources `plan::select` puts one above the other. At +/// the bottom is what FROM names: the table source, which picks an index when the filter can +/// use one and scans otherwise, hands on only the rows `reader` may see, and loads a value kept +/// beside its row only when a selected or filtered column needs it. Above it the rows are +/// aggregated, or sorted when the path does not give the order and the select list worked +/// out; then DISTINCT, OFFSET and LIMIT. A `COUNT(*)` is answered with no row read when a kept +/// number or the entries of one index range give it. The result, and whatever a source keeps +/// on the way to it, grows through reservations on `budget` and refuses with +/// `MemoryBudgetExceeded` before it grows. /// -/// A similarity search, `ORDER BY column <=> vector LIMIT k`, is answered by the vector part -/// from the rows this part lets it see, and returns the nearest rows first. +/// A similarity search, `ORDER BY column <=> vector LIMIT k`, is the table source of its +/// statement: the vector part finds the nearest of the rows this part lets it see. pub(crate) fn run( plan: &Plan, params: &HashMap, @@ -168,339 +177,74 @@ pub(crate) fn run( budget: &Budget, now: i64, ) -> Result { - if let Some(found) = search::run(plan, params, catalog, read, reader, budget, now)? { - return Ok(found); - } if let Some(shown) = inspect::show(plan, catalog, read, budget)? { return Ok(shown); } - let select = Select::of(plan)?; - let table = catalog - .table(select.table) - .ok_or_else(|| Error::TableNotFound(select.table.to_owned()))?; - - // Everything the statement names is looked up before a row is read. - let width = table.meta.columns.len(); - let (mut filtered, mut wanted) = (vec![false; width], vec![false; width]); - if let Some(filter) = select.filter { - reads(filter, table, params, &mut filtered)?; - } - for key in select.order { - reads(&key.expr, table, params, &mut wanted)?; + if let Plan::Explain(plan) = plan { + let lines = inspect::explain(plan, params, catalog, read, reader, budget, now)?; + let rows = lines.lines().map(|line| vec![Value::Text(line.to_owned())]); + return Ok(QueryResult::from_rows( + vec!["QUERY PLAN".to_owned()], + rows.collect(), + )); } - let mut aggregates = Vec::new(); - match select.columns { - None => wanted.fill(true), - Some(columns) => { - for column in columns { - let Some(aggregate) = Aggregate::of(&column.expr)? else { - reads(&column.expr, table, params, &mut wanted)?; - continue; - }; - if let Some(of) = aggregate.of { - reads(of, table, params, &mut wanted)?; - aggregate.check(table, of)?; - } - aggregates.push(aggregate); - } - if !aggregates.is_empty() && aggregates.len() < columns.len() { - return Err(unsupported("a column beside an aggregate (GROUP BY)")); - } - } - } - let columns = names(table, select.columns, !aggregates.is_empty()); - + let Plan::Select(select) = plan else { + return Err(not_supported("this statement")); + }; + let given = Given { + params, + catalog, + read, + reader, + budget, + ctx: EvalContext::new(params, now), + evaluations: &Cell::default(), + named: None, + bound: None, + }; // What the reader's filter holds is given back with the statement. let mut seeing = budget.reserve(0, "query")?; - let visible = Visible::new(table, catalog, reader, &mut seeing)?; - let source = - Source::new(table, select.filter, params, now, read, visible).reading(filtered, &wanted); - let limit = select.limit.map_or(usize::MAX, |limit| { - usize::try_from(limit).unwrap_or(usize::MAX) - }); + let (columns, source) = plan::select(select, &given, &mut seeing)?; let mut reservation = budget.reserve(0, "query")?; let mut rows = Vec::new(); - let mut examined = 0; - let scope = table.scope(); - - if !aggregates.is_empty() { - let counted = match aggregates.iter().all(|aggregate| aggregate.of.is_none()) { - true => { - let ctx = EvalContext::new(params, now); - counts::count_without_rows(table, select.filter, reader, &ctx, read)? - } - false => None, - }; - if let Some(count) = counted { - for aggregate in &mut aggregates { - aggregate.seen = count as i64; - } - } else { - let path = source.choose(&[], &[])?; - examined = source.walk(&path, &mut reservation, |_, row, bytes, reservation| { - for aggregate in &mut aggregates { - aggregate.add(&scope, &row, params, now, reservation)?; - } - reservation.shrink(bytes); - Ok(true) - })?; - } - if limit > 0 { - // What a least or greatest value takes is already held. - reservation.grow(row_overhead(aggregates.len()))?; - rows.push(aggregates.into_iter().map(Aggregate::answer).collect()); - } - } else if limit > 0 { - // The select list worked out for one row. - let moved = source.moved(select.columns)?; - let output = |row: Vec, bytes: u64, reservation: &mut Reservation| { - source.output(select.columns, &moved, row, bytes, None, reservation) - }; - let path = source.choose(select.order, &[])?; - if path.in_order { - examined = source.walk(&path, &mut reservation, |_, row, bytes, reservation| { - rows.push(output(row, bytes, reservation)?); - Ok(rows.len() < limit) - })?; - } else { - let mut sorting: Vec = Vec::new(); - let mut key_bytes = 0; - examined = source.walk(&path, &mut reservation, |_, row, bytes, reservation| { - let order = select.order; - let most = order - .iter() - .map(|key| most_bytes(&key.expr, &scope, &row, params)); - let held = row_overhead(order.len()) + most.sum::(); - reservation.grow(held + size_of::() as u64)?; - key_bytes += held + size_of::() as u64; - let keys = order - .iter() - .map(|key| eval(&key.expr, &scope, &row, &EvalContext::new(params, now))) - .collect::>>()?; - sorting.push(Sorting { keys, row, bytes }); - Ok(true) - })?; - sorting.sort_by(|a, b| { - let keys = a.keys.iter().zip(&b.keys).zip(select.order); - keys.map(|((a, b), key)| match key.direction { - SortDirection::Desc => sort_order(a, b).reverse(), - _ => sort_order(a, b), - }) - .find(|order| order.is_ne()) - .unwrap_or(Ordering::Equal) - }); - for cut in sorting.drain(limit.min(sorting.len())..) { - reservation.shrink(cut.bytes); - } - for kept in sorting { - rows.push(output(kept.row, kept.bytes, &mut reservation)?); - } - reservation.shrink(key_bytes); - } - } - + let examined = source.rows(&mut reservation, &mut |row, _, _| { + rows.push(row); + Ok(true) + })?; Ok(QueryResult { columns, rows, rows_affected: 0, rows_examined: examined, - distance_evaluations: 0, + distance_evaluations: given.evaluations.get(), _reservation: Some(reservation), }) } -/// What a result calls its columns: the table's own names for `SELECT *` (`None`), otherwise -/// each item's `AS` name, a bare column's name, an aggregate's name, and `expr` for any other -/// expression. -fn names(table: &Table, columns: Option<&[ProjectColumn]>, aggregates: bool) -> Vec { - let Some(columns) = columns else { - let declared = table.meta.columns.iter(); - return declared.map(|column| column.name.clone()).collect(); - }; - columns - .iter() - .map(|column| match (&column.alias, &column.expr) { - (Some(alias), _) => alias.clone(), - (None, Expr::Column(column)) => column.column.clone(), - (None, Expr::FunctionCall { name, .. }) if aggregates => name.clone(), - (None, _) => "expr".to_owned(), - }) - .collect() -} - -/// One planned SELECT, as the planner nests it: LIMIT over the select list over ORDER BY over -/// one table with its filter. -struct Select<'a> { - table: &'a str, - filter: Option<&'a Expr>, - order: &'a [SortKey], - /// `None` for `SELECT *`. - columns: Option<&'a [ProjectColumn]>, - limit: Option, -} - -impl<'a> Select<'a> { - /// Reads the shape out of a plan, refusing by name a plan this version does not answer. - fn of(mut plan: &'a Plan) -> Result> { - let (mut limit, mut columns) = (None, None); - let mut order: &[SortKey] = &[]; - if let Plan::Limit { input, count } = plan { - limit = Some(*count); - plan = &**input; - } - if let Plan::Project { - input, - columns: list, - } = plan - { - columns = Some(list.as_slice()); - plan = &**input; - } - if let Plan::Sort { input, keys } = plan { - order = keys; - plan = &**input; - } - let Plan::Scan { table, filter } = plan else { - return Err(unsupported("this statement")); - }; - let (table, filter) = (table.as_str(), filter.as_ref()); - Ok(Select { - table, - filter, - order, - columns, - limit, - }) - } -} - -/// A row waiting to be sorted: the values it sorts by, and the bytes the row holds of the -/// statement's reservation. -struct Sorting { - keys: Vec, - row: Vec, - bytes: u64, -} - -/// One aggregate of a select list, and its answer over the rows seen so far. -struct Aggregate<'a> { - function: Function, - /// What is counted, added or compared; `None` for `COUNT(*)`. - of: Option<&'a Expr>, - /// How many rows took part: every row for `COUNT(*)`, otherwise those where `of` is not NULL. - seen: i64, - /// The sum, the least or the greatest so far; NULL until a row takes part. - value: Value, - /// The bytes of the statement's reservation that `value` holds. - held: u64, -} - -#[derive(Clone, Copy, PartialEq)] -enum Function { - Count, - Sum, - Min, - Max, -} - -impl<'a> Aggregate<'a> { - /// The aggregate an item of a select list is, if it is one. - fn of(expr: &'a Expr) -> Result>> { - let Expr::FunctionCall { name, args } = expr else { - return Ok(None); - }; - let functions = [ - ("COUNT", Function::Count), - ("SUM", Function::Sum), - ("MIN", Function::Min), - ("MAX", Function::Max), - ]; - let Some((_, function)) = functions - .into_iter() - .find(|(known, _)| name.eq_ignore_ascii_case(known)) - else { - return Ok(None); - }; - let [of] = args.as_slice() else { - return Err(Error::PlanError(format!("{name} takes one argument"))); - }; - let every_row = function == Function::Count - && matches!(of, Expr::Column(column) if column.column == "*"); - Ok(Some(Aggregate { - function, - of: (!every_row).then_some(of), - seen: 0, - value: Value::Null, - held: 0, - })) - } - - /// Refuses a SUM over a column that does not hold numbers, whatever rows the table has. - fn check(&self, table: &Table, of: &Expr) -> Result<()> { - let Expr::Column(column) = of else { - return Ok(()); - }; - let column = &table.meta.columns[column_index(table, column)?]; - if self.function == Function::Sum - && !matches!(column.column_type, ColumnType::Integer | ColumnType::Real) - { - return Err(Error::PlanError(format!( - "SUM needs numbers, and the column {} holds none", - column.name - ))); - } - Ok(()) - } - - /// Takes one row into the answer. A NULL takes no part in any aggregate but `COUNT(*)`. - /// The memory of the value is asked for before it is made, and given back unless the value - /// is kept as the least or the greatest so far. - fn add( - &mut self, - scope: &Scope, - row: &[Value], - params: &HashMap, - now: i64, - reservation: &mut Reservation, - ) -> Result<()> { - if let Some(of) = self.of { - let most = most_bytes(of, scope, row, params); - reservation.grow(most)?; - let value = eval(of, scope, row, &EvalContext::new(params, now))?; - if value == Value::Null { - reservation.shrink(most); - return Ok(()); - } - let first = self.value == Value::Null; - let better = match self.function { - Function::Count => None, - Function::Sum => { - let so_far = if first { &Value::Int64(0) } else { &self.value }; - self.value = arithmetic(Arithmetic::Add, so_far, &value)?; - None - } - Function::Min => Some(Ordering::Less), - Function::Max => Some(Ordering::Greater), - }; - if better.is_some_and(|better| first || compare(&value, &self.value) == Some(better)) { - reservation.shrink(self.held); - (self.value, self.held) = (value, most); - } else { - reservation.shrink(most); - } - } - self.seen += 1; - Ok(()) - } +/// The values of the SELECTs of one statement, each under the place its text begins. +pub(crate) type Values = Vec<(usize, Vec)>; - /// The answer over the rows taken: a count of nothing is zero, and every other aggregate of - /// nothing is NULL. - fn answer(self) -> Value { - match self.function { - Function::Count => Value::Int64(self.seen), - _ => self.value, - } - } +/// The values of the SELECTs inside the INSERT, UPDATE or DELETE `plan` that `write` is run +/// with, as [`run`] would read them from `read`, each read once before the write changes a row +/// and held in `held`. +pub(crate) fn written( + plan: &Plan, + write: &crate::write::Given, + read: &dyn Read, + held: &mut Reservation, +) -> Result { + let given = Given { + params: write.params, + catalog: write.catalog, + read, + reader: write.reader, + budget: write.budget, + ctx: EvalContext::new(write.params, write.now), + evaluations: &Cell::default(), + named: None, + bound: None, + }; + subquery::written(plan, &given, held) } /// The memory a row of this many values takes before any text, JSON or vector in it. diff --git a/v2/contextdb/src/query/plan.rs b/v2/contextdb/src/query/plan.rs new file mode 100644 index 000000000..0d993ab5d --- /dev/null +++ b/v2/contextdb/src/query/plan.rs @@ -0,0 +1,665 @@ +//! The shape of a statement: the row sources that answer one SELECT, each above the one below. +//! At the bottom is what FROM names; above it the rows are aggregated, or sorted unless they +//! arrive in order and the select list worked out, rows that are the same are given once for +//! DISTINCT, and OFFSET and LIMIT leave rows out and stop the read. Every stage takes a source +//! of rows and the scope of its columns, never a table. + +use std::cell::Cell; +use std::collections::btree_map::Entry; +use std::collections::{BTreeMap, HashMap}; + +use super::aggregate::{Grouped, Groups, spelled}; +use super::expression::{EvalContext, Scope, eval, holds, most_bytes, numbers, reads, unbound}; +use super::graph::Graph; +use super::search::{self, Search}; +use super::sort::{Key, Sort}; +use super::table::{self, Path}; +use super::visible::{Reader, Visible}; +use super::window::{Numbered, Window}; +use super::{counts, join, row_overhead, subquery}; +use crate::memory::{Budget, Reservation}; +use crate::schema::{Catalog, Table}; +use crate::sql::plan::{FromItem, ProjectColumn, SelectPlan, SortKey}; +use crate::sql::{Expr, Plan, not_supported}; +use crate::store::Read; +use crate::types::{ColumnDef, Error, Result, Value, VectorIndexRef, heap_bytes}; + +/// What takes the rows of a source: one row, and the bytes of the statement's reservation the +/// row holds, which are the taker's from then on to pass on or give back. Answers false when +/// it wants no more rows. +pub(super) type Each<'e> = dyn FnMut(Vec, u64, &mut Reservation) -> Result + 'e; + +/// Something that gives rows, one at a time and in its own order. What its columns are is +/// the `Scope` that is made with it and handed to every stage that reads its rows. +pub(super) trait Source { + /// Hands `each` every row until it answers false. What the source keeps on the way is + /// asked of `reservation` before it is kept. Returns how many stored rows were read. + fn rows(&self, reservation: &mut Reservation, each: &mut Each<'_>) -> Result; +} + +/// What one statement is answered with, the same for every source of it. +pub(super) struct Given<'a> { + pub(super) params: &'a HashMap, + pub(super) catalog: &'a Catalog, + pub(super) read: &'a dyn Read, + pub(super) reader: &'a Reader, + /// What a source asks for the memory of a reader's filter it makes for itself. + pub(super) budget: &'a Budget, + /// What every expression of the statement is worked out with beside its row. + pub(super) ctx: EvalContext<'a>, + /// The distances the statement's searches worked out, counted as they are. + pub(super) evaluations: &'a Cell, + /// The last WITH name in reach, which leads to the ones before it. + pub(super) named: Option<&'a subquery::Named<'a>>, + /// For the SELECT of a WITH name read in place: the WHERE of the statement that reads it, + /// which says how much of each partition of a window it asks for. + pub(super) bound: Option<&'a Expr>, +} + +/// One SELECT ready to give its rows: what its columns are called, and the source of them. +/// A statement that reads more than one table of its own is bound here and put together +/// when its rows are asked for. +pub(super) fn select<'a>( + select: &'a SelectPlan, + given: &'a Given<'a>, + seeing: &'a mut Reservation, +) -> Result<(Vec, Box)> { + let (columns, source) = match subquery::Whole::of(select, given) { + Some(whole) => (whole.bound()?, Box::new(whole) as Box), + None => one(select, given, seeing, None)?, + }; + Ok(( + columns.into_iter().map(|column| column.name).collect(), + source, + )) +} + +/// The SELECT itself, without its WITH names, the SELECTs a UNION puts after it and the +/// values of its subqueries: its columns, and the source of its rows over `from`, or over +/// the one table FROM names when `from` is `None`. +/// +/// A form whose source is not built in this version is refused here by its name, before any +/// table is looked up; then every name is bound against the scope of what FROM names, so no +/// refusal depends on the rows. `seeing` is what the reader's filter of the table holds. +pub(super) fn one<'a>( + select: &'a SelectPlan, + given: &'a Given<'a>, + seeing: &'a mut Reservation, + from: Option>, +) -> Result<(Vec, Box)> { + let table = match (select.from.as_slice(), &from) { + ([], _) | (_, Some(_)) => None, + ([FromItem::Table { name, alias }], None) => { + let table = given.catalog.table(name); + let table = table.ok_or_else(|| Error::TableNotFound(name.clone()))?; + Some((table, alias.as_ref().unwrap_or(name).as_str())) + } + ([FromItem::Graph(_)], None) => None, + _ => return Err(not_supported("more than one FROM item")), + }; + // A graph pattern is a source of its own, whose columns are what its COLUMNS gives. + let (graph, mut scope) = match (select.from.as_slice(), &from, table) { + (_, Some(from), _) => (None, from.scope.clone()), + ([FromItem::Graph(pattern)], None, _) => { + let (graph, scope) = Graph::new(pattern, given)?; + (Some(graph), scope) + } + (_, None, Some((table, qualifier))) => (None, Scope::of(qualifier, &table.meta.columns)), + (_, None, None) => (None, Scope::default()), + }; + // A search names a VECTOR column of its table and a vector of its length, or NULL, and + // under USE RANK a policy of that column: all settled before any row, whatever the LIMIT. + let search = match (table, search::asked(select)) { + (Some((table, _)), Some((_, column, near))) => { + let (at, _) = scope.find(column)?; + let Some(vector) = table.vector(&column.column) else { + let (table, column) = (table.name.clone(), column.column.clone()); + let index = VectorIndexRef { table, column }; + return Err(Error::UnknownVectorIndex { index }); + }; + let (index, expected) = (table.vector_ref(vector), table.dimension(vector)); + // Explained, a `$name` with no value as the vector, taken as NULL, or beside a key + // column is left open: neither changes what the search says. + let explained = given.ctx.said.is_some(); + if explained { + let keys = search::Scope::new(table, vector, given); + keys.keys(select.filter.as_ref())?; + scope.open = keys.unbound.take(); + } + let near = match near { + Expr::Parameter(name) if explained && !given.params.contains_key(name) => { + scope.open.push(name.clone()); + None + } + near => numbers(eval(near, &table.scope(), &[], &given.ctx)?)?, + }; + let actual = near.as_ref().map_or(expected, Vec::len); + if actual != expected { + return Err(Error::VectorIndexDimensionMismatch { + index, + expected, + actual, + }); + } + if let Some(position) = near.iter().flatten().position(|n| !n.is_finite()) { + return Err(Error::InvalidVectorValue { index, position }); + } + let mut declared = table.rules.rank_policies.iter(); + let rank = select.use_rank.as_ref().map(|sort_key| { + let at = declared + .position(|ranked| ranked.column == at && ranked.policy.sort_key == *sort_key); + let sort_key = sort_key.clone(); + at.ok_or(Error::RankPolicyNotFound { index, sort_key }) + }); + // A reader the table its rank joins or this one refuses is refused, whatever follows. + let rank = rank.transpose()?; + let joined = rank.map(|at| &table.rules.rank_policies[at].policy.table); + let joined = joined.and_then(|name| given.catalog.table(name)); + for table in joined.into_iter().chain([table]) { + let mut held = given.budget.reserve(0, "query")?; + Visible::new(table, given.catalog, given.reader, &mut held)?; + } + Some((vector, at, near, rank)) + } + _ => None, + }; + let (params, ctx) = (given.params, &given.ctx); + + // Everything the statement names is looked up before a row is read. + let width = scope.columns().count(); + let (mut filtered, mut wanted) = (vec![false; width], vec![false; width]); + let filter = match &from { + Some(from) => from.filter, + None => select.filter.as_ref(), + }; + if let Some(filter) = filter { + reads(filter, &scope, params, &mut filtered)?; + } + let (limit, offset) = limits(select, params)?; + let list = list(select); + let stored = table.map(|(table, _)| table); + let groups = Groups::of(select, &scope, stored, params, &mut wanted)?; + let (mut window, mut carried) = (None, None); + if groups.is_none() { + window = Window::of(select)?; + // A search's one sort key is the order its rows arrive in: no stage works it out. A + // select item written as that key takes the true distance the search has for each row. + let ordered = search.is_some() && window.is_none() && select.order_by.len() == 1; + let own = |column: &ProjectColumn| column.expr == select.order_by[0].expr; + let unranked = list.filter(|_| ordered && select.use_rank.is_none()); + carried = unranked.and_then(|list| list.iter().position(own)); + let order = select.order_by.iter().map(|key| &key.expr); + let order = order.skip(usize::from(ordered)); + let listed = list.unwrap_or_default().iter().enumerate(); + let listed = listed.filter(|(at, _)| Some(*at) != carried); + for expr in order.chain(listed.map(|(_, column)| &column.expr)) { + reads(expr, &scope, params, &mut wanted)?; + } + } + if list.is_none() && groups.is_none() { + wanted.fill(true); + } + // A SELECT DISTINCT sorts only by what it lists, as Postgres has it. + let listed = list.unwrap_or_default().iter(); + let listed: Vec<_> = listed.map(|item| spelled(&item.expr, &scope)).collect(); + let unlisted = |key: &SortKey| match list { + Some(_) => !listed.contains(&spelled(&key.expr, &scope)), + None => !matches!(key.expr, Expr::Column(_)), + }; + if select.distinct && select.order_by.iter().any(unlisted) { + let why = "for SELECT DISTINCT, ORDER BY expressions must appear in the select list"; + return Err(Error::PlanError(why.to_owned())); + } + let columns = subquery::columns(&scope, list, params)?; + let search = search.filter(|_| groups.is_none() && window.is_none()); + if select.use_rank.is_some() && search.is_none() { + return Err(Error::UseRankRequiresVectorOrder); + } + let order = select.order_by.iter().map(|key| &key.expr); + let listed = list.unwrap_or_default().iter().map(|column| &column.expr); + let mut written = order.chain(listed).chain(filter).chain(&select.having); + if let (Some(Table { name, rules, .. }), None) = (stored, &search) + && !rules.exclude_vector_states.is_empty() + && written.any(|expr| holds(expr, |expr| matches!(expr, Expr::Distance { .. }))) + { + return Err(Error::PlanError(format!( + "{name} leaves rows in some states out of vector search (EXCLUDE VECTOR), so <=> is \ + answered there only as ORDER BY <=> LIMIT " + ))); + } + + // A count of every row is answered with no row read when a kept number gives it. + let counted = match (table, &groups) { + (Some((table, _)), Some(groups)) if groups.counts_every_row() => { + counts::count_without_rows(table, &scope, filter, given.reader, ctx, given.read)? + } + _ => None, + }; + // A grouped count is answered from one record for each group when a kept count has them. + let kept = match (table, &groups) { + (Some((table, _)), Some(groups)) => { + groups.kept(table, &scope, filter, given.reader, ctx, given.read)? + } + _ => None, + }; + let cut = |input| -> Box { + Box::new(Cut { + input, + offset, + limit, + }) + }; + // Only the rows that can leave are kept, unless which rows leave is settled later. + let most = match select.distinct { + true => usize::MAX, + false => limit.saturating_add(offset), + }; + // Rows whose select list is worked out already: DISTINCT, then OFFSET and LIMIT. + let leave = |input: Box| match select.distinct { + true => cut(Box::new(Distinct { input })), + false => cut(input), + }; + + // What FROM names, and whether its rows arrive in the order asked for: the order of the + // window when there is one, and none for rows that are grouped. + let order = match groups { + Some(_) => &[], + None => select.order_by.as_slice(), + }; + let reached = window.as_ref().map_or(order, Window::keys); + let (mut rows, in_order): (Box, bool) = match (table, search, graph, from) { + (Some(_), ..) if counted.is_some() || kept.is_some() => (Box::new(One(Vec::new())), true), + // The distance is the one sort key, or a rank orders the rows. + (Some((table, qualifier)), Some((vector, at, near, rank)), ..) => { + let search = Search { + table, + qualifier, + vector, + at, + near, + rank, + select, + filtered, + wanted, + most, + given, + }; + // The search of the SELECT explained says only itself, in place of all said before. + let explained = + matches!(ctx.explained, Some(Plan::Select(top)) if std::ptr::eq(top, select)); + if let Some(said) = ctx.said.filter(|_| explained) { + said.take(); + said.replace(vec![super::inspect::searched(&search)?]); + } + (Box::new(search), select.order_by.len() == 1) + } + (Some((table, qualifier)), None, ..) => { + let visible = Visible::new(table, given.catalog, given.reader, seeing)?; + let rows = table::Source::new(table, filter, ctx, given.read, visible) + .named(qualifier) + .reading(filtered, &wanted); + let path = rows.choose(reached, &[])?; + rows.say(&[], reached, &[])?; + let in_order = path.in_order; + (Box::new(Rows { table: rows, path }), in_order) + } + // With no table: the matches of a pattern or the rows of a join or of a WITH name, in + // no order, or the one row of no FROM, each through the statement's filter. + (None, _, Some(graph), _) => (Box::new(graph), reached.is_empty()), + (None, _, None, Some(from)) => (from.rows, false), + (None, _, None, None) => (Box::new(One(Vec::new())), true), + }; + if let (None, Some(filter)) = (table, filter) { + rows = Box::new(Filter { + input: rows, + scope: scope.clone(), + filter, + ctx, + }); + } + if let Some(groups) = groups { + let grouped = Grouped { + input: rows, + scope, + groups, + ctx, + counted, + kept, + most, + }; + return Ok((columns, leave(Box::new(grouped)))); + } + if let Some(window) = window { + let numbered = Numbered { + input: rows, + scope, + window, + ctx, + in_order, + most, + }; + return Ok((columns, leave(Box::new(numbered)))); + } + if !in_order { + rows = Box::new(Sort { + input: rows, + scope: scope.clone(), + order, + ctx, + most, + }); + } + let mut moved = moved(list, &scope); + carried.into_iter().for_each(|at| moved[at] = Some(width)); + let listed = |input| -> Box { + Box::new(Project { + input, + scope, + columns: list, + moved, + ctx, + }) + }; + let rows = match select.distinct { + true => cut(Box::new(Distinct { + input: listed(rows), + })), + false => listed(cut(rows)), + }; + Ok((columns, rows)) +} + +/// The select list of a SELECT unless it is `*`, which is `None`. +pub(super) fn list(select: &SelectPlan) -> Option<&[ProjectColumn]> { + let star = matches!( + select.columns.as_slice(), + [ProjectColumn { expr: Expr::Column(column), alias: None }] + if column.table.is_none() && column.column == "*" + ); + (!star).then_some(select.columns.as_slice()) +} + +/// What a result calls its columns: the names of the scope's columns for `SELECT *` (`None`), +/// otherwise each item's `AS` name, or without one the name the expression gives it. +pub(super) fn names(scope: &Scope, columns: Option<&[ProjectColumn]>) -> Vec { + let Some(columns) = columns else { + return scope.columns().map(|column| column.name.clone()).collect(); + }; + columns.iter().map(ProjectColumn::name).collect() +} + +/// How many rows LIMIT lets through and how many OFFSET leaves out first: the number written, +/// or the value bound to the `$name` written in its place, which is refused unless it is a +/// whole number that is not negative. No LIMIT is every row, and no OFFSET is none left out. +pub(super) fn limits( + select: &SelectPlan, + params: &HashMap, +) -> Result<(usize, usize)> { + let count = |written: Option, name: &Option, word: &str| { + let count = match name { + None => written, + Some(name) => match params.get(name).ok_or_else(|| unbound(name))? { + Value::Int64(count) if *count >= 0 => Some(*count as u64), + _ => { + return Err(Error::PlanError(format!( + "{word} ${name} needs a whole number that is not negative" + ))); + } + }, + }; + Ok(count.map(|count| usize::try_from(count).unwrap_or(usize::MAX))) + }; + let limit = count(select.limit, &select.limit_name, "LIMIT")?; + let offset = count(select.offset, &select.offset_name, "OFFSET")?; + Ok((limit.unwrap_or(usize::MAX), offset.unwrap_or(0))) +} + +/// Hands on the rows a source kept, each with the bytes it holds and the bytes that were held +/// beside it, which are given back. Once `each` answers false the rest give back theirs too. +pub(super) fn hand_on( + kept: impl Iterator, u64, u64)>, + reservation: &mut Reservation, + each: &mut Each<'_>, +) -> Result<()> { + let mut more = true; + for (row, bytes, beside) in kept { + reservation.shrink(beside); + match more { + true => more = each(row, bytes, reservation)?, + false => reservation.shrink(bytes), + } + } + Ok(()) +} + +/// The rows of one table that a path reaches, in the path's order: those the reader may see +/// and the statement's filter passes. Holds the row it is handing on and nothing else. +pub(super) struct Rows<'a> { + pub(super) table: table::Source<'a>, + pub(super) path: Path, +} + +impl Source for Rows<'_> { + fn rows(&self, reservation: &mut Reservation, each: &mut Each<'_>) -> Result { + let each = |_, row, bytes, reservation: &mut Reservation| each(row, bytes, reservation); + self.table.walk(&self.path, reservation, each) + } +} + +/// One row that is known before any is read: the row of no columns that a SELECT without FROM +/// works its select list out over, and a count that needed no row. Its values are numbers. +struct One(Vec); + +impl Source for One { + fn rows(&self, reservation: &mut Reservation, each: &mut Each<'_>) -> Result { + let bytes = row_overhead(self.0.len()); + reservation.grow(bytes)?; + each(self.0.clone(), bytes, reservation)?; + Ok(0) + } +} + +/// The rows of its input that a filter passes; the others give their bytes back. For rows +/// that are not the rows of one table, whose source applies the statement's filter itself. +pub(super) struct Filter<'a> { + pub(super) input: Box, + pub(super) scope: Scope<'a>, + pub(super) filter: &'a Expr, + pub(super) ctx: &'a EvalContext<'a>, +} + +impl Source for Filter<'_> { + fn rows(&self, reservation: &mut Reservation, each: &mut Each<'_>) -> Result { + self.input + .rows(reservation, &mut |row, bytes, reservation| { + if eval(self.filter, &self.scope, &row, self.ctx)? == Value::Bool(true) { + return each(row, bytes, reservation); + } + reservation.shrink(bytes); + Ok(true) + }) + } +} + +/// For each item of a select list, the column whose value it moves out of a row of `scope`: +/// the column it names, when no other item of the list reads that column. Any other item +/// copies what it reads. Empty for `SELECT *`, which hands the row over as it is. +pub(super) fn moved(columns: Option<&[ProjectColumn]>, scope: &Scope) -> Vec> { + let columns = columns.unwrap_or_default(); + let mut readers = vec![0; scope.columns().count()]; + for column in columns { + let mut read = vec![false; readers.len()]; + super::expression::mark(&column.expr, scope, &mut read); + for (readers, read) in readers.iter_mut().zip(read) { + *readers += usize::from(read); + } + } + let alone = |column: &ProjectColumn| match &column.expr { + Expr::Column(named) => scope.find(named).ok().map(|(at, _)| at), + _ => None, + }; + let moved = columns.iter().map(alone); + moved.map(|at| at.filter(|at| readers[*at] == 1)).collect() +} + +/// A select list over the rows of one scope: `moved` is [`moved`] of the list. +pub(super) struct List<'s, 'a> { + /// `None` for `SELECT *`. + pub(super) columns: Option<&'s [ProjectColumn]>, + pub(super) moved: &'s [Option], + pub(super) scope: &'s Scope<'a>, + pub(super) ctx: &'s EvalContext<'a>, +} + +impl List<'_, '_> { + /// The select list worked out for one row that holds `bytes` of `reservation`, or the row + /// itself for `SELECT *`. The memory of the values is asked for before they are made, and + /// the row's bytes are given back once they are. A value that is moved is held once: what + /// it takes passes from the row to the result and is not asked for again. + pub(super) fn of( + &self, + mut row: Vec, + bytes: u64, + reservation: &mut Reservation, + ) -> Result> { + let Some(columns) = self.columns else { + return Ok(row); + }; + let most = columns + .iter() + .map(|column| most_bytes(&column.expr, self.scope, &row, self.ctx)); + let passed = self.moved.iter().flatten().map(|at| heap_bytes(&row[*at])); + let passed = passed.sum::().min(bytes); + reservation.grow(row_overhead(columns.len()) + most.sum::() - passed)?; + let values = columns + .iter() + .zip(self.moved) + .map(|(column, moved)| match moved { + Some(at) => Ok(std::mem::replace(&mut row[*at], Value::Null)), + None => eval(&column.expr, self.scope, &row, self.ctx), + }) + .collect::>>()?; + reservation.shrink(bytes - passed); + Ok(values) + } +} + +/// The rows of `input`, whose columns are `scope`, in `order` when it says one, with the select +/// list `columns` worked out over each: what is written over the groups or a window. +pub(super) fn listed<'a>( + mut input: Box, + scope: Scope<'a>, + (order, columns): (&'a [SortKey], &'a [ProjectColumn]), + ctx: &'a EvalContext<'a>, + most: usize, +) -> Box { + if !order.is_empty() { + let scope = scope.clone(); + input = Box::new(Sort { + input, + scope, + order, + ctx, + most, + }); + } + let moved = vec![None; columns.len()]; + let columns = Some(columns); + Box::new(Project { + input, + scope, + columns, + moved, + ctx, + }) +} + +/// The select list worked out for each row of its input, whose columns are `scope`. +struct Project<'a> { + input: Box, + scope: Scope<'a>, + /// `None` for `SELECT *`. + columns: Option<&'a [ProjectColumn]>, + moved: Vec>, + ctx: &'a EvalContext<'a>, +} + +impl Source for Project<'_> { + fn rows(&self, reservation: &mut Reservation, each: &mut Each<'_>) -> Result { + let list = List { + columns: self.columns, + moved: &self.moved, + scope: &self.scope, + ctx: self.ctx, + }; + self.input + .rows(reservation, &mut |row, bytes, reservation| { + let before = reservation.bytes(); + let row = list.of(row, bytes, reservation)?; + // What the row held has become what the worked-out values hold. + each(row, reservation.bytes() + bytes - before, reservation) + }) + } +} + +/// OFFSET and LIMIT: the first `offset` rows are given back, the next `limit` are handed on, +/// and then the input is asked for no more. Holds nothing. +pub(super) struct Cut<'s> { + pub(super) input: Box, + pub(super) offset: usize, + pub(super) limit: usize, +} + +impl Source for Cut<'_> { + fn rows(&self, reservation: &mut Reservation, each: &mut Each<'_>) -> Result { + if self.limit == 0 { + return Ok(0); + } + let (mut skipped, mut left) = (0, 0); + self.input + .rows(reservation, &mut |row, bytes, reservation| { + if skipped < self.offset { + skipped += 1; + reservation.shrink(bytes); + return Ok(true); + } + left += 1; + Ok(each(row, bytes, reservation)? && left < self.limit) + }) + } +} + +/// DISTINCT: each different row of its input once, in the order the first of each arrived. +/// Reads every row of its input and holds one entry for each different row. +pub(super) struct Distinct<'s> { + pub(super) input: Box, +} + +impl Source for Distinct<'_> { + fn rows(&self, reservation: &mut Reservation, each: &mut Each<'_>) -> Result { + // Beside a row: its entry here, and its place when the rows are put back in the order + // they arrived in. + let beside = 2 * size_of::<(Key<'_, ()>, (usize, u64))>() as u64; + let mut first = BTreeMap::new(); + let examined = self + .input + .rows(reservation, &mut |row, bytes, reservation| { + let arrived = first.len(); + match first.entry(Key(row, &[], ())) { + Entry::Vacant(new) => { + reservation.grow(beside)?; + new.insert((arrived, bytes)); + } + Entry::Occupied(_) => reservation.shrink(bytes), + } + Ok(true) + })?; + let mut kept: Vec<_> = first.into_iter().collect(); + kept.sort_unstable_by_key(|(_, (arrived, _))| *arrived); + let kept = kept + .into_iter() + .map(|(Key(row, ..), (_, bytes))| (row, bytes, beside)); + hand_on(kept, reservation, each)?; + Ok(examined) + } +} diff --git a/v2/contextdb/src/query/rank.rs b/v2/contextdb/src/query/rank.rs new file mode 100644 index 000000000..8207112b2 --- /dev/null +++ b/v2/contextdb/src/query/rank.rs @@ -0,0 +1,122 @@ +//! `USE RANK`: the order a VECTOR column's rank policy gives the rows a similarity search +//! compares. A row's joined row is found by one lookup, and the policy's formula is worked out +//! by the one evaluator over the row, the joined row and `vector_score`, which is one minus the +//! row's distance. + +use std::cmp::Ordering; + +use super::expression::{Scope, column_index, compare, eval, reads}; +use super::plan::Given; +use super::table::Source; +use super::visible::Visible; +use crate::memory::Reservation; +use crate::schema::Table; +use crate::sql::Expr; +use crate::sql::ast::ColumnRef; +use crate::types::{ColumnDef, Error, Result, Value}; + +/// A rank policy ready to rank rows. +pub(super) struct Rank<'a> { + formula: Expr, + /// The columns of the table, then those of the joined table, then `vector_score`. + scope: Scope<'a>, + /// The joined table's rows the reader may see, read for what the formula reads of them. + lookup: Source<'a>, + width: usize, + /// The column of the joined table its row is found by, and the column of the table whose + /// value finds it. + on: usize, + anchor: usize, +} + +impl<'a> Rank<'a> { + /// The policy at `policy` among those of `table`; `score` is the column `vector_score`, and + /// the joined rows are read through `seeing`. Marks in `read`, which has one place for each + /// column of the table, the columns of it the formula reads and the one the joined row is + /// found by. + pub(super) fn of( + table: &'a Table, + policy: usize, + score: &'a [ColumnDef], + given: &'a Given<'a>, + seeing: &'a mut Reservation, + read: &mut [bool], + ) -> Result> { + let (ranked, catalog) = (&table.rules.rank_policies[policy], given.catalog); + let policy = &ranked.policy; + let joined = catalog.table(&policy.table); + let joined = joined.ok_or_else(|| Error::TableNotFound(policy.table.clone()))?; + let on = ColumnRef { + table: None, + column: policy.column.clone(), + }; + let scope = Scope::of(&table.name, &table.meta.columns); + let scope = scope.and(&joined.name, &joined.meta.columns).and("", score); + let formula = crate::sql::formula(&policy.formula)?; + let mut every = vec![false; scope.columns().count()]; + reads(&formula, &scope, given.params, &mut every)?; + // The joined column is read: a row found through a digest is checked against it. + let on = column_index(joined, &on)?; + every[read.len() + on] = true; + let (own, rest) = every.split_at(read.len()); + read.iter_mut().zip(own).for_each(|(read, by)| *read |= by); + read[ranked.anchor] = true; + let width = joined.meta.columns.len(); + let visible = Visible::new(joined, catalog, given.reader, seeing)?; + let lookup = Source::new(joined, None, &given.ctx, given.read, visible); + let lookup = lookup.reading(vec![false; width], rest); + Ok(Rank { + formula, + scope, + lookup, + width, + on, + anchor: ranked.anchor, + }) + } + + /// The rank of a row at `distance` as an answer is put in order going up: its negation, so + /// that highest rank comes first and a NULL rank after every other; and how many stored + /// rows the lookup of the joined row read. That row is the one of lowest key among those + /// the reader may see; with none, its columns are NULL. A BOOLEAN is 1 or 0. + pub(super) fn order( + &self, + row: &[Value], + distance: f64, + given: &Given, + reservation: &mut Reservation, + ) -> Result<(Value, u64)> { + let (mut lowest, mut joined) = (None, vec![Value::Null; self.width]); + let path = (self.lookup).given(&[(self.on, Some(&row[self.anchor]))], &[], &[])?; + // A value that is no key of the joined column, NULL among them, finds no row. + let read = match path.pinned { + 0 => 0, + _ => self + .lookup + .walk(&path, reservation, |key, values, bytes, reservation| { + reservation.shrink(bytes); + // An index entry of a long text stands for every text with its digest. + let equal = + compare(&values[self.on], &row[self.anchor]) == Some(Ordering::Equal); + if equal && lowest.as_ref().is_none_or(|lowest| key < *lowest) { + (lowest, joined) = (Some(key), values); + } + Ok(true) + })?, + }; + let values = row.iter().cloned().chain(joined); + let values = values.chain([Value::Float64(1.0 - distance)]); + let values: Vec = values + .map(|value| match value { + Value::Bool(yes) => Value::Int64(i64::from(yes)), + value => value, + }) + .collect(); + let order = match eval(&self.formula, &self.scope, &values, &given.ctx)? { + Value::Int64(rank) => Value::Float64(-(rank as f64)), + Value::Float64(rank) => Value::Float64(-rank), + _ => Value::Null, + }; + Ok((order, read)) + } +} diff --git a/v2/contextdb/src/query/search.rs b/v2/contextdb/src/query/search.rs index 486c59816..7ce6821fe 100644 --- a/v2/contextdb/src/query/search.rs +++ b/v2/contextdb/src/query/search.rs @@ -1,199 +1,259 @@ -//! A similarity search: the rows of a table that pass the statement's filter and lie nearest a -//! vector. This part settles what is searched for, which partitions the filter selects and -//! which rows may be seen, and works out each row's distance from its stored vector; the vector -//! part finds the rows. +//! A similarity search, one source of a statement's rows: the rows of a table that pass the +//! statement's filter and lie nearest a vector, or under `USE RANK` rank best among those the +//! search compares. This part settles what is searched for, which partitions the filter selects +//! and which rows may be seen, and works out each row's distance from its stored vector; the +//! vector part finds the rows. -use std::cell::Cell; +use std::cell::{Cell, RefCell}; use std::collections::HashMap; -use super::expression::{EvalContext, column_index, eval, reads}; -use super::table::{Source, as_key}; -use super::visible::Visible; -use super::{QueryResult, Reader, names}; -use crate::memory::Budget; -use crate::schema::{Catalog, Table}; -use crate::sql::ast::{BinOp, ColumnRef}; -use crate::sql::{Expr, Plan}; -use crate::store::{Key, Read}; -use crate::types::{ColumnType, Error, Result, Value, VectorIndexRef, vector_from_text}; -use crate::vector::{self, Nearest}; +use super::aggregate::made; +use super::expression::{EvalContext, column_index, eval, holds, sort_order}; +use super::plan::{self, Each, Given, Source}; +use super::rank::Rank; +use super::table::{self, as_key}; +use super::visible::{Reader, Visible}; +use crate::memory::Reservation; +use crate::schema::{Table, VectorColumn}; +use crate::sql::Expr; +use crate::sql::ast::{BinOp, ColumnRef, SortDirection}; +use crate::sql::plan::{FromItem, SelectPlan, SortKey}; +use crate::store::Key; +use crate::types::{Error, Result, Value, VectorSearchMode}; +use crate::vector::{self, Nearest, Planned, Route}; /// The most key tuples a filter may name; past that the search reads every partition. const MOST_TUPLES: usize = 4096; -/// Answers a planned similarity search, a `VectorSearch` under the select list unless the -/// statement is `SELECT *`: the `k` rows that pass the filter and have a vector nearest the one -/// searched for, nearest first, rows at one distance in key order. `None` for any other plan. -/// -/// The column, the mode, the vector and every name of the statement are settled before a row -/// is read, so a refusal does not depend on what the table holds. Then the vector part searches -/// the partitions the filter selects and asks, row by row, for the distance: the row is read, -/// the whole filter applied, and the distance worked out from the row's stored vector. Each row -/// of the answer is read once more for the select list, in which every `<=>` is the distance -/// the row was ordered by. Every one of those reads is counted. -pub(super) fn run( - plan: &Plan, - params: &HashMap, - catalog: &Catalog, - read: &dyn Read, - reader: &Reader, - budget: &Budget, - now: i64, -) -> Result> { - let (plan, list) = match plan { - Plan::Project { input, columns } => (&**input, Some(columns.as_slice())), - plan => (plan, None), +/// Whether a SELECT is a similarity search, and if so its table, its VECTOR column and the +/// vector it is near: it reads one stored table and nothing beside it, groups no rows, has no +/// DISTINCT and has a LIMIT, and its first sort key is `column <=> value` nearest first, where +/// the value reads no column of a row. Planning asks this; EXPLAIN takes what the plan made. +pub(super) fn asked(select: &SelectPlan) -> Option<(&String, &ColumnRef, &Expr)> { + let [FromItem::Table { name, .. }] = select.from.as_slice() else { + return None; }; - let Plan::VectorSearch { - table, - column, - query, - k, - filter, - mode, - } = plan + let Some(SortKey { + expr: Expr::Distance { left, right }, + direction: SortDirection::Asc, + }) = select.order_by.first() else { - return Ok(None); - }; - let filter = filter.as_ref(); - let table = catalog - .table(table) - .ok_or_else(|| Error::TableNotFound(table.clone()))?; - let named = ColumnRef { - table: None, - column: column.clone(), - }; - let at = column_index(table, &named)?; - let index = VectorIndexRef { - table: table.name.clone(), - column: named.column, - }; - let Some(vector) = table.vector(column) else { - return Err(Error::UnknownVectorIndex { index }); + return None; }; - let near = match eval(query, &table.scope(), &[], &EvalContext::new(params, now))? { - Value::Vector(vector) => Some(vector), - Value::Text(text) => vector_from_text(&text), - _ => None, + let Expr::Column(column) = &**left else { + return None; }; - let Some(near) = near else { - return Err(Error::PlanError( - "the right side of <=> is not a vector: write [1.0, 0.0], its text '[1, 0]', or a \ - $name bound to a vector" - .to_owned(), - )); - }; - let actual = near.len(); - if let ColumnType::Vector(expected) = table.meta.columns[at].column_type - && expected != actual - { - return Err(Error::VectorIndexDimensionMismatch { - index, - expected, - actual, - }); - } - if let Some(position) = near.iter().position(|number| !number.is_finite()) { - return Err(Error::InvalidVectorValue { index, position }); - } - - let width = table.meta.columns.len(); - let (mut filtered, mut wanted) = (vec![false; width], vec![false; width]); - if let Some(filter) = filter { - reads(filter, table, params, &mut filtered)?; - } - match list { - None => wanted.fill(true), - Some(list) => { - for column in list { - reads(&column.expr, table, params, &mut wanted)?; - } - } - } - let columns = names(table, list, false); - let k = usize::try_from(*k).unwrap_or(usize::MAX); - if k == 0 { - return Ok(Some(QueryResult::from_rows(columns, Vec::new()))); - } + let alone = select.joins.is_empty() && select.union.is_empty() && select.group_by.is_empty(); + let limited = select.limit.is_some() || select.limit_name.is_some(); + let reads_row = holds(right, |expr| matches!(expr, Expr::Column(_))); + let search = alone && limited && !select.distinct && !reads_row; + search.then_some((name, column, &**right)) +} - let key = vector.partition_key.iter(); - let key = key.filter_map(|name| table.meta.columns.iter().position(|c| c.name == *name)); - let key = key.collect(); - let scope = Scope { - table, - key, - params, - now, - unbound: Cell::default(), - }; - let (scope, on_rows) = (scope.keys(filter)?, scope.on_rows(filter)?); - // A row the vector part asks about is read for the filter and its vector alone; a row of - // the answer for what the select list reads, so a large value is loaded only then. - let mut its_vector = vec![false; width]; - its_vector[at] = true; - // Each is read through the reader's filter, and what a filter holds is given back with - // the statement. - let (mut seeing, mut showing) = (budget.reserve(0, "query")?, budget.reserve(0, "query")?); - let visible = Visible::new(table, catalog, reader, &mut seeing)?; - let asked = - Source::new(table, filter, params, now, read, visible).reading(filtered, &its_vector); - let visible = Visible::new(table, catalog, reader, &mut showing)?; - let returned = - Source::new(table, None, params, now, read, visible).reading(vec![false; width], &wanted); - // What the vector part holds is given back once the rows are built; the rows stay counted - // with the result. - let mut searching = budget.reserve(0, "query")?; - let mut reservation = budget.reserve(0, "query")?; - let mut examined = 0; +/// A similarity search as the source of a statement's rows: the `most` rows of the table nearest +/// the vector `near`, nearest first and rows at one distance in key order, or under `USE RANK` +/// the `most` the column's rank policy puts first among the rows the search compares. A row in +/// a state its table leaves out of every search (`EXCLUDE VECTOR`) is in no answer. +/// +/// When the filter's path reaches few rows (see [`small`]), they are compared exactly; otherwise +/// the vector part searches the partitions the filter selects and asks, row by row, for the +/// distance. A row it asks about is read for the filter, its vector, its state and what its rank +/// reads; a row of the answer once more, for what the statement reads, its distance last unless +/// it reads `*`. With further sort keys one row more is asked for: when it is at the distance of +/// the last, and the search was exact, every row the search may answer with is handed on, for the +/// sort above to choose among the rows at one distance. +pub(super) struct Search<'a> { + pub(super) table: &'a Table, + /// The name the statement gives the table. + pub(super) qualifier: &'a str, + /// The VECTOR column, and where it is in a row. + pub(super) vector: &'a VectorColumn, + pub(super) at: usize, + /// The vector searched for; `None` for NULL, which is near no row. + pub(super) near: Option>, + /// Under `USE RANK`, where its policy is among the table's. + pub(super) rank: Option, + pub(super) select: &'a SelectPlan, + /// The columns the filter reads, and those the statement reads of a row of the answer. + pub(super) filtered: Vec, + pub(super) wanted: Vec, + pub(super) most: usize, + pub(super) given: &'a Given<'a>, +} - let nearest = Nearest { - table: table.id, - vector: vector.id, - column: vector, - mode: mode.unwrap_or_else(|| vector.mode()), - scope: &scope, - query: &near, - k, - filtered: on_rows, - }; - let mut distance_of = |key: &Key| -> Result> { - examined += 1; - let Some((row, bytes)) = asked.row(key, &mut reservation)? else { - return Ok(None); +impl Source for Search<'_> { + fn rows(&self, reservation: &mut Reservation, each: &mut Each<'_>) -> Result { + let (table, vector, select, given) = (self.table, self.vector, self.select, self.given); + let (ctx, filter, at) = (&given.ctx, select.filter.as_ref(), self.at); + let evaluations = given.evaluations; + // A NULL vector is near no row: no row has a distance from it. + let Some(near) = &self.near else { + return Ok(0); }; - let distance = match &row[at] { - Value::Vector(stored) => Some(vector::distance(stored, &near)), + let reserve = || given.budget.reserve(0, "query"); + let (mut seeing, mut looking, mut kept) = (reserve()?, reserve()?, reserve()?); + // A row is read for the filter, its vector, its state and what its rank reads. + let (columns, states) = (&table.meta.columns, &table.rules.exclude_vector_states); + let machine = &table.meta.state_machine; + let state = machine.as_ref().map(|machine| &machine.column); + let state = columns.iter().position(|c| Some(&c.name) == state); + let its = (0..columns.len()).map(|c| c == at || Some(c) == state); + let mut its: Vec = its.collect(); + let excluded = |row: &[Value]| matches!(state.map(|at| &row[at]), Some(Value::Text(s)) if states.contains(s)); + let measured = |row: &[Value]| match (&row[at], excluded(row)) { + (Value::Vector(stored), false) => Some(vector::distance(stored, near)), _ => None, }; - reservation.shrink(bytes); - Ok(distance) - }; - // `None` is a search under INDEXED of a partition whose grouping is behind its writes, or - // one whose filter on rows passes fewer rows than it asks for. - let Some(found) = vector::search(&nearest, read, &mut searching, &mut distance_of)? else { - return Err(Error::VectorIndexedRouteUnavailable { index }); - }; - // Every row the vector part asked about had its distance worked out or was turned away. - let asked_for = examined; - let hits = found.hits; + let (rank, score) = (self.rank, [made(None, "vector_score").0]); + let rank = rank.map(|at| Rank::of(table, at, &score, given, &mut looking, &mut its)); + let rank = rank.transpose()?; + let visible = Visible::new(table, given.catalog, given.reader, &mut seeing)?; + let asked = table::Source::new(table, filter, ctx, given.read, visible); + let asked = asked.named(self.qualifier); + let asked = asked.reading(self.filtered.clone(), &its); + let path = &asked.choose(&[], &[])?; + // A row of the answer passed both filters when it was asked about: now only what is read. + let (admin, mut shown) = (Reader::admin(), reserve()?); + let shown = Visible::new(table, given.catalog, &admin, &mut shown)?; + let shown = table::Source::new(table, None, ctx, given.read, shown); + let shown = shown.reading(vec![false; columns.len()], &self.wanted); + let mut answer = |key: &Key, by: &Value, reservation: &mut Reservation| { + let Some((mut row, bytes)) = shown.row(key, reservation)? else { + return Ok(true); + }; + row.extend(plan::list(select).map(|_| by.clone())); + each(row, bytes, reservation) + }; - let moved = returned.moved(list)?; - let mut rows = Vec::new(); - for hit in &hits { - examined += 1; - if let Some((row, bytes)) = returned.row(&hit.key, &mut reservation)? { - let distance = Some(hit.distance); - rows.push(returned.output(list, &moved, row, bytes, distance, &mut reservation)?); + let further = select.order_by.len() > 1; + let want = self.most.saturating_add(usize::from(further)); + let examined = Cell::new(0); + let mut best = Vec::new(); + + let scope = Scope::new(table, vector, given); + let Some(keys) = scope.keys(filter)? else { + return Ok(0); + }; + // A narrowed handle is never refused by the state of an index it shares: INDEXED is AUTO. + let mode = select.use_vector.unwrap_or_else(|| vector.mode()); + let auto = !given.reader.is_admin() && mode == VectorSearchMode::Indexed; + let nearest = Nearest { + table: table.id, + vector: vector.id, + column: vector, + mode: if auto { VectorSearchMode::Auto } else { mode }, + scope: &keys, + query: near, + k: want, + filtered: scope.on_rows(filter)?, + ranked: rank.is_some(), + }; + let mut searching = given.budget.reserve(0, "query")?; + let mut planned = vector::plan(&nearest, given.read, &mut searching)?; + // Under INDEXED a partition that is behind its writes refuses the search whole. + let index = table.vector_ref(vector); + let refused = Error::VectorIndexedRouteUnavailable { index }; + if nearest.mode == VectorSearchMode::Indexed && planned.iter().any(|p| !p.usable) { + return Err(refused); } + let few = asked.few(path, small(&planned, want))?; + let exact = few || planned.iter().all(|planned| planned.route == Route::Exact); + // Works a row's distance out from its stored vector and offers the row to the answer + // by that distance, or by its rank; the vector part keeps the nearest itself. + let mut offer = |key: &Key, row: &[Value], kept: &mut Reservation| -> Result<_> { + let Some(distance) = measured(row) else { + return Ok(None); + }; + evaluations.set(evaluations.get() + 1); + let by = match &rank { + None if !few => return Ok(Some(distance)), + None => Value::Float64(distance), + Some(rank) => { + let (by, read) = rank.order(row, distance, given, kept)?; + examined.set(examined.get() + read); + by + } + }; + keep(&mut best, want, (by, key), kept)?; + Ok(Some(distance)) + }; + if few { + let read = asked.walk(path, &mut kept, |key, row, bytes, kept| { + offer(&key, &row, kept)?; + kept.shrink(bytes); + Ok(true) + })?; + examined.set(examined.get() + read); + } else { + let mut distance_of = |key: &Key| -> Result> { + examined.set(examined.get() + 1); + let Some((row, bytes)) = asked.row(key, &mut kept)? else { + return Ok(None); + }; + let distance = offer(key, &row, &mut kept)?; + kept.shrink(bytes); + Ok(distance) + }; + // `None` is a search under INDEXED whose filter on rows passes fewer rows than it + // asks for. + let (read, searched) = (given.read, &mut searching); + let found = vector::search(&nearest, read, searched, &mut planned, &mut distance_of)?; + let found = found.ok_or(refused)?; + evaluations.set(evaluations.get() + found.evaluations); + let hits = found.hits.into_iter().filter(|_| rank.is_none()); + best.extend(hits.map(|hit| (Value::Float64(hit.distance), hit.key))); + } + let mut examined = examined.get(); + let tied = matches!(&best[..], [.., (last, ..), (after, ..)] if last == after); + if further && best.len() == want && tied && exact { + let read = asked.walk(path, &mut kept, |key, row, bytes, kept| { + kept.shrink(bytes); + measured(&row).map_or(Ok(true), |d| answer(&key, &Value::Float64(d), reservation)) + })?; + return Ok(examined + read); + } + for (by, key) in best.iter().take(self.most) { + examined += 1; + if !answer(key, by, reservation)? { + break; + } + } + Ok(examined) } - Ok(Some(QueryResult { - columns, - rows, - rows_affected: 0, - rows_examined: examined, - distance_evaluations: found.evaluations + asked_for, - _reservation: Some(reservation), - })) +} + +/// The most rows a filter's path may reach and be compared one by one, and never fewer than the +/// rows `asked` for: a row read by key costs what 16 slots of a block or 128 sketches cost to +/// screen, so a 128th of the live vectors searched through a grouping, a 16th of the others. +pub(super) fn small(planned: &[Planned], asked: usize) -> u64 { + let grouped = |p: &Planned| p.route == Route::Indexed && p.groups > 1; + let weight = |p: &Planned| if grouped(p) { p.live } else { p.live * 8 }; + (planned.iter().map(weight).sum::() / 128).max(asked as u64) +} + +/// Offers a pair to `best`, which holds in order the `most` least pairs offered: by value as +/// ORDER BY puts values going up, NULL last, then by key. A key `best` holds is not offered +/// again. What a pair holds is taken from `reservation` while it is held. +fn keep( + best: &mut Vec<(Value, Key)>, + most: usize, + (value, key): (Value, &Key), + reservation: &mut Reservation, +) -> Result<()> { + let bytes = |key: &Key| (size_of::<(Value, Key)>() + key.as_bytes().len()) as u64; + let before = |(held, by): &(_, Key)| sort_order(held, &value).then(by.cmp(key)).is_lt(); + let at = best.partition_point(before); + if at == most || best.iter().any(|(_, held)| held == key) { + return Ok(()); + } + reservation.grow(bytes(key))?; + best.insert(at, (value, key.clone())); + if best.len() > most + && let Some((_, out)) = best.pop() + { + reservation.shrink(bytes(&out)); + } + Ok(()) } /// The values a filter fixes for the PARTITION_KEY columns, in their order; `None` for a @@ -207,13 +267,28 @@ pub(super) struct Scope<'a> { pub(super) key: Vec, pub(super) params: &'a HashMap, pub(super) now: i64, - /// The `$name` beside a key column that nothing is bound to, once one was met; its column - /// is left open. A search refuses such a name before it asks; `explain` binds nothing, - /// lists every partition and names it. - pub(super) unbound: Cell>, + reader: &'a Reader, + /// Each `$name` beside a key column that nothing is bound to, as it is met; its column is + /// left open. A search refuses such a name before it asks; `explain` binds nothing, lists + /// every partition and names the last. + pub(super) unbound: RefCell>, } -impl Scope<'_> { +impl<'a> Scope<'a> { + /// The scope of the partitions of `vector`, a VECTOR column of `table`. + pub(super) fn new(table: &'a Table, vector: &VectorColumn, given: &Given<'a>) -> Self { + let key = vector.partition_key.iter(); + let key = key.filter_map(|name| table.meta.columns.iter().position(|c| c.name == *name)); + Scope { + table, + key: key.collect(), + params: given.params, + now: given.ctx.now(), + reader: given.reader, + unbound: RefCell::default(), + } + } + /// True when `filter` does more than select partitions, so that some row of the /// partitions [`Scope::keys`] selects may not pass it: a filter on rows. False with no /// filter, and for a filter made only of the selections of key tuples `keys` understood. @@ -238,7 +313,7 @@ impl Scope<'_> { /// key column. fn only_selects(&self, filter: &Expr) -> Result { let whole = |columns: &Expr, values: &Expr| -> Result { - let (columns, values) = (sides(columns), sides(values)); + let (columns, values) = (columns.sides(), values.sides()); let fixed = self.tuple(columns, values)?.iter().flatten().count(); Ok(fixed == columns.len() && fixed == values.len()) }; @@ -272,30 +347,38 @@ impl Scope<'_> { } /// The partitions to search: for each key tuple the filter names, the key of the leading - /// key columns it fixes, which every partition with those values begins with. Empty for - /// every partition: no filter, a tuple that fixes no leading column, or more than 4,096 - /// tuples. It may select too much and never too little: the whole filter is still applied - /// to every row. - pub(super) fn keys(&self, filter: Option<&Expr>) -> Result> { - let (Some(filter), false) = (filter, self.key.is_empty()) else { - return Ok(Vec::new()); + /// key columns it fixes, which every partition with those values begins with; every one for + /// no filter, more than 4,096 tuples, or a tuple that fixes no leading column or names one + /// through a `$name` with no value. It may select too much and never too little: the whole + /// filter is still applied to every row. When the reader's Context is the leading key + /// column they are narrowed first to its own Contexts, so that nothing of another is read + /// or counted: `None` when none is left. + pub(super) fn keys(&self, filter: Option<&Expr>) -> Result>> { + let tuples = match (filter, self.key.is_empty()) { + (Some(filter), false) => self.said(filter)?, + _ => Vec::new(), }; - let tuples = self.said(filter)?; - if tuples.len() > MOST_TUPLES { - return Ok(Vec::new()); - } - let mut keys = Vec::with_capacity(tuples.len()); - for tuple in tuples { - let leading: Vec = tuple.into_iter().map_while(|value| value).collect(); - if leading.is_empty() { - return Ok(Vec::new()); - } + let every = tuples.len() > MOST_TUPLES || tuples.iter().any(|tuple| tuple[0].is_none()); + let every = every || !self.unbound.borrow().is_empty(); + let mut keys = Vec::new(); + for tuple in tuples.iter().filter(|_| !every) { + let leading: Vec = tuple.iter().map_while(Clone::clone).collect(); keys.push(Key::from_values(&leading, &[])?); } // A partition is named once, and not again under a key that begins as another does. keys.sort(); keys.dedup_by(|later, kept| later.starts_with(kept)); - Ok(keys) + let leading = self.table.rules.context_column; + let leading = leading.is_some() && leading == self.key.first().copied(); + let Some(own) = self.reader.contexts.as_ref().filter(|_| leading) else { + return Ok(Some(keys)); + }; + let own = (own.iter()).map(|context| Key::from_values(&[Value::Uuid(context.0)], &[])); + let own = own.collect::>>()?; + let named = if keys.is_empty() { &own } else { &keys }; + let mine = |key: &&Key| own.iter().any(|own| key.starts_with(own)); + let named: Vec = named.iter().filter(mine).cloned().collect(); + Ok((!named.is_empty()).then_some(named)) } /// What a filter says about the key columns: a row passes it only under one of these @@ -326,7 +409,7 @@ impl Scope<'_> { Expr::Column(_) => (left, right), _ => (right, left), }; - vec![self.tuple(sides(column), sides(value))?] + vec![self.tuple(column.sides(), value.sides())?] } Expr::InList { expr, @@ -334,7 +417,7 @@ impl Scope<'_> { negated: false, } => { let tuples = list.iter(); - let tuples = tuples.map(|item| self.tuple(sides(expr), sides(item))); + let tuples = tuples.map(|item| self.tuple(expr.sides(), item.sides())); tuples.collect::>()? } _ => open(), @@ -357,7 +440,7 @@ impl Scope<'_> { }; match value { Expr::Parameter(name) if !self.params.contains_key(name) => { - self.unbound.set(Some(name.clone())); + self.unbound.borrow_mut().push(name.clone()); } value => { let ctx = EvalContext::new(self.params, self.now); @@ -369,11 +452,3 @@ impl Scope<'_> { Ok(tuple) } } - -/// The expressions of one side of `=` or IN: those of a row value, or the one expression. -fn sides(expr: &Expr) -> &[Expr] { - match expr { - Expr::Row(items) => items, - one => std::slice::from_ref(one), - } -} diff --git a/v2/contextdb/src/query/sort.rs b/v2/contextdb/src/query/sort.rs new file mode 100644 index 000000000..7e8bd1a27 --- /dev/null +++ b/v2/contextdb/src/query/sort.rs @@ -0,0 +1,109 @@ +//! ORDER BY for rows that do not arrive in the order asked for: every row of the input is read, +//! and only the rows that can still leave are kept. + +use std::cmp::Ordering; +use std::collections::BinaryHeap; + +use super::expression::{EvalContext, Scope, eval, holds, most_bytes, sort_order}; +use super::plan::{Each, Source, hand_on}; +use super::row_overhead; +use crate::memory::Reservation; +use crate::sql::Expr; +use crate::sql::ast::SortDirection; +use crate::sql::plan::SortKey; +use crate::types::{Result, Value}; + +/// The rows of its input, whose columns are `scope`, in the order of the sort keys; rows the +/// keys do not tell apart stay in the order they arrived in. The keys are worked out with the +/// caller's `ctx`. Holds each kept row and the values it sorts by, and never more than `most` +/// rows and the one that has just arrived: with a LIMIT that is the rows LIMIT and OFFSET let +/// leave, the best so far. +pub(super) struct Sort<'s> { + pub(super) input: Box, + pub(super) scope: Scope<'s>, + pub(super) order: &'s [SortKey], + pub(super) ctx: &'s EvalContext<'s>, + pub(super) most: usize, +} + +impl Source for Sort<'_> { + fn rows(&self, reservation: &mut Reservation, each: &mut Each<'_>) -> Result { + let (scope, ctx) = (&self.scope, self.ctx); + // A row whose distance in a sort key is NULL is in no answer. + let distance = |expr: &Expr| matches!(expr, Expr::Distance { .. }); + // The order of arrival is the last key, so rows the keys do not tell apart keep it. + let order = self.order.iter(); + let descending = order.map(|key| key.direction == SortDirection::Desc); + let descending: Vec = descending.chain([false]).collect(); + // The greatest of a heap is the row that sorts last: the one to drop for a better one. + let mut best = BinaryHeap::new(); + let mut arrived = 0_i64; + let examined = self + .input + .rows(reservation, &mut |row, bytes, reservation| { + let order = self.order.iter(); + let most = order.map(|key| most_bytes(&key.expr, scope, &row, ctx)); + let beside = row_overhead(descending.len()) + + size_of::, u64, u64)>>() as u64 + + most.sum::(); + reservation.grow(beside)?; + let order = self.order.iter(); + let keys = order.map(|key| eval(&key.expr, scope, &row, ctx)); + let keys: Vec = keys + .chain([Ok(Value::Int64(arrived))]) + .collect::>()?; + let mut keyed = self.order.iter().zip(&keys); + if keyed.any(|(key, value)| *value == Value::Null && holds(&key.expr, distance)) { + reservation.shrink(bytes + beside); + return Ok(true); + } + best.push(Key(keys, &descending, (row, bytes, beside))); + arrived += 1; + if best.len() > self.most + && let Some(Key(_, _, (_, bytes, beside))) = best.pop() + { + reservation.shrink(bytes + beside); + } + Ok(true) + })?; + let kept = best + .into_sorted_vec() + .into_iter() + .map(|Key(_, _, kept)| kept); + hand_on(kept, reservation, each)?; + Ok(examined) + } +} + +/// Values in the order of the keys they were worked out for, each greatest first where the flag +/// beside it says so (going up where no flag is), and what rides with them, which takes no part +/// in the order. Values that no key tells apart are equal, as two NULLs are. +pub(super) struct Key<'s, T>(pub(super) Vec, pub(super) &'s [bool], pub(super) T); + +impl Ord for Key<'_, T> { + fn cmp(&self, other: &Self) -> Ordering { + let flags = self.1.iter().chain(std::iter::repeat(&false)); + let values = self.0.iter().zip(&other.0).zip(flags); + let mut orders = values.map(|((left, right), descending)| match descending { + true => sort_order(left, right).reverse(), + false => sort_order(left, right), + }); + orders + .find(|order| order.is_ne()) + .unwrap_or(Ordering::Equal) + } +} + +impl PartialOrd for Key<'_, T> { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl PartialEq for Key<'_, T> { + fn eq(&self, other: &Self) -> bool { + self.cmp(other).is_eq() + } +} + +impl Eq for Key<'_, T> {} diff --git a/v2/contextdb/src/query/subquery.rs b/v2/contextdb/src/query/subquery.rs new file mode 100644 index 000000000..579e20f54 --- /dev/null +++ b/v2/contextdb/src/query/subquery.rs @@ -0,0 +1,411 @@ +//! A SELECT that reads more than one relation of its own: its WITH names, then the values of +//! the SELECTs written inside its expressions, each worked out once before its first row, and +//! then the statement itself over them. What such a statement borrows lives while its rows +//! are read, so it is bound once when it is planned and put together when it is run. + +use std::collections::HashMap; + +use super::bind::{bind, kind}; +use super::expression::Scope; +use super::plan::{self, Each, Given, Source}; +use super::{Values, Visible, aggregate, join, union}; +use crate::memory::Reservation; +use crate::sql::ast::Select; +use crate::sql::plan::{FromItem, ProjectColumn, SelectPlan}; +use crate::sql::{Expr, MAX_EXPR_NESTING, Plan, depth_error, inside}; +use crate::types::{ColumnDef, ColumnType, Error, Result, Value}; + +/// What a statement is put together with. +pub(super) struct Pass<'r> { + /// The statement's reservation: whatever is kept is asked of it first. + pub(super) reservation: &'r mut Reservation, + /// False while the statement is only bound: no row is read. + pub(super) run: bool, + /// The stored rows read on the way: those of subqueries and of WITH names that are kept. + pub(super) examined: u64, +} + +/// What takes a statement once it is put together: its columns and the source of its rows. +pub(super) type Then<'t, R> = dyn FnMut(&[ColumnDef], &dyn Source, &mut Pass<'_>) -> Result + 't; + +/// A statement that is put together when its rows are asked for, `depth` statements deep. +pub(super) struct Whole<'a> { + pub(super) select: &'a SelectPlan, + pub(super) given: &'a Given<'a>, + pub(super) depth: usize, +} + +impl<'a> Whole<'a> { + /// `select` as such a statement; `None` for one SELECT of one table or of none with no + /// SELECT inside it, which needs nothing put together. + pub(super) fn of(select: &'a SelectPlan, given: &'a Given<'a>) -> Option> { + let alone = select.with.is_empty() && select.union.is_empty() && select.joins.is_empty(); + (!alone || !subqueries(select).is_empty()).then_some(Whole { + select, + given, + depth: 0, + }) + } + + /// Binds the statement, reading no row: its columns, or its refusal. + pub(super) fn bound(&self) -> Result> { + let mut nothing = self.given.budget.reserve(0, "query")?; + let mut pass = Pass { + reservation: &mut nothing, + run: false, + examined: 0, + }; + let columns = + &mut |columns: &[ColumnDef], _: &dyn Source, _: &mut Pass<'_>| Ok(columns.to_vec()); + frame(self.select, 0, self.depth, self.given, &mut pass, columns) + } +} + +impl Source for Whole<'_> { + fn rows(&self, reservation: &mut Reservation, each: &mut Each<'_>) -> Result { + let mut pass = Pass { + reservation, + run: true, + examined: 0, + }; + let read = frame( + self.select, + 0, + self.depth, + self.given, + &mut pass, + &mut |_, source, pass| source.rows(pass.reservation, each), + )?; + Ok(read + pass.examined) + } +} + +/// A WITH name in reach of a statement, and through `before` the ones written before it. +pub(super) struct Named<'a> { + name: &'a str, + plan: &'a SelectPlan, + pub(super) columns: Vec, + /// Its rows and the bytes each holds, when the statement reads the name more than once. + kept: Option, u64)>>, + before: Option<&'a Named<'a>>, +} + +impl<'a> Named<'a> { + /// The WITH name a FROM item names, if it is one. + pub(super) fn find(given: &Given<'a>, name: &str) -> Option<&'a Named<'a>> { + let mut next = given.named; + while let Some(named) = next { + if named.name == name { + return Some(named); + } + next = named.before; + } + None + } + + /// Hands on the rows of the name: the kept rows, each copied and asked for again, or the + /// rows of its SELECT as they are read, `depth` statements deep, with the names written + /// before it in reach and `bound`, the WHERE of the statement that reads nothing but this name. + pub(super) fn rows( + &self, + given: &Given<'_>, + bound: Option<&Expr>, + depth: usize, + reservation: &mut Reservation, + each: &mut Each<'_>, + ) -> Result { + let Some(kept) = &self.kept else { + let given = Given { + named: self.before, + bound, + ..*given + }; + let whole = Whole { + select: self.plan, + given: &given, + depth, + }; + return whole.rows(reservation, each); + }; + for (row, bytes) in kept { + reservation.grow(*bytes)?; + if !each(row.clone(), *bytes, reservation)? { + break; + } + } + Ok(0) + } +} + +/// Puts `select` together from its WITH name at `at` on and hands it to `then`: each name in +/// written order, the SELECTs of its UNION, the values of its subqueries and its own source +/// over them; what names and values hold goes back when `then` is done. `depth` statements and +/// joins hold it; one more for it and each of its joins past the limit of nesting is refused. +pub(super) fn frame( + select: &SelectPlan, + at: usize, + depth: usize, + given: &Given<'_>, + pass: &mut Pass<'_>, + then: &mut Then<'_, R>, +) -> Result { + let depth = depth + 1; + if depth + select.joins.len() > MAX_EXPR_NESTING { + return Err(depth_error(depth + select.joins.len())); + } + // The bound is for this SELECT alone, never for one inside it. + let bound = given.bound; + let given = &Given { + bound: None, + ..*given + }; + let start = pass.reservation.bytes(); + if let Some((name, plan)) = select.with.get(at) { + let columns = Whole { + select: plan, + given, + depth, + } + .bound()?; + let mut named = Named { + name, + plan, + columns, + kept: None, + before: given.named, + }; + // A name the rest of the statement reads once is read in place; read more, its rows + // are read once and kept. + if pass.run && reads(select, at + 1, name) > 1 { + let mut rows = Vec::new(); + let read = frame(plan, 0, depth, given, pass, &mut |_, source, pass| { + source.rows(pass.reservation, &mut |row, bytes, reservation| { + reservation.grow(size_of::<(Vec, u64)>() as u64)?; + rows.push((row, bytes)); + Ok(true) + }) + })?; + pass.examined += read; + named.kept = Some(rows); + } + let given = Given { + named: Some(&named), + bound, + ..*given + }; + let taken = pass.reservation.bytes() - start; + let framed = frame(select, at + 1, depth, &given, pass, then); + pass.reservation.shrink(taken); + return framed; + } + if !select.union.is_empty() { + return union::after(select, depth, given, pass, then); + } + + let outer: Vec<_> = relations(select).collect(); + let values = values(subqueries(select), &outer, depth, given, pass)?; + let taken = pass.reservation.bytes() - start; + let given = Given { + ctx: given.ctx.over(&values), + ..*given + }; + let mut seeing = given.budget.reserve(0, "query")?; + let mut firsts = match bound { + Some(bound) => join::firsts(select, bound, &given)?, + None => None, + }; + let first = match &mut firsts { + Some(firsts) => join::first(firsts, &given)?, + None => None, + }; + let mut held = match first { + Some(_) => None, + None => join::held(select, &given)?, + }; + let from = match (first, &mut held) { + (Some(first), _) => Some(first), + (None, Some(held)) => Some(join::from(select, &given, held, depth)?), + (None, None) => None, + }; + let (columns, source) = plan::one(select, &given, &mut seeing, from)?; + let framed = then(&columns, &*source, pass); + pass.reservation.shrink(taken); + framed +} + +/// Works out each SELECT of `found`, written inside a statement whose relations FROM names +/// `outer`, `depth` statements deep: its values, under the place its text begins. +pub(super) fn values( + found: Vec<(&Select, bool)>, + outer: &[&String], + depth: usize, + given: &Given<'_>, + pass: &mut Pass<'_>, +) -> Result { + let mut values = Vec::new(); + for (query, one) in found { + let single = &mut |columns: &[ColumnDef], source: &dyn Source, pass: &mut Pass<'_>| { + if columns.len() != 1 { + return Err(Error::PlanError( + "a SELECT inside an expression gives one column".to_owned(), + )); + } + let _ = query.gives.0.set(columns[0].column_type); + let mut found = Vec::new(); + if pass.run { + // What the row holds stays held for its value. + let rows = &mut |mut row: Vec, _, _: &mut Reservation| { + if one && !found.is_empty() { + return Err(Error::PlanError( + "a SELECT that stands for one value gives one row".to_owned(), + )); + } + found.push(row.swap_remove(0)); + Ok(true) + }; + pass.examined += source.rows(pass.reservation, rows)?; + } + Ok(found) + }; + let found = frame(query, 0, depth, given, pass, single); + values.push(( + query.at.0, + found.map_err(|refused| around(outer, query, refused))?, + )); + } + Ok(values) +} + +/// The values of the SELECTs inside the INSERT, UPDATE or DELETE `plan`, each worked out once +/// before the write changes a row (when it is explained, bound and no row read); then every +/// expression of it bound, those of VALUES with no column in reach. +pub(super) fn written(plan: &Plan, given: &Given, held: &mut Reservation) -> Result { + let Some((name, exprs)) = plan.written() else { + return Ok(Vec::new()); + }; + // A reader the written table refuses is refused before any SELECT of the statement. + let table = given.catalog.table(name); + let table = table.ok_or_else(|| Error::TableNotFound(name.clone()))?; + let seeing = given.budget.reserve(0, "query"); + Visible::new(table, given.catalog, given.reader, &mut seeing?)?; + let mut found = Vec::new(); + exprs.iter().for_each(|expr| gather(expr, &mut found)); + let mut pass = Pass { + reservation: held, + run: given.ctx.said.is_none(), + examined: 0, + }; + let found = values(found, &[name], 0, given, &mut pass)?; + let plain = match plan { + Plan::Insert(insert) => insert.values.iter().map(Vec::len).sum(), + _ => 0, + }; + let (none, scope) = (Scope::of(name, &[]), table.scope()); + for (at, expr) in exprs.into_iter().enumerate() { + bind(expr, if at < plain { &none } else { &scope }, given.params)?; + } + Ok(found) +} + +/// The SELECTs written inside the expressions of `select` itself, each with whether it +/// stands for one value and not for the list after IN. +fn subqueries(select: &SelectPlan) -> Vec<(&Select, bool)> { + let mut found = Vec::new(); + let columns = select.columns.iter().map(|column| &column.expr); + let joins = select.joins.iter().filter_map(|join| join.on.as_ref()); + let order = select.order_by.iter().map(|key| &key.expr); + let rest = (select.filter.iter().chain(&select.group_by)).chain(&select.having); + let patterns = select.from.iter().filter_map(|item| match item { + FromItem::Graph(pattern) => pattern.filter.as_ref(), + FromItem::Table { .. } => None, + }); + for expr in columns + .chain(joins) + .chain(rest) + .chain(order) + .chain(patterns) + { + gather(expr, &mut found); + } + found +} + +/// Adds the SELECTs written in `expr`, at any depth, to `found`. +pub(super) fn gather<'s>(expr: &'s Expr, found: &mut Vec<(&'s Select, bool)>) { + match expr { + Expr::Subquery(query) => found.push((query, true)), + Expr::InSubquery { query, .. } => found.push((query, false)), + _ => {} + } + for inner in inside(expr) { + gather(inner, found); + } +} + +/// How many FROM items and joins name `name` in the WITH SELECTs of `select` from `from` on, in +/// `select` itself, and in the SELECTs of its UNION and inside its expressions, at any depth. +fn reads(select: &SelectPlan, from: usize, name: &str) -> usize { + let items = select + .from + .iter() + .chain(select.joins.iter().map(|join| &join.item)); + let own = + items.filter(|item| matches!(item, FromItem::Table { name: read, .. } if read == name)); + let with = select.with.iter().skip(from).map(|(_, select)| select); + let inner = with.chain(select.union.iter().map(|(_, select)| select)); + let inner = inner.chain(subqueries(select).into_iter().map(|(select, _)| select)); + own.count() + inner.map(|select| reads(select, 0, name)).sum::() +} + +/// The names FROM gives the relations of a SELECT. +fn relations(select: &SelectPlan) -> impl Iterator { + let items = select.from.iter(); + let items = items.chain(select.joins.iter().map(|join| &join.item)); + items.filter_map(|item| match item { + FromItem::Table { name, alias } => Some(alias.as_ref().unwrap_or(name)), + FromItem::Graph(_) => None, + }) +} + +/// The refusal of a subquery `inner` of a statement whose relations are `outer`: a column it +/// could not find under a name that only the statement around it gives a relation is a read of +/// the outer row, which no version does, and is refused by that name. +fn around(outer: &[&String], inner: &SelectPlan, refused: Error) -> Error { + match &refused { + Error::ColumnNotFound { table, .. } + if outer.contains(&table) && !relations(inner).any(|name| name == table) => + { + Error::SubqueryNotSupported + } + _ => refused, + } +} + +/// The columns a SELECT gives a statement that reads it, for the select list `list` over +/// `scope`: each one's name, and its type, which is TEXT for a value whose type no row is +/// needed to know only because it is NULL. +pub(super) fn columns( + scope: &Scope, + list: Option<&[ProjectColumn]>, + params: &HashMap, +) -> Result> { + let Some(list) = list else { + return Ok(scope.columns().cloned().collect()); + }; + let names = plan::names(scope, Some(list)); + let typed = names.into_iter().zip(list).map(|(name, column)| { + // An aggregate is typed by what it answers: binding, which has passed, knows none. + let mut expr = column.expr.clone(); + aggregate::typed(&mut expr); + let column_type = kind(&expr, scope, params).ok().flatten(); + Ok(ColumnDef { + name, + column_type: column_type.unwrap_or(ColumnType::Text), + nullable: true, + primary_key: false, + unique: false, + default: None, + }) + }); + typed.collect() +} diff --git a/v2/contextdb/src/query/table.rs b/v2/contextdb/src/query/table.rs index facb137e7..564a77931 100644 --- a/v2/contextdb/src/query/table.rs +++ b/v2/contextdb/src/query/table.rs @@ -1,21 +1,20 @@ -//! The one source of a table's rows: which rows a statement has to read, reading them through -//! the reader's filter and the statement's own, and working out the select list for a row that -//! was read. +//! The one source of a table's rows: which rows a statement has to read, and reading them +//! through the reader's filter and the statement's own. -use std::cell::RefCell; +use std::cell::{OnceCell, RefCell}; use std::cmp::Ordering; use std::collections::HashMap; -use std::ops::Bound; +use std::ops::Bound::{self, Unbounded}; -use super::expression::{EvalContext, Scope, column_index, eval, most_bytes, reads, sort_order}; +use super::expression::{EvalContext, Scope, eval, sort_order}; use super::row_overhead; use super::visible::Visible; use crate::memory::Reservation; -use crate::schema::Table; +use crate::schema::{Table, field_key}; use crate::sql::Expr; -use crate::sql::ast::{BinOp, SortDirection as Asked}; -use crate::sql::plan::{ProjectColumn, SortKey}; -use crate::store::{Cell, Entry, Key, Read, Row}; +use crate::sql::ast::{BinOp, ColumnRef, Literal, SortDirection as Asked}; +use crate::sql::plan::SortKey; +use crate::store::{Cell, Entry, Key, Keys, Read, Row}; use crate::types::{ColumnType, Result, SortDirection, Value, heap_bytes}; /// The keys or entries between two bounds. @@ -40,14 +39,26 @@ pub(super) struct Path { pub(super) one: bool, /// True when the rows arrive in the order asked for, so that they need no sort. pub(super) in_order: bool, + /// How many leading columns of the key or index it reads are given one value each, or any + /// values when they make the whole key, whose rows a list names exactly. + pub(super) pinned: usize, /// The columns of that order. A run of entries that hold cut values is in the order of /// their digests, and is put in the order of the values themselves before it is handed on. order: Vec<(usize, SortDirection)>, } +impl Path { + /// True when a row's values give this path the whole key, or more than `own` columns. + pub(super) fn serves(&self, own: usize) -> bool { + matches!(self.reach, Reach::Keys(_)) || self.pinned > own + } +} + /// A part of a filter that every kept row must pass, and that compares a column with values /// known before any row is read: one value, or for `=` the values of an `IN` list. pub(super) struct Term { + /// The column; for the field an index over a JSON path keeps, the table's number of columns + /// and the index's place: a column only that index has. pub(super) column: usize, pub(super) op: BinOp, pub(super) values: Vec, @@ -55,6 +66,10 @@ pub(super) struct Term { one: bool, } +/// A key or index tried for a path, with how many of its leading columns were given a value and +/// whether the next was given a range. +type Tried = (Ordered, usize, bool); + /// Something that keeps the rows of a table in an order: the table itself, under its primary /// key, or one of its indexes. struct Ordered { @@ -165,31 +180,79 @@ pub(super) fn as_key(column: ColumnType, value: Value) -> Option { | (ColumnType::Uuid, value @ Value::Uuid(_)) | (ColumnType::Timestamp, value @ Value::Timestamp(_)) | (ColumnType::TxId, value @ Value::TxId(_)) => Some(value), - (ColumnType::Real, Value::Int64(value)) => Some(Value::Float64(value as f64)), + (ColumnType::Real, Value::Int64(value)) if (value as f64) as i128 == i128::from(value) => { + Some(Value::Float64(value as f64)) + } (ColumnType::Uuid, Value::Text(value)) => value.parse().ok().map(Value::Uuid), _ => None, } } +/// True for a value known before any row: a literal, a `$name`, and a SELECT when it is run. +pub(super) fn known(value: &Expr, ctx: &EvalContext) -> bool { + let ran = ctx.said.is_none() && matches!(value, Expr::Subquery(_)); + ran || matches!(value, Expr::Literal(_) | Expr::Parameter(_)) +} + /// Gathers the terms of a filter: the comparisons, `IS NULL` and `IN` lists joined by AND at -/// its top. Answers whether the filter is nothing but the terms gathered. +/// its top, its columns named as `scope` names the table's, and the values of a SELECT after +/// `IN`. Answers whether the filter is nothing but the terms gathered. pub(super) fn collect( table: &Table, + scope: &Scope, filter: &Expr, ctx: &EvalContext, terms: &mut Vec, ) -> Result { - let known = |value: &Expr| matches!(value, Expr::Literal(_) | Expr::Parameter(_)); - let (column, op, values, one) = match filter { + let worked = |value: &Expr| eval(value, scope, &[], ctx); + let (column, op, mut values, one) = match filter { Expr::BinaryOp { left, op, right } if *op == BinOp::And => { - let left = collect(table, left, ctx, terms)?; - return Ok(collect(table, right, ctx, terms)? && left); + let left = collect(table, scope, left, ctx, terms)?; + return Ok(collect(table, scope, right, ctx, terms)? && left); } Expr::BinaryOp { left, op, right } => match (&**left, &**right, op) { (_, _, BinOp::Neq | BinOp::Or) => return Ok(false), - (Expr::Column(column), value, op) if known(value) => (column, *op, vec![value], true), + // `doc -> 'k' -> 'j' = value` is a term of the index over that path, if there is one. + (mut json @ Expr::Field { .. }, value, BinOp::Eq) if known(value, ctx) => { + let mut path = Vec::new(); + while let Expr::Field { + json: of, + key, + as_text: false, + } = json + && let Expr::Literal(Literal::Text(key)) = &**key + { + path.insert(0, key); + json = of; + } + let Expr::Column(column) = json else { + return Ok(false); + }; + let name = &table.meta.columns[scope.find(column)?.0].name; + let place = table.meta.indexes.iter().position(|index| { + index.json_path.iter().eq(path.iter().copied()) && index.columns[0].0 == *name + }); + let field = match worked(value)? { + Value::Text(text) => serde_json::from_str(&text).ok(), + Value::Json(field) => Some(field), + _ => None, + }; + let (Some(place), Some(key)) = (place, field.as_ref().and_then(field_key)) else { + return Ok(false); + }; + terms.push(Term { + column: table.meta.columns.len() + place, + op: BinOp::Eq, + values: vec![key], + one: true, + }); + return Ok(true); + } + (column @ Expr::Column(_), value, op) if known(value, ctx) => { + (column, *op, vec![worked(value)?], true) + } // `5 < id` is `id > 5`. - (value, Expr::Column(column), op) if known(value) => { + (value, column @ Expr::Column(_), op) if known(value, ctx) => { let turned = match op { BinOp::Lt => BinOp::Gt, BinOp::Lte => BinOp::Gte, @@ -197,14 +260,14 @@ pub(super) fn collect( BinOp::Gte => BinOp::Lte, other => *other, }; - (column, turned, vec![value], true) + (column, turned, vec![worked(value)?], true) } _ => return Ok(false), }, Expr::IsNull { expr, negated } => match &**expr { Expr::Column(column) if !negated => { terms.push(Term { - column: column_index(table, column)?, + column: scope.find(column)?.0, op: BinOp::Eq, values: vec![Value::Null], one: false, @@ -216,28 +279,28 @@ pub(super) fn collect( Expr::InList { expr, list, - negated, - } => match &**expr { - Expr::Column(column) if !negated && list.iter().all(known) => { - (column, BinOp::Eq, list.iter().collect(), false) - } - _ => return Ok(false), - }, + negated: false, + } if list.iter().all(|value| known(value, ctx)) => { + let values = list.iter().map(worked).collect::>()?; + (&**expr, BinOp::Eq, values, false) + } + Expr::InSubquery { + expr, + query, + negated: false, + } if ctx.said.is_none() => (&**expr, BinOp::Eq, ctx.subquery(query)?.to_vec(), false), _ => return Ok(false), }; - let column = column_index(table, column)?; - let mut keys = Vec::new(); - for value in values { - match eval(value, &table.scope(), &[], ctx)? { - // A NULL in a list equals nothing. - Value::Null if !one => {} - value => match as_key(table.meta.columns[column].column_type, value) { - Some(value) => keys.push(value), - None => return Ok(false), - }, - } - } - let values = keys; + let Expr::Column(column) = column else { + return Ok(false); + }; + let column = scope.find(column)?.0; + // A NULL in a list equals nothing. + values.retain(|value| one || *value != Value::Null); + let kind = table.meta.columns[column].column_type; + let Some(values) = values.into_iter().map(|key| as_key(kind, key)).collect() else { + return Ok(false); + }; terms.push(Term { column, op, @@ -247,6 +310,35 @@ pub(super) fn collect( Ok(true) } +/// Why a key or index none of whose leading columns `filter` gives a value lost, when a part of +/// it reads `column` in a way no key or index serves. +fn residual(filter: &Expr, column: &str) -> Option<&'static str> { + fn reads(expr: &Expr, column: &str) -> bool { + let mut inner = crate::sql::inside(expr).into_iter(); + matches!(expr, Expr::Column(c) if c.column == column) || inner.any(|e| reads(e, column)) + } + let known = |expr: &Expr| matches!(expr, Expr::Literal(_) | Expr::Parameter(_)); + match filter { + Expr::BinaryOp { left, op, right } if *op == BinOp::And => { + residual(left, column).or_else(|| residual(right, column)) + } + _ if !reads(filter, column) => None, + Expr::Like { .. } => Some("LIKE is residual-only"), + Expr::BinaryOp { op: BinOp::Or, .. } => Some("OR gives no single range"), + Expr::BinaryOp { left, right, .. } => match (&**left, &**right) { + (Expr::FunctionCall { name, .. }, _) | (_, Expr::FunctionCall { name, .. }) => { + Some(match name.starts_with("__") { + true => "arithmetic in predicate", + false => "function call in predicate", + }) + } + (side, other) if known(side) || known(other) => None, + _ => Some("non-literal rhs"), + }, + _ => None, + } +} + /// A row a walk holds back: its key, its values, the cells not taken from it, and the bytes /// its values hold. type Held = (Key, Vec, Vec, u64); @@ -260,10 +352,14 @@ fn held_bytes(key: &Key) -> u64 { /// here, so every one has passed the reader's filter. pub(super) struct Source<'a> { table: &'a Table, + /// The table's columns under the name the statement gives the table. scope: Scope<'a>, filter: Option<&'a Expr>, - params: &'a HashMap, - now: i64, + /// The terms of the filter, gathered once and shared by every path tried. + terms: OnceCell>, + /// What the filter is worked out with beside a row; the caller's, so that it holds + /// whatever the statement worked out before any row. + ctx: &'a EvalContext<'a>, read: &'a dyn Read, /// The reader's filter, which remembers the grants it has looked up; `None` when it reads /// no column of a row, and so hides none. @@ -281,8 +377,7 @@ impl<'a> Source<'a> { pub(super) fn new( table: &'a Table, filter: Option<&'a Expr>, - params: &'a HashMap, - now: i64, + ctx: &'a EvalContext<'a>, read: &'a dyn Read, visible: Visible<'a>, ) -> Source<'a> { @@ -293,8 +388,8 @@ impl<'a> Source<'a> { table, scope: table.scope(), filter, - params, - now, + terms: OnceCell::new(), + ctx, read, visible: seen.contains(&true).then(|| RefCell::new(visible)), seen, @@ -303,6 +398,13 @@ impl<'a> Source<'a> { } } + /// The source whose filter names the table's columns under `qualifier`, the name the + /// statement gives the table, in place of the table's own. + pub(super) fn named(mut self, qualifier: &'a str) -> Source<'a> { + self.scope = Scope::of(qualifier, &self.table.meta.columns); + self + } + /// `filtered` marks the columns the filter reads and `wanted` every column the statement /// reads after it. A column in neither is never taken from a row, so a large value in it /// is never loaded. @@ -330,12 +432,52 @@ impl<'a> Source<'a> { /// Rows are kept under their primary key, so the key is answered from the table itself. Its /// own index, `__pk_`, is declared and has no entries, and is never walked. pub(super) fn choose(&self, order: &[SortKey], assigned: &[usize]) -> Result { - let mut terms = Vec::new(); - if let Some(filter) = self.filter { - let ctx = EvalContext::new(self.params, self.now); - collect(self.table, filter, &ctx, &mut terms)?; + self.given(&[], order, assigned) + } + + /// [`Source::choose`] for the rows whose column at each place of `given` equals the value + /// beside it, as well as passing the filter: a join gives the values of its left row. A + /// value that is no key of its column gives nothing to the path; `None` stands for the + /// value a row will give, when the path is said before any row is read. + pub(super) fn given( + &self, + given: &[(usize, Option<&Value>)], + order: &[SortKey], + assigned: &[usize], + ) -> Result { + Ok(self.scored(given, order, assigned)?.0) + } + + /// The path [`Source::given`] picks, and each key or index tried: first the one the path + /// reads, when one did better than the whole table. + fn scored( + &self, + given: &[(usize, Option<&Value>)], + order: &[SortKey], + assigned: &[usize], + ) -> Result<(Path, Vec)> { + let own = match self.terms.get() { + Some(own) => own, + None => { + let mut own = Vec::new(); + if let Some(filter) = self.filter { + collect(self.table, &self.scope, filter, self.ctx, &mut own)?; + } + self.terms.get_or_init(|| own) + } + }; + let (columns, mut terms) = (&self.table.meta.columns, Vec::new()); + for &(column, value) in given { + let value = value.map_or(Some(Value::Null), |value| { + as_key(columns[column].column_type, value.clone()) + }); + terms.extend(value.map(|value| Term { + column, + op: BinOp::Eq, + values: vec![value], + one: false, + })); } - let columns = &self.table.meta.columns; let column_named = |name: &String| columns.iter().position(|column| column.name == *name); // The order asked for, when it is plain columns. let asked: Option> = order @@ -348,7 +490,7 @@ impl<'a> Source<'a> { Asked::Asc => SortDirection::Asc, Asked::Desc => SortDirection::Desc, }; - Some((column_index(self.table, column).ok()?, direction)) + Some((self.scope.find(column).ok()?.0, direction)) }) .collect(); @@ -361,63 +503,61 @@ impl<'a> Source<'a> { }; let indexes = self.table.meta.indexes.iter().enumerate(); let indexes = indexes - .filter(|(_, index)| !index.name.starts_with("__pk_") && index.json_path.is_empty()) + .filter(|(_, index)| !index.name.starts_with("__pk_")) + .filter(|(_, index)| { + let mut columns = index.columns.iter().map(|(name, _)| column_named(name)); + !columns.any(|at| at.is_some_and(|at| assigned.contains(&at))) + }) .map(|(at, index)| Ordered { index: Some(at), unique: index.name.starts_with("__unique_"), - columns: index - .columns - .iter() - .filter_map(|(name, direction)| Some((column_named(name)?, *direction))) - .collect(), - }) - .filter(|index| { - !index - .columns - .iter() - .any(|column| assigned.contains(&column.0)) + columns: match index.json_path.is_empty() { + true => (index.columns.iter()) + .filter_map(|(name, direction)| Some((column_named(name)?, *direction))) + .collect(), + false => vec![(columns.len() + at, SortDirection::Asc)], + }, }); // Until something better is found: the whole table, in no order that was asked for. let mut best = ( - (0, false, false), + (false, 0, false, false), Path { reach: Reach::Rows(vec![(Bound::Unbounded, Bound::Unbounded)]), one: false, in_order: false, + pinned: 0, order: Vec::new(), }, ); + let mut tried = Vec::new(); // A table that declares no key keeps its rows under numbers no statement names. let the_table = Some(the_table).filter(|_| !self.table.key.is_empty()); for ordered in the_table.into_iter().chain(indexes) { - // The leading columns the filter gives values for. One list at most is taken, so - // the ranges read are no more than the values the statement wrote. - let mut listed = false; + // The leading columns given values. One list at most is taken, and none for a row's + // values, so the ranges read are no more than the values the statement wrote. + let mut listed = !given.is_empty(); let pins: Vec<&Term> = (ordered.columns.iter()) .map_while(|(column, _)| { let equal = |term: &&Term| term.column == *column && term.op == BinOp::Eq; - let term = terms.iter().find(equal)?; + let term = terms.iter().chain(own).find(equal)?; let list = term.values.len() != 1; let taken = !(list && listed); listed |= list; taken.then_some(term) }) .collect(); - let mut tuples = vec![Vec::new()]; - for pin in &pins { - let mut longer = Vec::new(); - for tuple in &tuples { - for value in &pin.values { - longer.push([tuple.as_slice(), std::slice::from_ref(value)].concat()); - } - } - tuples = longer; - } let mut ranges = Vec::new(); let (mut ranged, mut cut) = (false, false); - for tuple in &tuples { - let (entry, range, is_ranged) = ordered.range(self.table, tuple, &terms)?; + // A key for each value of the list taken, if one is, among the single values. + let each = pins + .iter() + .map(|pin| pin.values.len()) + .find(|&len| len != 1); + for at in 0..each.unwrap_or(1) { + let one = |pin: &&Term| pin.values[at.min(pin.values.len() - 1)].clone(); + let tuple: Vec = pins.iter().map(one).collect(); + let (entry, range, is_ranged) = ordered.range(self.table, &tuple, own)?; cut |= entry.cut.is_some(); ranged = is_ranged; ranges.push((entry.key, range)); @@ -449,17 +589,111 @@ impl<'a> Source<'a> { reach, one, in_order, + pinned: pins + .iter() + .filter(|pin| whole_key || pin.values.len() == 1) + .count(), order, }; - if whole_key { - return Ok(path); - } - let score = (pins.len(), ranged, in_order); + // The whole key is better than any index. + let score = (whole_key, pins.len(), ranged, in_order); + let pinned = pins.len(); if score > best.0 { best = (score, path); + tried.insert(0, (ordered, pinned, ranged)); + } else { + tried.push((ordered, pinned, ranged)); + } + } + Ok((best.1, tried)) + } + + /// Says, when the statement is explained, the path [`Source::given`] picks, with `joined` + /// given by a row when that serves better than the filter alone: its key or index (`Scan` + /// when no column is given a value or a range), the columns given, and why each other lost. + pub(super) fn say( + &self, + joined: &[usize], + order: &[SortKey], + assigned: &[usize], + ) -> Result<()> { + let Some(said) = self.ctx.said else { + return Ok(()); + }; + let row: Vec<_> = joined.iter().map(|&column| (column, None)).collect(); + let (path, mut tried) = self.scored(&row, order, assigned)?; + if !path.serves(self.choose(order, assigned)?.pinned) { + tried = self.scored(&[], order, assigned)?.1; + } + let (table, columns) = (self.table, &self.table.meta.columns); + let indexes = &table.meta.indexes; + let name = |index: Option| { + let key = indexes.iter().find(|index| index.name.starts_with("__pk_")); + index + .map_or(key, |at| indexes.get(at)) + .map_or("", |index| &index.name) + }; + // A column only an index over a JSON path has is named by the column it reads. + let column = |at: usize| match columns.get(at) { + Some(column) => column.name.clone(), + None => table.meta.indexes[at - columns.len()].columns[0].0.clone(), + }; + let chosen = tried.first().filter(|tried| tried.1 > 0 || tried.2); + let mut lines = vec![match chosen { + Some((by, ..)) => format!("IndexScan {{ index: {} }}", name(by.index)), + None => "Scan".to_owned(), + }]; + if let Some((by, pinned, ranged)) = chosen { + let pushed = by.columns.iter().take(pinned + usize::from(*ranged)); + let pushed: Vec = pushed.map(|(at, _)| column(*at)).collect(); + lines.push(format!(" predicates_pushed: [{}]", pushed.join(", "))); + } + let pinned = chosen.map_or(0, |chosen| chosen.1); + let whole = chosen.is_some_and(|(by, n, _)| by.index.is_none() && by.columns.len() == *n); + let ranged = chosen.is_some_and(|chosen| chosen.2); + let considered: Vec = (tried[usize::from(chosen.is_some())..].iter()) + .map(|(other, other_pinned, other_ranged)| { + let first = column(other.columns[0].0); + let reason = match *other_pinned { + 0 => (self.filter.and_then(|filter| residual(filter, &first))) + .unwrap_or("first column not in WHERE"), + other_pinned if other_pinned < pinned => { + "fewer predicate columns matched than chosen index" + } + _ if whole || ranged && !other_ranged => "lower selectivity than chosen index", + _ => "tied with chosen index; lost by creation order", + }; + format!("{}: {reason}", name(other.index)) + }) + .collect(); + if !considered.is_empty() { + lines.push(format!(" indexes_considered: [{}]", considered.join(", "))); + } + said.borrow_mut().extend(lines); + Ok(()) + } + + /// Whether the path reaches at most `most` rows, counted by keys or index entries alone and + /// no further than one past `most`. The whole table is never few. + pub(super) fn few(&self, path: &Path, most: u64) -> Result { + let ranges = match &path.reach { + Reach::Keys(keys) => return Ok(keys.len() as u64 <= most), + Reach::Rows(ranges) if ranges[..] == [(Unbounded, Unbounded)] => return Ok(false), + Reach::Rows(ranges) | Reach::Index(_, ranges) => ranges, + }; + let of = match path.reach { + Reach::Index(at, _) => Keys::Index(self.table.index_ids[at]), + _ => Keys::Table(self.table.id), + }; + let mut left = most.saturating_add(1); + for (from, to) in ranges { + let (from, to) = (from.as_ref(), to.as_ref()); + left -= self.read.counted(of, from, to, left as usize)?; + if left == 0 { + break; } } - Ok(best.1) + Ok(left > 0) } /// Reads the rows the path reaches and hands `each` every one the reader may see and the @@ -564,7 +798,7 @@ impl<'a> Source<'a> { break 'ranges; } let Some(row) = self.read.row(table, &key)? else { - continue; + return Err(self.read.damaged("an index entry names no row")); }; examined += 1; let Some((values, cells, bytes)) = self.pass(row, path.one, reservation)? @@ -638,65 +872,6 @@ impl<'a> Source<'a> { Ok(passed.map(|(values, _, bytes)| (values, bytes))) } - /// For each item of a select list, the column whose value it moves out of a row: the column - /// it names, when no other item of the list reads that column. Any other item copies what - /// it reads. Empty for `SELECT *`, which hands the row over as it is. - pub(super) fn moved(&self, columns: Option<&[ProjectColumn]>) -> Result>> { - let columns = columns.unwrap_or_default(); - let mut readers = vec![0; self.table.meta.columns.len()]; - for column in columns { - let mut read = vec![false; readers.len()]; - reads(&column.expr, self.table, self.params, &mut read)?; - for (readers, read) in readers.iter_mut().zip(read) { - *readers += usize::from(read); - } - } - let alone = |column: &ProjectColumn| match &column.expr { - Expr::Column(named) => column_index(self.table, named).ok(), - _ => None, - }; - let moved = columns.iter().map(alone); - Ok(moved.map(|at| at.filter(|at| readers[*at] == 1)).collect()) - } - - /// The select list worked out for one row this source handed over, or the row itself for - /// `SELECT *`. `moved` is [`Source::moved`] of the list, and `distance` is the row's distance - /// when a similarity search found it. The memory of the values is asked for before they - /// are made, and the row's bytes are given back once they are. A value that is moved is - /// held once: what it takes passes from the row to the result and is not asked for again. - pub(super) fn output( - &self, - columns: Option<&[ProjectColumn]>, - moved: &[Option], - mut row: Vec, - bytes: u64, - distance: Option, - reservation: &mut Reservation, - ) -> Result> { - let Some(columns) = columns else { - return Ok(row); - }; - let most = columns - .iter() - .map(|column| most_bytes(&column.expr, &self.scope, &row, self.params)); - let passed = moved.iter().flatten().map(|at| heap_bytes(&row[*at])); - let passed = passed.sum::().min(bytes); - reservation.grow(row_overhead(columns.len()) + most.sum::() - passed)?; - let values = columns - .iter() - .zip(moved) - .map(|(column, moved)| match moved { - Some(at) => Ok(std::mem::replace(&mut row[*at], Value::Null)), - None => { - let ctx = EvalContext::new(self.params, self.now).found(distance); - eval(&column.expr, &self.scope, &row, &ctx) - } - }) - .collect::>>()?; - reservation.shrink(bytes - passed); - Ok(values) - } - /// A stored row the reader may see and the filter passes: its values, the cells not taken /// from it, both in column order, and the bytes of `reservation` the values hold. A row /// that does not pass holds none. A column the statement does not read is left as NULL. @@ -725,8 +900,7 @@ impl<'a> Source<'a> { if passes { self.take(&mut cells, &mut values, &self.filtered, reservation)?; if let Some(filter) = self.filter { - let ctx = EvalContext::new(self.params, self.now); - passes = eval(filter, &self.scope, &values, &ctx)? == Value::Bool(true); + passes = eval(filter, &self.scope, &values, self.ctx)? == Value::Bool(true); } } if !passes { @@ -769,3 +943,33 @@ impl<'a> Source<'a> { /// What a row that passed hands over: its values, the cells not taken from it, and the bytes /// its values hold. type Passed = (Vec, Vec, u64); + +/// What passes exactly the rows that hold `values` in `columns`, side by side, and the +/// parameters it reads them from: each under its column's name. +pub(crate) fn equal( + table: &Table, + columns: &[usize], + values: &[Value], +) -> (Expr, HashMap) { + let mut bound = HashMap::new(); + let each = columns.iter().zip(values).map(|(&at, value)| { + let name = &table.meta.columns[at].name; + bound.insert(name.clone(), value.clone()); + let column = ColumnRef { + table: None, + column: name.clone(), + }; + Expr::BinaryOp { + left: Box::new(Expr::Column(column)), + op: BinOp::Eq, + right: Box::new(Expr::Parameter(name.clone())), + } + }); + let filter = each.reduce(|left, right| Expr::BinaryOp { + left: Box::new(left), + op: BinOp::And, + right: Box::new(right), + }); + let filter = filter.expect("a key and a UNIQUE rule have a column"); + (filter, bound) +} diff --git a/v2/contextdb/src/query/tests.rs b/v2/contextdb/src/query/tests.rs index 307b922ee..19ce02635 100644 --- a/v2/contextdb/src/query/tests.rs +++ b/v2/contextdb/src/query/tests.rs @@ -1,66 +1,9 @@ -//! How two values compare and sort, and arithmetic: the evaluator's pure functions. +//! How two reals compare: the evaluator's pure function. use std::cmp::Ordering; -use super::expression::{Arithmetic, arithmetic, compare, sort_order}; -use crate::types::{Error, Uuid, Value}; - -#[test] -fn arithmetic_keeps_whole_numbers_whole_and_refuses_what_does_not_fit() { - let (int, real) = (Value::Int64, Value::Float64); - let ok = |op, left: &Value, right: &Value| arithmetic(op, left, right).expect("arithmetic"); - assert_eq!(ok(Arithmetic::Div, &int(7), &int(2)), int(3)); - assert_eq!(ok(Arithmetic::Mul, &int(7), &real(0.5)), real(3.5)); - assert_eq!(ok(Arithmetic::Sub, &real(1.5), &int(1)), real(0.5)); - assert_eq!(ok(Arithmetic::Add, &Value::Null, &int(1)), Value::Null); - for (op, left, right) in [ - (Arithmetic::Add, int(i64::MAX), int(1)), - (Arithmetic::Mul, int(i64::MIN), int(-1)), - (Arithmetic::Div, int(7), int(0)), - (Arithmetic::Div, real(7.0), real(0.0)), - (Arithmetic::Add, int(7), Value::Text("x".to_owned())), - ] { - let refused = arithmetic(op, &left, &right); - assert!( - matches!(refused, Err(Error::PlanError(_))), - "{left:?} and {right:?} gave {refused:?}" - ); - } -} - -#[test] -fn values_sort_with_nan_above_every_number_and_null_after_everything() { - let mut values = [ - Value::Null, - Value::Float64(f64::NAN), - Value::Float64(f64::MAX), - Value::Int64(3), - Value::Float64(-1.5), - ]; - values.sort_by(sort_order); - assert_eq!( - values[..3], - [ - Value::Float64(-1.5), - Value::Int64(3), - Value::Float64(f64::MAX) - ] - ); - assert!(matches!(values[3], Value::Float64(nan) if nan.is_nan())); - assert_eq!(values[4], Value::Null); -} - -#[test] -fn a_uuid_compares_with_the_text_that_spells_it() { - let uuid = Value::Uuid(Uuid::from_u128(0x550e_8400_e29b_41d4_a716_4466_5544_0000)); - let spelled = |text: &str| Value::Text(text.to_owned()); - assert_eq!( - compare(&uuid, &spelled("550E8400-E29B-41D4-A716-446655440000")), - Some(Ordering::Equal) - ); - assert_eq!(compare(&spelled("not a uuid"), &uuid), None); - assert_eq!(compare(&uuid, &Value::Int64(1)), None); -} +use super::expression::compare; +use crate::types::Value; #[test] fn a_real_compares_as_a_key_holds_it() { diff --git a/v2/contextdb/src/query/union.rs b/v2/contextdb/src/query/union.rs new file mode 100644 index 000000000..69e320de2 --- /dev/null +++ b/v2/contextdb/src/query/union.rs @@ -0,0 +1,109 @@ +//! UNION ALL and UNION: the rows of one SELECT after another's, each SELECT read in turn. UNION +//! ALL hands each row on and holds nothing; the SELECTs up to the last UNION pass through one +//! table that holds one entry for each different row, as DISTINCT does. + +use super::expression::{Scope, reads}; +use super::join::Parts; +use super::plan::{Cut, Distinct, Each, Given, Source, limits}; +use super::sort::Sort; +use super::subquery::{Pass, Then, Whole}; +use crate::memory::Reservation; +use crate::sql::Expr; +use crate::sql::ast::Literal; +use crate::sql::plan::{ProjectColumn, SelectPlan}; +use crate::types::ColumnType::{Integer, Real}; +use crate::types::{Error, Result}; + +/// Puts the SELECTs of the UNION of `select` one after another, each read `depth` statements +/// deep, under the ORDER BY, LIMIT and OFFSET of `select`, which are over the whole and name its +/// columns, and hands the whole to `then`. Each SELECT gives as many columns as the first, of its +/// types (a whole number and a REAL are one, as are two VECTOR lengths), or a NULL that takes the +/// other's type: refused when the statement is bound, whatever the tables hold. +pub(super) fn after( + select: &SelectPlan, + depth: usize, + given: &Given<'_>, + pass: &mut Pass<'_>, + then: &mut Then<'_, R>, +) -> Result { + let mismatch = || { + let why = "the SELECTs of a UNION give the same number of columns, of types that match"; + Error::PlanError(why.to_owned()) + }; + let meet = |left, right| { + let same = std::mem::discriminant(&left) == std::mem::discriminant(&right); + same || matches!((left, right), (Integer, Real) | (Real, Integer)) + }; + // A column of NULL has no type of its own: the first SELECT that gives another types it. + let null = |list: &[ProjectColumn], at: usize| { + let expr = list.get(at).map(|column| &column.expr); + matches!(expr, Some(Expr::Literal(Literal::Null))) + }; + let mut first = select.clone(); + (first.with, first.union, first.order_by) = (Vec::new(), Vec::new(), Vec::new()); + (first.limit, first.offset, first.limit_name) = (None, None, None); + first.offset_name = None; + let (mut columns, mut typed, mut sources) = (Vec::new(), Vec::new(), Vec::new()); + let arms = select.union.iter().map(|(_, arm)| arm); + for arm in std::iter::once(&first).chain(arms) { + let arm = Whole { + select: arm, + given, + depth, + }; + let theirs = arm.bound()?; + if sources.is_empty() { + (columns, typed) = (theirs.clone(), vec![false; theirs.len()]); + } + if theirs.len() != columns.len() { + return Err(mismatch()); + } + for (at, (column, next)) in columns.iter_mut().zip(&theirs).enumerate() { + if null(&arm.select.columns, at) { + } else if !typed[at] { + (column.column_type, typed[at]) = (next.column_type, true); + } else if !meet(column.column_type, next.column_type) { + return Err(mismatch()); + } + } + sources.push(Box::new(arm) as Box); + } + if let Some(last) = select.union.iter().rposition(|(all, _)| !all) { + let rest = sources.split_off(last + 2); + let input = Box::new(Parts(std::mem::replace(&mut sources, rest))); + sources.insert(0, Box::new(Distinct { input })); + } + let mut scope = Scope::of("", &columns); + scope.checked = true; + let read = &mut vec![false; columns.len()]; + for key in &select.order_by { + let Expr::Column(_) = key.expr else { + let why = "the ORDER BY of a UNION names columns of its result, not expressions"; + return Err(Error::PlanError(why.to_owned())); + }; + reads(&key.expr, &scope, given.params, read)?; + } + let (limit, offset) = limits(select, given.params)?; + let mut input: Box = Box::new(Parts(sources)); + if !select.order_by.is_empty() { + input = Box::new(Sort { + input, + scope, + order: &select.order_by, + ctx: &given.ctx, + most: limit.saturating_add(offset), + }); + } + let cut = Cut { + input, + offset, + limit, + }; + then(&columns, &cut, pass) +} + +impl Source for &S { + fn rows(&self, reservation: &mut Reservation, each: &mut Each<'_>) -> Result { + (**self).rows(reservation, each) + } +} diff --git a/v2/contextdb/src/query/visible.rs b/v2/contextdb/src/query/visible.rs index 2b1751473..ea4ba24aa 100644 --- a/v2/contextdb/src/query/visible.rs +++ b/v2/contextdb/src/query/visible.rs @@ -3,7 +3,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap}; -use super::expression::reads; +use super::expression::{EvalContext, reads}; use super::table::Source; use crate::memory::Reservation; use crate::schema::{Catalog, Table}; @@ -118,7 +118,7 @@ impl<'a> Visible<'a> { // nobody. let grants = catalog.table(from).and_then(|table| { let mut filtered = vec![false; table.meta.columns.len()]; - reads(&filter, table, ¶ms, &mut filtered).ok()?; + reads(&filter, &table.scope(), ¶ms, &mut filtered).ok()?; Some((table, filtered)) }); let grants = match grants { @@ -247,7 +247,8 @@ impl Grants<'_> { reader, acl: None, }; - let source = Source::new(self.table, Some(&self.filter), &self.params, 0, read, seen) + let ctx = EvalContext::new(&self.params, 0); + let source = Source::new(self.table, Some(&self.filter), &ctx, read, seen) .reading(self.filtered.clone(), &self.filtered); let mut path = source.choose(&[], &[])?; // A grant row the reader may not see is no grant, however the lookup names it. diff --git a/v2/contextdb/src/query/window.rs b/v2/contextdb/src/query/window.rs new file mode 100644 index 000000000..38e652e22 --- /dev/null +++ b/v2/contextdb/src/query/window.rs @@ -0,0 +1,171 @@ +//! `ROW_NUMBER() OVER ([PARTITION BY ...] ORDER BY ...)`: the rows of each partition numbered +//! 1, 2, 3 in the window's order. + +use std::cmp::Ordering; + +use super::aggregate::made; +use super::expression::{EvalContext, Scope, eval, most_bytes, sort_order}; +use super::plan::{Each, Source, listed}; +use super::sort::Sort; +use crate::memory::Reservation; +use crate::sql::plan::{ProjectColumn, SelectPlan, SortKey}; +use crate::sql::{Expr, inside_mut}; +use crate::types::{ColumnDef, Error, Result, SortDirection, Value}; + +/// What the column of a row's number is called and qualified with: no table has this name. +const NUMBER: &str = "ROW_NUMBER() OVER"; + +/// The one window of a SELECT, and the statement's ORDER BY and select list written over a +/// numbered row: a row of the input and then its number. +pub(super) struct Window { + /// What the rows are numbered in the order of: the partition's columns, then the window's + /// ORDER BY. + keys: Vec, + /// How many of `keys` name the partition. + partition: usize, + number: [ColumnDef; 1], + order: Vec, + list: Vec, +} + +impl Window { + /// The window of a SELECT that writes `ROW_NUMBER() OVER`; `None` for any other. Two + /// different windows in one SELECT, and a partition or an order that is not a column, are + /// refused by name. + pub(super) fn of(select: &SelectPlan) -> Result> { + let (mut order, mut list) = (select.order_by.clone(), select.columns.clone()); + let mut found = None; + let written = order.iter_mut().map(|key| &mut key.expr); + let mut written = written.chain(list.iter_mut().map(|column| &mut column.expr)); + written.try_for_each(|expr| numbered(expr, &mut found))?; + let Some(Expr::RowNumber { + partition_by, + order_by, + }) = found + else { + return Ok(None); + }; + let partition = partition_by.len(); + let partition_by = partition_by.into_iter().map(|expr| SortKey { + expr, + direction: SortDirection::Asc, + }); + Ok(Some(Window { + keys: partition_by.chain(order_by).collect(), + partition, + number: [made(Some(NUMBER), NUMBER).0], + order, + list, + })) + } + + /// The order the rows are numbered in. An input that arrives in it needs no sort. + pub(super) fn keys(&self) -> &[SortKey] { + &self.keys + } +} + +/// Puts the column of the row's number wherever `expr` writes a window, which becomes `found`. +fn numbered(expr: &mut Expr, found: &mut Option) -> Result<()> { + let Expr::RowNumber { + partition_by, + order_by, + } = expr + else { + let mut inner = inside_mut(expr).into_iter(); + return inner.try_for_each(|inner| numbered(inner, found)); + }; + let refused = |form: &str| { + let form = form.to_owned(); + Err(Error::WindowFunctionNotSupported { form }) + }; + let mut named = partition_by + .iter() + .chain(order_by.iter().map(|key| &key.expr)); + if !named.all(|expr| matches!(expr, Expr::Column(_))) { + return refused("a computed partition or order expression"); + } + let window = std::mem::replace(expr, made(Some(NUMBER), NUMBER).1); + match found { + Some(first) if format!("{first:?}") != format!("{window:?}") => { + refused("several different windows in one SELECT") + } + _ => { + *found = Some(window); + Ok(()) + } + } +} + +/// The rows of a statement with a window: its input, whose columns are `scope`, numbered, then +/// the statement's ORDER BY and its select list over the numbered rows. An input that is not +/// `in_order`, the order of [`Window::keys`], is sorted first, which holds every row of it. +pub(super) struct Numbered<'a> { + pub(super) input: Box, + pub(super) scope: Scope<'a>, + pub(super) window: Window, + pub(super) ctx: &'a EvalContext<'a>, + pub(super) in_order: bool, + /// How many rows can leave, as [`Sort`] has it. + pub(super) most: usize, +} + +impl Source for Numbered<'_> { + fn rows(&self, reservation: &mut Reservation, each: &mut Each<'_>) -> Result { + let (window, ctx) = (&self.window, self.ctx); + let scope = self.scope.clone().and(NUMBER, &window.number); + let rows = Box::new(Numbers(self)); + let written = (window.order.as_slice(), window.list.as_slice()); + listed(rows, scope, written, ctx, self.most).rows(reservation, each) + } +} + +/// The rows of a window's input in the window's order, each with its number after its values. +/// Holds the partition values of the row before, to tell where the next partition begins. +struct Numbers<'s, 'a>(&'s Numbered<'a>); + +impl Source for Numbers<'_, '_> { + fn rows(&self, reservation: &mut Reservation, each: &mut Each<'_>) -> Result { + let Numbered { + input, + scope, + window, + ctx, + in_order, + .. + } = self.0; + let sorted = Sort { + input: Box::new(&**input), + scope: scope.clone(), + order: &window.keys, + ctx, + most: usize::MAX, + }; + let input: &dyn Source = if *in_order { &**input } else { &sorted }; + let partition = &window.keys[..window.partition]; + let cell = size_of::() as u64; + let (mut before, mut held, mut number) = (Vec::new(), 0, 0); + let examined = input.rows(reservation, &mut |mut row, bytes, reservation| { + let most = partition.iter(); + let most = most.map(|key| most_bytes(&key.expr, scope, &row, ctx)); + let most = most.sum::(); + reservation.grow(most + cell)?; + let values = partition + .iter() + .map(|key| eval(&key.expr, scope, &row, ctx)) + .collect::>>()?; + let same = |(left, right)| sort_order(left, right) == Ordering::Equal; + if number > 0 && values.iter().zip(&before).all(same) { + reservation.shrink(most); + number += 1; + } else { + reservation.shrink(held); + (before, held, number) = (values, most, 1); + } + row.push(Value::Int64(number)); + each(row, bytes + cell, reservation) + })?; + reservation.shrink(held); + Ok(examined) + } +} diff --git a/v2/contextdb/src/read/mod.rs b/v2/contextdb/src/read/mod.rs index 8d4462cd1..c40a7f19a 100644 --- a/v2/contextdb/src/read/mod.rs +++ b/v2/contextdb/src/read/mod.rs @@ -10,7 +10,7 @@ use std::sync::{Arc, Mutex, PoisonError}; use crate::memory::Budget; use crate::query::{self, QueryResult}; -use crate::schema::{self, Catalog}; +use crate::schema::Catalog; use crate::sql::{self, Effect, Plan}; use crate::store::{Store, View, WrapStorage}; use crate::system::{self, Clock}; @@ -119,7 +119,7 @@ impl ReadSession { /// - [`crate::Error::StoreIo`] when the folder or its data file cannot be read, and /// [`crate::Error::StoreCorrupted`] when what was read fails its check. pub fn execute(&self, sql: &str, params: &HashMap) -> Result { - let plan = sql::plan(&sql::parse(sql)?)?; + let plan = sql::plan(sql::parse(sql)?)?; if plan.effect() != Effect::Reads { return Err(Error::ReadOnlySession); } @@ -141,11 +141,11 @@ impl ReadSession { /// /// As [`ReadSession::execute`] for a statement that reads. pub fn explain(&self, sql: &str) -> Result { - let plan = sql::plan(&sql::parse(sql)?)?; + let plan = sql::plan(sql::parse(sql)?)?; let now = system::now_millis(&*self.clock); let (view, catalog) = self.newest()?; - let admin = query::Reader::admin(); - query::explain(&plan, &catalog, &view, &admin, &self.budget, now) + let (admin, budget) = (query::Reader::admin(), &self.budget); + query::explain(&plan, &HashMap::new(), &catalog, &view, &admin, budget, now) } /// The names of the store's tables as of the newest commit, in name order. A store with no @@ -157,9 +157,7 @@ impl ReadSession { /// [`crate::Error::StoreIo`] when the folder or its data file cannot be read, and /// [`crate::Error::StoreCorrupted`] when what was read fails its check. pub fn table_names(&self) -> Result> { - let (_, catalog) = self.newest()?; - let tables = catalog.tables().into_iter(); - Ok(tables.map(|table| table.name.clone()).collect()) + Ok(self.newest()?.1.table_names()) } /// A table's declaration as SQL text, as of the newest commit: its `CREATE TABLE` statement, @@ -174,11 +172,7 @@ impl ReadSession { /// - [`crate::Error::StoreIo`] when the folder or its data file cannot be read, and /// [`crate::Error::StoreCorrupted`] when what was read fails its check. pub fn declaration(&self, table: &str) -> Result { - let (_, catalog) = self.newest()?; - match catalog.table(table) { - Some(table) => Ok(schema::render(table)), - None => Err(Error::TableNotFound(table.to_owned())), - } + self.newest()?.1.declaration(table) } /// The newest commit and the tables declared at it. The view holds that commit's pages for diff --git a/v2/contextdb/src/schema/alter.rs b/v2/contextdb/src/schema/alter.rs index a62264c9b..b6e511cb8 100644 --- a/v2/contextdb/src/schema/alter.rs +++ b/v2/contextdb/src/schema/alter.rs @@ -355,8 +355,10 @@ fn altered( column, search_mode, } => clause(column, &|v| v.search_mode = Some(*search_mode)), - AlterAction::SetAutoIndexAt(c, to) => clause(c, &|v| v.auto_index_at.clone_from(to)), - AlterAction::SetConsolidation(c, to) => clause(c, &|v| v.consolidation.clone_from(to)), + AlterAction::SetIndexingThreshold(c, to) => { + clause(c, &|v| v.indexing_threshold.clone_from(to)) + } + AlterAction::SetCompaction(c, to) => clause(c, &|v| v.compaction.clone_from(to)), } } diff --git a/v2/contextdb/src/schema/check.rs b/v2/contextdb/src/schema/check.rs index b2e2506e6..67d8b2cd6 100644 --- a/v2/contextdb/src/schema/check.rs +++ b/v2/contextdb/src/schema/check.rs @@ -1,7 +1,7 @@ //! Checking a declaration: what CREATE TABLE and CREATE INDEX may say, and the table each gives. -use super::{Catalog, Consolidation, Quantization, RESERVED_PREFIXES, Table, VectorColumn, rules}; -use crate::sql::ast::{self, ConsolidationClause, Expr, Literal}; +use super::{Catalog, Compaction, Quantization, RESERVED_PREFIXES, Table, VectorColumn, rules}; +use crate::sql::ast::{self, CompactionClause, Expr, Literal}; use crate::sql::not_carried; use crate::sql::plan::{CreateIndexPlan, CreateTablePlan}; use crate::store::{IndexId, TableId, VectorId}; @@ -176,27 +176,27 @@ fn vector_column( return Err(policy(PolicyIssue::InvalidMember { member })); } }; - let auto_index_at = match &declared.vector.auto_index_at { + let indexing_threshold = match &declared.vector.indexing_threshold { None => None, Some(written) => match written.parse::() { Ok(at) if at > 0 => Some(at), Err(_) if !written.starts_with('-') => { - return Err(policy(PolicyIssue::AutoIndexAtOutOfRange)); + return Err(policy(PolicyIssue::IndexingThresholdOutOfRange)); } - _ => return Err(policy(PolicyIssue::AutoIndexAtNotPositive)), + _ => return Err(policy(PolicyIssue::IndexingThresholdNotPositive)), }, }; let percent = |written: &Option| match written { None => Ok(None), Some(written) => match written.parse::() { Ok(percent @ 1..=100) => Ok(Some(percent)), - _ => Err(policy(PolicyIssue::ConsolidationPercentOutOfRange)), + _ => Err(policy(PolicyIssue::CompactionPercentOutOfRange)), }, }; - let consolidation = match &declared.vector.consolidation { + let compaction = match &declared.vector.compaction { None => None, - Some(ConsolidationClause::None) => Some(Consolidation::None), - Some(ConsolidationClause::Percent { change, tombstone }) => Some(Consolidation::Percent { + Some(CompactionClause::None) => Some(Compaction::None), + Some(CompactionClause::Percent { change, tombstone }) => Some(Compaction::Percent { change: percent(change)?, tombstone: percent(tombstone)?, }), @@ -207,8 +207,8 @@ fn vector_column( partition_key: declared.vector.partition_key.clone(), max_partitions, search_mode: declared.vector.search_mode, - auto_index_at, - consolidation, + indexing_threshold, + compaction, quantization, }) } diff --git a/v2/contextdb/src/schema/mod.rs b/v2/contextdb/src/schema/mod.rs index 9be7b95a8..7f295af4a 100644 --- a/v2/contextdb/src/schema/mod.rs +++ b/v2/contextdb/src/schema/mod.rs @@ -28,8 +28,11 @@ use std::sync::Arc; pub(crate) use self::alter::Declared; pub(crate) use self::rules::{Reference, Rules}; use crate::query::Scope; -use crate::sql::Plan; -use crate::store::{Cell, ChangeSet, EntryShape, IndexId, Read, Row, TableId, VectorId, View}; +use crate::sql::plan::InsertPlan; +use crate::sql::{Expr, Plan}; +use crate::store::{ + Cell, ChangeSet, Entry, EntryShape, IndexId, Read, Row, TableId, VectorId, View, +}; use crate::types::{ ColumnType, Error, IndexDecl, Result, TableMeta, Value, VectorIndexRef, VectorSearchMode, }; @@ -38,6 +41,9 @@ use crate::types::{ /// may not take one of these. const RESERVED_PREFIXES: [&str; 4] = ["__pk_", "__unique_", "__fk_", "__graph_"]; +/// What [`Table::insert`] gives. +pub(crate) type Inserted<'p> = (Vec, Option<(Vec, Vec<(usize, &'p Expr)>)>); + /// One declared table as the other parts use it. The rules a host reads are in `meta`; what /// `schema` works out from the declaration beyond them is in `rules`. #[derive(Clone)] @@ -77,21 +83,21 @@ pub(crate) struct VectorColumn { pub max_partitions: Option, /// SEARCH_MODE as declared; `None` when the declaration names none. pub search_mode: Option, - /// AUTO_INDEX_AT as declared; `None` when the declaration names none. - pub auto_index_at: Option, - /// CONSOLIDATION as declared; `None` when the declaration names none. - pub consolidation: Option, + /// INDEXING_THRESHOLD as declared; `None` when the declaration names none. + pub indexing_threshold: Option, + /// COMPACTION as declared; `None` when the declaration names none. + pub compaction: Option, /// How the column keeps a vector: what `WITH (quantization = ...)` declared. pub quantization: Quantization, } -/// What `CONSOLIDATION` declares: when the vectors written since a partition was grouped, and +/// What `COMPACTION` declares: when the vectors written since a partition was grouped, and /// the slots its rows have left behind, call for grouping it again. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum Consolidation { - /// `CONSOLIDATION NONE`: never for those reasons. +pub(crate) enum Compaction { + /// `COMPACTION NONE`: never for those reasons. None, - /// `CONSOLIDATION (CHANGE_PERCENT = n, TOMBSTONE_PERCENT = n)`; a member that was not + /// `COMPACTION (CHANGE_PERCENT = n, TOMBSTONE_PERCENT = n)`; a member that was not /// written is `None` and takes its default. Percent { change: Option, @@ -109,15 +115,15 @@ pub(crate) enum Quantization { Sq8, } -/// AUTO_INDEX_AT of a column that declares none: a comparison of every vector of this many +/// INDEXING_THRESHOLD of a column that declares none: a comparison of every vector of this many /// takes about a hundredth of a second on one core, and past it the groupings are worth using. const DEFAULT_INDEX_AT: u64 = 100_000; -/// A partition is given its first grouping when it holds this share of AUTO_INDEX_AT: one in +/// A partition is given its first grouping when it holds this share of INDEXING_THRESHOLD: one in /// a hundred, so that the groupings of a store spread over many partitions are in place before /// AUTO begins to use them. const GROUPED_SHARE: u64 = 100; /// CHANGE_PERCENT and TOMBSTONE_PERCENT of a column that declares none. -const DEFAULT_CONSOLIDATION: (u8, u8) = (20, 10); +const DEFAULT_COMPACTION: (u8, u8) = (20, 10); impl VectorColumn { /// The most partitions the column may have: what was declared, 256 when a PARTITION_KEY @@ -133,26 +139,26 @@ impl VectorColumn { self.search_mode.unwrap_or_default() } - /// AUTO_INDEX_AT in force: what was declared, else 100,000. The count of vectors in the + /// INDEXING_THRESHOLD in force: what was declared, else 100,000. The count of vectors in the /// selected partitions together from which AUTO uses their groupings. pub(crate) fn index_at(&self) -> u64 { - self.auto_index_at.unwrap_or(DEFAULT_INDEX_AT) + self.indexing_threshold.unwrap_or(DEFAULT_INDEX_AT) } /// How many slots a partition's tail holds when its first grouping is due: a hundredth of - /// AUTO_INDEX_AT in force and one at least, so 1,000 where nothing is declared. + /// INDEXING_THRESHOLD in force and one at least, so 1,000 where nothing is declared. pub(crate) fn grouped_from(&self) -> u64 { (self.index_at() / GROUPED_SHARE).max(1) } /// CHANGE_PERCENT and TOMBSTONE_PERCENT in force, 20 and 10 where none was declared; - /// `None` under `CONSOLIDATION NONE`. - pub(crate) fn consolidation(&self) -> Option<(u8, u8)> { - let (change, tombstone) = DEFAULT_CONSOLIDATION; - match self.consolidation { + /// `None` under `COMPACTION NONE`. + pub(crate) fn compaction(&self) -> Option<(u8, u8)> { + let (change, tombstone) = DEFAULT_COMPACTION; + match self.compaction { None => Some((change, tombstone)), - Some(Consolidation::None) => None, - Some(Consolidation::Percent { + Some(Compaction::None) => None, + Some(Compaction::Percent { change: c, tombstone: t, }) => Some((c.unwrap_or(change), t.unwrap_or(tombstone))), @@ -166,6 +172,70 @@ impl Table { Scope::of(&self.name, &self.meta.columns) } + /// Where the column a statement or an index names is in a row of the table. + pub(crate) fn column(&self, name: &str) -> Result { + rules::position(&self.name, &self.meta, name) + } + + /// Where each column a statement writes is in a row; one named twice is refused. + pub(crate) fn targets<'n>(&self, of: impl Iterator) -> Result> { + let mut targets = Vec::new(); + for name in of { + let at = self.column(name)?; + if targets.contains(&at) { + let table = &self.name; + let refusal = format!("{name} is named twice as a column {table} is written in"); + return Err(Error::PlanError(refusal)); + } + targets.push(at); + } + Ok(targets) + } + + /// Where each assigned column is in a row, with its new value. + pub(crate) fn set<'e>(&self, set: &'e [(String, Expr)]) -> Result> { + let at = self.targets(set.iter().map(|(name, _)| name))?; + let values = set.iter().map(|(_, value)| value); + Ok(at.into_iter().zip(values).collect()) + } + + /// Checks an INSERT's columns, its `ON CONFLICT` and the length of each row of VALUES. Gives + /// where each column is, and the columns of `ON CONFLICT` with where each assignment writes. + pub(crate) fn insert<'p>(&self, plan: &'p InsertPlan) -> Result> { + let named = match plan.columns.is_empty() { + true => (0..self.meta.columns.len()).collect(), + false => self.targets(plan.columns.iter())?, + }; + let conflict = match &plan.on_conflict { + Some(conflict) => { + let on = conflict.columns.iter().map(|name| self.column(name)); + let mut on: Vec = on.collect::>()?; + on.sort_unstable(); + let is_on = |index: &IndexDecl| { + let at = index.columns.iter().map(|(name, _)| self.column(name).ok()); + let mut at: Vec<_> = at.collect::>().unwrap_or_default(); + at.sort_unstable(); + rules::is_rule(index) && at == on + }; + if !self.meta.indexes.iter().any(is_on) { + return Err(Error::PlanError(format!( + "ON CONFLICT ({}) names neither the primary key nor a UNIQUE rule of {}", + conflict.columns.join(", "), + self.name + ))); + } + Some((on, self.set(&conflict.assignments)?)) + } + None => None, + }; + let (table, columns) = (&self.name, named.len()); + if let Some(given) = plan.values.iter().map(Vec::len).find(|&n| n != columns) { + let refusal = format!("INSERT INTO {table} gives {given} values for {columns} columns"); + return Err(Error::PlanError(refusal)); + } + Ok((named, conflict)) + } + /// The cell a stored row holds for a column. A row written before the column was added has /// none, and reads as the table says such a row does. pub(crate) fn cell<'a>(&self, row: &'a Row, column: usize) -> Cow<'a, Cell> { @@ -180,6 +250,19 @@ impl Table { &self.shapes[index] } + /// The entry, in the index at this place in `meta.indexes`, of a row holding `values` in its + /// columns. One over a JSON path has none for a row with no [`field_key`] at the path. + pub(crate) fn entry(&self, index: usize, values: &[Value]) -> Result> { + let path = &self.meta.indexes[index].json_path; + let field = match (path.is_empty(), values) { + (true, _) => return self.shapes[index].entry(values).map(Some), + (false, [Value::Json(json)]) => path.iter().try_fold(json, |json, key| json.get(key)), + (false, _) => None, + }; + let key = field.and_then(field_key); + key.map(|key| self.shapes[index].entry(&[key])).transpose() + } + /// The table with the shape of each of its indexes, made once here: every table of a /// catalog has been through this. fn shaped(mut self) -> Table { @@ -225,6 +308,17 @@ impl Table { } } +/// What an index over a JSON path keeps for the field there: its text as JSON writes it, a +/// number as its REAL value (adding zero makes `-0` into `0`), so that fields `=` finds equal +/// keep one text; nothing for an object or an array. +pub(crate) fn field_key(field: &serde_json::Value) -> Option { + Some(Value::Text(match field { + serde_json::Value::Object(_) | serde_json::Value::Array(_) => return None, + serde_json::Value::Number(number) => (number.as_f64()? + 0.0).to_string(), + scalar => scalar.to_string(), + })) +} + /// Every table declared in a store at one moment. pub(crate) struct Catalog { tables: BTreeMap, @@ -272,6 +366,17 @@ impl Catalog { self.tables.values().collect() } + /// The name of every table, in name order. + pub(crate) fn table_names(&self) -> Vec { + self.tables.keys().cloned().collect() + } + + /// A table's declaration as `.schema` prints it, or `TableNotFound`. + pub(crate) fn declaration(&self, name: &str) -> Result { + let table = self.table(name).map(render); + table.ok_or_else(|| Error::TableNotFound(name.to_owned())) + } + /// The table that has the VECTOR column with this number, and what it keeps about it. pub(crate) fn vector(&self, id: VectorId) -> Option<(&Table, &VectorColumn)> { self.tables.values().find_map(|table| { @@ -328,6 +433,6 @@ pub(crate) fn declare( } /// The declaration as `.schema` prints it: text that, run again, declares the same table. -pub(crate) fn render(table: &Table) -> String { +fn render(table: &Table) -> String { render::declaration(table) } diff --git a/v2/contextdb/src/schema/record.rs b/v2/contextdb/src/schema/record.rs index b12809670..cd5b94626 100644 --- a/v2/contextdb/src/schema/record.rs +++ b/v2/contextdb/src/schema/record.rs @@ -11,7 +11,7 @@ //! number that is no column and bytes left over are all damage. use super::rules::{Count, RankPolicy, Reference}; -use super::{Consolidation, Quantization, Rules, Table, VectorColumn}; +use super::{Compaction, Quantization, Rules, Table, VectorColumn}; use crate::sql::ast; use crate::store::{CountId, IndexId, Read, TableId, VectorId, View}; use crate::types::{ @@ -205,7 +205,7 @@ fields! { ColumnDef { name, column_type, nullable, primary_key, unique, default } IndexDecl { name, columns, json_path } VectorColumn { - id, column, partition_key, max_partitions, search_mode, auto_index_at, consolidation, + id, column, partition_key, max_partitions, search_mode, indexing_threshold, compaction, quantization } StateMachine { column, transitions } @@ -334,18 +334,18 @@ impl Stored for Value { } } -impl Stored for Consolidation { +impl Stored for Compaction { fn put(&self, out: &mut Vec) { match *self { - Consolidation::None => out.push(0), - Consolidation::Percent { change, tombstone } => (1u8, change, tombstone).put(out), + Compaction::None => out.push(0), + Compaction::Percent { change, tombstone } => (1u8, change, tombstone).put(out), } } fn get(read: &mut Reader) -> Option { match u8::get(read)? { - 0 => Some(Consolidation::None), - 1 => Some(Consolidation::Percent { + 0 => Some(Compaction::None), + 1 => Some(Compaction::Percent { change: Stored::get(read)?, tombstone: Stored::get(read)?, }), diff --git a/v2/contextdb/src/schema/render.rs b/v2/contextdb/src/schema/render.rs index 8ecf53ffa..77f967739 100644 --- a/v2/contextdb/src/schema/render.rs +++ b/v2/contextdb/src/schema/render.rs @@ -1,6 +1,6 @@ //! Printing a declaration back as SQL. -use super::{Consolidation, Quantization, RESERVED_PREFIXES, Table}; +use super::{Compaction, Quantization, RESERVED_PREFIXES, Table}; use crate::sql::ast::{EdgeDiscard, Propagation}; use crate::types::{ ColumnDefault, ConflictPolicy, History, KeptCounts, RetainUnit, SortDirection, SyncDirection, @@ -162,19 +162,19 @@ fn column(table: &Table, at: usize) -> String { Some(VectorSearchMode::Exact) => " SEARCH_MODE EXACT", Some(VectorSearchMode::Indexed) => " SEARCH_MODE INDEXED", }); - if let Some(at) = vector.auto_index_at { - text.push_str(&format!(" AUTO_INDEX_AT {at}")); + if let Some(at) = vector.indexing_threshold { + text.push_str(&format!(" INDEXING_THRESHOLD {at}")); } - match vector.consolidation { + match vector.compaction { None => {} - Some(Consolidation::None) => text.push_str(" CONSOLIDATION NONE"), - Some(Consolidation::Percent { change, tombstone }) => { + Some(Compaction::None) => text.push_str(" COMPACTION NONE"), + Some(Compaction::Percent { change, tombstone }) => { let members = [("CHANGE_PERCENT", change), ("TOMBSTONE_PERCENT", tombstone)]; let written = members.iter().filter_map(|(member, percent)| { percent.map(|percent| format!("{member} = {percent}")) }); let written: Vec = written.collect(); - text.push_str(&format!(" CONSOLIDATION ({})", written.join(", "))); + text.push_str(&format!(" COMPACTION ({})", written.join(", "))); } } } diff --git a/v2/contextdb/src/schema/rules.rs b/v2/contextdb/src/schema/rules.rs index bbbce1181..47ee44a9e 100644 --- a/v2/contextdb/src/schema/rules.rs +++ b/v2/contextdb/src/schema/rules.rs @@ -73,7 +73,7 @@ pub(super) fn position(table: &str, meta: &TableMeta, name: &str) -> Result bool { +pub(super) fn is_rule(index: &crate::types::IndexDecl) -> bool { index.name.starts_with("__pk_") || index.name.starts_with("__unique_") } @@ -92,12 +92,17 @@ pub(super) fn of( Some(SyncDirection::Off | SyncDirection::PullOnly) ); let current = meta.history == Some(History::CurrentOnly); + let state = meta.state_machine.as_ref().map(|machine| &machine.column); + let mut fixed = create.columns.iter().filter(|c| c.immutable); let refused = if meta.immutable && current { "IMMUTABLE with HISTORY CURRENT ONLY: an IMMUTABLE table has no older version to drop, \ so leave one of the two out" } else if meta.immutable && meta.retain.is_some() { "IMMUTABLE with RETAIN: an IMMUTABLE table has no row to expire, so leave one of the two \ out" + } else if state.is_some() && (meta.immutable || fixed.any(|c| Some(&c.name) == state)) { + "a STATE MACHINE over a state that is IMMUTABLE: a state that is never changed has no \ + next state, so leave one of the two out" } else if current && delivers && meta.conflict != Some(ConflictPolicy::KeepLatest) { "HISTORY CURRENT ONLY on a table that sends its rows out and keeps the first write: \ another machine would take a newest value as the first, so write SYNC CONFLICT KEEP \ diff --git a/v2/contextdb/src/schema/tests.rs b/v2/contextdb/src/schema/tests.rs index f2f87c44d..6dc8109a1 100644 --- a/v2/contextdb/src/schema/tests.rs +++ b/v2/contextdb/src/schema/tests.rs @@ -208,22 +208,22 @@ fn a_schema_record_with_one_byte_changed_is_a_whole_table_or_damage_and_never_a_ #[test] fn the_index_clauses_of_a_vector_column_give_the_numbers_in_force() { - use super::{Consolidation, Quantization, VectorColumn}; + use super::{Compaction, Quantization, VectorColumn}; use crate::store::VectorId; - let column = |id, auto_index_at, consolidation, quantization| VectorColumn { + let column = |id, indexing_threshold, compaction, quantization| VectorColumn { id: VectorId(id), column: format!("v{id}"), partition_key: Vec::new(), max_partitions: None, search_mode: None, - auto_index_at, - consolidation, + indexing_threshold, + compaction, quantization, }; - let percent = |change, tombstone| Some(Consolidation::Percent { change, tombstone }); + let percent = |change, tombstone| Some(Compaction::Percent { change, tombstone }); let vectors = [ column(0, None, None, Quantization::F32), - column(1, Some(1000), Some(Consolidation::None), Quantization::Sq8), + column(1, Some(1000), Some(Compaction::None), Quantization::Sq8), column( 2, Some(u64::MAX), @@ -241,7 +241,7 @@ fn the_index_clauses_of_a_vector_column_give_the_numbers_in_force() { ( vector.index_at(), vector.grouped_from(), - vector.consolidation(), + vector.compaction(), ) }) .collect(); @@ -264,7 +264,7 @@ fn dropping_a_vector_column_leaves_no_record_of_any_kind_for_it() { let folder = folder("drop-vector-records"); declare( &folder, - &["CREATE TABLE t (id INTEGER PRIMARY KEY, v VECTOR(4) AUTO_INDEX_AT 1000)"], + &["CREATE TABLE t (id INTEGER PRIMARY KEY, v VECTOR(4) INDEXING_THRESHOLD 1000)"], ); let id = table(&folder, "t").vectors[0].id; // One record of every kind the vector part keeps for the column, as sealing and building diff --git a/v2/contextdb/src/sql/ast.rs b/v2/contextdb/src/sql/ast.rs index 6ae0bcda5..a8a674311 100644 --- a/v2/contextdb/src/sql/ast.rs +++ b/v2/contextdb/src/sql/ast.rs @@ -1,5 +1,7 @@ //! A statement as it was written: what `parse` returns and `plan` reads. +use std::sync::OnceLock; + pub use crate::types::{ ColumnType as DataType, ConflictPolicy, History, KeptCounts, Retain, RetainUnit, SortDirection, StateMachine, SyncDirection, VectorSearchMode, @@ -19,6 +21,8 @@ pub enum Statement { SetMemoryLimit(SetMemoryLimitValue), ShowMemoryLimit, ShowVectorIndexes, + /// `EXPLAIN `: the statement's path, as rows, without running it. + Explain(Box), ShowVectorPartitions { /// The table and column after `FOR`. column: Option<(String, String)>, @@ -34,33 +38,137 @@ pub enum SetMemoryLimitValue { None, } -#[derive(Debug, Clone)] +/// One SELECT as it was written. ORDER BY and what follows it are over the whole statement: +/// over every SELECT of `union` when there is one. +#[derive(Debug, Clone, Default, PartialEq)] pub struct Select { + /// The SELECTs named by WITH, in written order. + pub with: Vec<(String, Select)>, + pub distinct: bool, /// `SELECT *` is one column named `*`. pub columns: Vec, - pub table: String, - pub where_clause: Option, - /// The ORDER BY items. A similarity search has one, a distance ([`Expr::Distance`]) or the - /// name the select list gives one. + /// Empty for a SELECT without FROM. + pub from: Vec, + pub joins: Vec, + pub filter: Option, + pub group_by: Vec, + pub having: Option, + /// The SELECTs after this one, in written order; true for UNION ALL. + pub union: Vec<(bool, Select)>, + /// A bare name the select list gives an item stands here as that item's expression. pub order_by: Vec, /// `USE VECTOR AUTO | EXACT | INDEXED`, when it was written. pub use_vector: Option, + /// The key after `USE RANK`. + pub use_rank: Option, pub limit: Option, + pub offset: Option, + /// The `$name` written where the count of LIMIT stands, and of OFFSET. + pub limit_name: Option, + pub offset_name: Option, + /// Where its text begins in the statement: what a SELECT inside an expression is found by. + pub at: Note, + /// The type of its one column, kept from the first time a SELECT inside an expression is + /// framed. + pub gives: Note>, } -#[derive(Debug, Clone)] +/// What is kept on a statement but is no part of what it says: printed as nothing, so the same +/// expression written twice prints alike. +#[derive(Clone, Default, PartialEq)] +pub struct Note(pub T); + +impl std::fmt::Debug for Note { + fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + Ok(()) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub enum FromItem { + Table { name: String, alias: Option }, + Graph(GraphTable), +} + +/// `GRAPH_TABLE(...)`: the rows a pattern matches over an edge table. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct GraphTable { + pub edge_table: String, + pub start: NodePattern, + pub steps: Vec, + pub filter: Option, + pub columns: Vec, + /// What COLUMNS calls each of its columns and the type of each, kept from the first time + /// the pattern is bound: the statement's text settles both. + pub output: Note>>, +} + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct NodePattern { + pub alias: Option, +} + +/// One edge of a pattern and the node it leads to, followed at least `min` and at most `max` +/// times; `max` is never above 10. +#[derive(Debug, Clone, PartialEq)] +pub struct EdgeStep { + pub direction: EdgeDirection, + pub edge_type: Option, + pub min: u32, + pub max: u32, + pub to: NodePattern, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EdgeDirection { + Outgoing, + Incoming, + Both, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Join { + /// LEFT JOIN: a row of the left side with no partner is kept. + pub left_outer: bool, + pub item: FromItem, + /// `None` for CROSS JOIN. + pub on: Option, +} + +#[derive(Debug, Clone, PartialEq)] pub struct SelectColumn { pub expr: Expr, pub alias: Option, } -#[derive(Debug, Clone)] +impl SelectColumn { + /// What a result calls the column: its alias; without one a column's own name, a function's + /// name in lower case, `row_number`, the name a one-column SELECT gives, else `?column?`. + pub fn name(&self) -> String { + match (&self.alias, &self.expr) { + (Some(alias), _) => alias.clone(), + (None, Expr::Column(column)) => column.column.clone(), + // The four operators arrive as calls whose names begin `__`. + (None, Expr::FunctionCall { name, .. }) if !name.starts_with("__") => { + name.to_lowercase() + } + (None, Expr::RowNumber { .. }) => "row_number".to_owned(), + (None, Expr::Subquery(query)) => match query.columns.as_slice() { + [item] if item.name() != "*" => item.name(), + _ => "?column?".to_owned(), + }, + _ => "?column?".to_owned(), + } + } +} + +#[derive(Debug, Clone, PartialEq)] pub struct OrderByItem { pub expr: Expr, pub direction: SortDirection, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, PartialEq)] pub enum Expr { Column(ColumnRef), Literal(Literal), @@ -104,6 +212,49 @@ pub enum Expr { list: Vec, negated: bool, }, + /// `expr [NOT] IN (SELECT ...)`. + InSubquery { + expr: Box, + query: Box), + /// `expr [NOT] LIKE pattern`. + Like { + expr: Box, + pattern: Box, + negated: bool, + }, + /// `expr [NOT] BETWEEN low AND high`. + Between { + expr: Box, + low: Box, + high: Box, + negated: bool, + }, + /// `json -> key` and, with `as_text`, `json ->> key`. Both bind as `<=>` does. + Field { + json: Box, + key: Box, + as_text: bool, + }, + /// `ROW_NUMBER() OVER ([PARTITION BY ...] ORDER BY ...)`. The parser refuses every other + /// function before `OVER`, and a window with no ORDER BY. + RowNumber { + partition_by: Vec, + order_by: Vec, + }, +} + +impl Expr { + /// The expressions of one side of `=` or IN: those of a row value, or the one expression. + pub(crate) fn sides(&self) -> &[Expr] { + match self { + Expr::Row(items) => items, + one => std::slice::from_ref(one), + } + } } #[derive(Debug, Clone, PartialEq, Eq)] @@ -112,7 +263,7 @@ pub struct ColumnRef { pub column: String, } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, PartialEq)] pub enum Literal { Null, Bool(bool), @@ -285,20 +436,20 @@ pub struct VectorClauses { pub max_partitions: Option, /// `SEARCH_MODE AUTO | EXACT | INDEXED`, when it was written. pub search_mode: Option, - /// The number after `AUTO_INDEX_AT`, kept as written for `schema` to judge. - pub auto_index_at: Option, - /// `CONSOLIDATION NONE` or `CONSOLIDATION (...)`, when it was written. - pub consolidation: Option, + /// The number after `INDEXING_THRESHOLD`, kept as written for `schema` to judge. + pub indexing_threshold: Option, + /// `COMPACTION NONE` or `COMPACTION (...)`, when it was written. + pub compaction: Option, /// The text of `WITH (quantization = '...')`, kept as written for `schema` to judge. pub quantization: Option, } -/// `CONSOLIDATION` as it was written. +/// `COMPACTION` as it was written. #[derive(Debug, Clone, PartialEq, Eq)] -pub enum ConsolidationClause { - /// `CONSOLIDATION NONE`. +pub enum CompactionClause { + /// `COMPACTION NONE`. None, - /// `CONSOLIDATION (CHANGE_PERCENT = n, TOMBSTONE_PERCENT = n)`: each number as written, + /// `COMPACTION (CHANGE_PERCENT = n, TOMBSTONE_PERCENT = n)`: each number as written, /// `None` for a member that was not. Percent { change: Option, @@ -353,10 +504,10 @@ pub enum AlterAction { column: String, search_mode: VectorSearchMode, }, - /// `ALTER COLUMN column SET AUTO_INDEX_AT n`, the number kept as written; `None` is DEFAULT. - SetAutoIndexAt(String, Option), - /// `ALTER COLUMN column SET CONSOLIDATION ...`; `None` is DEFAULT. - SetConsolidation(String, Option), + /// `ALTER COLUMN column SET INDEXING_THRESHOLD n`, the number kept as written; `None` is DEFAULT. + SetIndexingThreshold(String, Option), + /// `ALTER COLUMN column SET COMPACTION ...`; `None` is DEFAULT. + SetCompaction(String, Option), } #[derive(Debug, Clone)] diff --git a/v2/contextdb/src/sql/grammar.pest b/v2/contextdb/src/sql/grammar.pest index c84de52fa..7d712733f 100644 --- a/v2/contextdb/src/sql/grammar.pest +++ b/v2/contextdb/src/sql/grammar.pest @@ -18,32 +18,39 @@ stmt = _{ | show_memory_limit | show_vector_indexes | show_vector_partitions + | explain_stmt | select_stmt - | later + | !with_word ~ later } // A statement or clause that a later version of the library reads, or that no version reads // (IVF and SEARCH). It is recognised by its first words alone and the rest of the text is left // unread, so that the statement is refused by that name and not as a syntax error. `later` // stands only where nothing this version reads can begin with one of these words: after a whole -// statement or clause, and after an expression, where LIKE and BETWEEN would follow. DISTINCT and -// GRAPH_TABLE stand where a name could, so they are looked for first. +// statement or clause, and after an expression, where ILIKE and the two other distances would +// follow. A statement that begins with WITH is a SELECT. later = { later_name ~ ANY* } later_name = @{ ( - ^"DROP" ~ SPACE+ ~ (^"TRIGGER" | ^"ROUTE" | ^"SCHEDULE") | ^"WITH" | ^"BEGIN" | ^"COMMIT" | ^"ROLLBACK" | ^"PURGE" | ^"DISCARD" - | ^"DECLARE" | ^"DISTINCT" | ^"GRAPH_TABLE" - | ((^"LEFT" | ^"INNER" | ^"CROSS") ~ SPACE+)? ~ ^"JOIN" - | ^"GROUP" ~ SPACE+ ~ ^"BY" | ^"HAVING" | ^"UNION" | ^"OFFSET" - | ^"USE" ~ SPACE+ ~ ^"RANK" - | (^"NOT" ~ SPACE+)? ~ (^"LIKE" | ^"BETWEEN") + ^"SHOW" ~ SPACE+ + ~ (^"TENANT" | ^"SYNC_CONFLICT_POLICY" | ^"SYNC" | ^"DELIVERY" | ^"DISK_LIMIT") + | ^"SET" ~ SPACE+ + ~ (^"DISK_LIMIT" | ^"MAINTENANCE_POLL_INTERVAL" | ^"READ_CACHE_SHARE" | ^"STORAGE_COMPACTION") + | ^"CREATE" ~ SPACE+ ~ (^"TRIGGER" | ^"EVENT" | ^"SINK" | ^"ROUTE" | ^"SCHEDULE") + | ^"FOLLOWS" + | ^"DROP" ~ SPACE+ ~ (^"TRIGGER" | ^"ROUTE" | ^"SCHEDULE") | ^"WITH" | ^"BEGIN" | ^"COMMIT" | ^"ROLLBACK" | ^"PURGE" | ^"DISCARD" + | ^"DECLARE" + | (^"NOT" ~ SPACE+)? ~ ^"ILIKE" | ^"EXPIRES" | ^"SEARCH" | ^"IVF" ) ~ !ident_char + | "<->" | "<#>" } -// Two forms of a later version that begin with words this version reads, so each is known by -// where it stands: a SELECT as the list of IN, and the options after the mode of USE VECTOR. -// Like `later`, each leaves the rest of the text unread. +// The word a SELECT in parentheses opens with. It is looked ahead for, so that what stands in +// parentheses is read once: as a SELECT or as expressions. subquery = @{ ^"SELECT" ~ !ident_char } +// The options after the mode of USE VECTOR are a later version's and begin with a mark this +// version reads, so they are known by where they stand. Like `later`, the rule leaves the rest +// of the text unread. vector_options = { "(" } set_memory_limit = { ^"SET" ~ ^"MEMORY_LIMIT" ~ "="? ~ ("'" ~ memory_limit_value ~ "'" | memory_limit_value) } @@ -52,34 +59,81 @@ memory_limit_value = { ^"none" | size_with_unit } size_with_unit = @{ ASCII_DIGIT+ ~ ("G" | "M" | "K") } show_vector_indexes = { ^"SHOW" ~ ^"VECTOR_INDEXES" } +explain_stmt = { ^"EXPLAIN" ~ stmt } show_vector_partitions = { ^"SHOW" ~ ^"VECTOR_PARTITIONS" ~ (^"FOR" ~ identifier ~ "." ~ identifier)? ~ (limit_clause ~ offset_clause?)? } -offset_clause = { ^"OFFSET" ~ integer } +// ORDER BY and what follows it are over the whole statement: over every SELECT of a UNION. select_stmt = { - ^"SELECT" - ~ ( - &^"DISTINCT" ~ later - | select_list ~ ^"FROM" - ~ ( - &(^"GRAPH_TABLE" ~ "(") ~ later - | identifier ~ where_clause? ~ order_by_clause? ~ use_vector_clause? ~ limit_clause? - ~ later? - ) - ) + with_clause? ~ select_core ~ (set_op ~ all? ~ select_core)* + ~ order_by_clause? ~ use_vector_clause? ~ use_rank_clause? ~ limit_clause? ~ offset_clause? + ~ later? +} +with_clause = { with_word ~ recursive? ~ cte ~ ("," ~ cte)* } +with_word = @{ ^"WITH" ~ !ident_char } +// WITH RECURSIVE, which no version has: it is read so that it is refused by its own kind. +recursive = @{ ^"RECURSIVE" ~ !ident_char } +cte = { identifier ~ ^"AS" ~ "(" ~ select_stmt ~ ")" } +// INTERSECT and EXCEPT, RIGHT and FULL JOIN and a second table after a comma are no version's: +// each is read so that it is refused by its name. +set_op = @{ (^"UNION" | ^"INTERSECT" | ^"EXCEPT") ~ !ident_char } +all = @{ ^"ALL" ~ !ident_char } +select_core = { + ^"SELECT" ~ distinct? ~ select_list + ~ (^"FROM" ~ (graph_table | table_ref ~ more_tables? ~ join*))? + ~ where_clause? ~ group_by_clause? ~ having_clause? +} +distinct = @{ ^"DISTINCT" ~ !ident_char } +table_ref = { identifier ~ alias? } +// The rows a pattern matches over an edge table, which stands alone in FROM. A step with no +// count is one hop; `+`, `*` and a count with no upper bound are read so that each is refused +// by its own name. +graph_table = { + ^"GRAPH_TABLE" ~ "(" ~ identifier ~ ^"MATCH" ~ node_pattern ~ edge_step+ + ~ where_clause? ~ graph_columns? ~ ")" +} +node_pattern = { "(" ~ identifier? ~ label? ~ ")" } +label = { ":" ~ as_written } +edge_step = { (incoming ~ edge ~ "-" | "-" ~ edge ~ outgoing | "-" ~ edge ~ "-") ~ hops? ~ node_pattern } +incoming = { "<-" } +outgoing = { "->" } +edge = { "[" ~ identifier? ~ label? ~ "]" } +hops = { "+" | "*" | "{" ~ integer ~ "," ~ integer? ~ "}" } +graph_columns = { ^"COLUMNS" ~ "(" ~ select_item ~ ("," ~ select_item)* ~ ")" } +more_tables = { "," ~ ANY* } +join = { cross ~ table_ref | join_kind ~ table_ref ~ ^"ON" ~ expr } +cross = { ^"CROSS" ~ join_word } +join_kind = { (^"INNER" | ^"LEFT" | ^"RIGHT" | ^"FULL")? ~ join_word } +join_word = @{ ^"JOIN" ~ !ident_char } +// A name given with AS, or without it when the word begins no clause. +alias = ${ as_alias | !clause_word ~ identifier } +// Without AS, the name of a select item is a name only before what may follow an item, so that +// a misspelt FROM is the word a syntax error stops at. +item_alias = ${ as_alias | !clause_word ~ identifier ~ &(WHITESPACE* ~ ("," | ")" | ";" | !ANY | clause_word)) } +as_alias = _{ ^"AS" ~ !ident_char ~ WHITESPACE* ~ identifier } +clause_word = _{ + ( + ^"FROM" | ^"WHERE" | ^"JOIN" | ^"INNER" | ^"LEFT" | ^"RIGHT" | ^"FULL" | ^"CROSS" | ^"ON" + | ^"GROUP" | ^"HAVING" | ^"UNION" | ^"INTERSECT" | ^"EXCEPT" | ^"ORDER" | ^"USE" + | ^"LIMIT" | ^"OFFSET" + ) ~ !ident_char } select_list = { star | select_item ~ ("," ~ select_item)* } star = { "*" } -select_item = { expr ~ (^"AS" ~ identifier)? } +select_item = { expr ~ item_alias? } where_clause = { ^"WHERE" ~ expr } order_by_clause = { ^"ORDER" ~ ^"BY" ~ order_item ~ ("," ~ order_item)* } order_item = { expr ~ sort_dir? } sort_dir = { ^"ASC" | ^"DESC" } use_vector_clause = { ^"USE" ~ ^"VECTOR" ~ search_mode ~ (vector_options ~ ANY*)? } search_mode = @{ (^"AUTO" | ^"EXACT" | ^"INDEXED") ~ !ident_char } -limit_clause = { ^"LIMIT" ~ integer } +use_rank_clause = { ^"USE" ~ ^"RANK" ~ identifier } +limit_clause = { ^"LIMIT" ~ (integer | parameter) } +offset_clause = { ^"OFFSET" ~ (integer | parameter) } +group_by_clause = { ^"GROUP" ~ ^"BY" ~ expr ~ ("," ~ expr)* } +having_clause = { ^"HAVING" ~ expr } create_table_stmt = { ^"CREATE" ~ ^"TABLE" ~ if_not_exists? ~ identifier @@ -105,16 +159,16 @@ data_type = { vector_type = { ^"VECTOR" ~ "(" ~ integer ~ ")" ~ quantization? ~ partition_key? ~ max_partitions? ~ (^"SEARCH_MODE" ~ search_mode)? - ~ auto_index_at? ~ consolidation? + ~ indexing_threshold? ~ compaction? // WITH stands first or nowhere: after another clause it is no clause of a later version. ~ !(^"WITH" ~ !ident_char) } quantization = { ^"WITH" ~ "(" ~ ^"quantization" ~ "=" ~ string ~ ")" } partition_key = { ^"PARTITION_KEY" ~ "(" ~ identifier ~ ("," ~ identifier)* ~ ")" } max_partitions = { ^"MAX_PARTITIONS" ~ signed } -auto_index_at = { ^"AUTO_INDEX_AT" ~ signed } -consolidation = { - ^"CONSOLIDATION" +indexing_threshold = { ^"INDEXING_THRESHOLD" ~ signed } +compaction = { + ^"COMPACTION" ~ ( ^"NONE" | "(" @@ -214,12 +268,12 @@ rename_column = { ^"RENAME" ~ column_word ~ identifier ~ ^"TO" ~ identifier } alter_column = { ^"ALTER" ~ column_word ~ identifier ~ ^"SET" ~ ( - ^"MAX_PARTITIONS" ~ signed | ^"SEARCH_MODE" ~ search_mode | auto_index_at | consolidation - | auto_index_default | consolidation_default | later + ^"MAX_PARTITIONS" ~ signed | ^"SEARCH_MODE" ~ search_mode | indexing_threshold | compaction + | indexing_threshold_default | compaction_default | later ) } -auto_index_default = { ^"AUTO_INDEX_AT" ~ ^"DEFAULT" } -consolidation_default = { ^"CONSOLIDATION" ~ ^"DEFAULT" } +indexing_threshold_default = { ^"INDEXING_THRESHOLD" ~ ^"DEFAULT" } +compaction_default = { ^"COMPACTION" ~ ^"DEFAULT" } // Whole words, so that a column whose name begins with one is still a column. column_word = @{ ^"COLUMN" ~ !ident_char } retain_word = @{ ^"RETAIN" ~ !ident_char } @@ -232,9 +286,10 @@ if_exists = { ^"IF" ~ ^"EXISTS" } insert_stmt = { ^"INSERT" ~ ^"INTO" ~ identifier ~ ("(" ~ identifier ~ ("," ~ identifier)* ~ ")")? - ~ ^"VALUES" ~ values_row ~ ("," ~ values_row)* - ~ on_conflict? ~ later? + ~ (^"VALUES" ~ values_row ~ ("," ~ values_row)* ~ on_conflict? ~ later? | insert_select) } +// INSERT ... SELECT, which no version has: its first word is read so that it is refused by name. +insert_select = { subquery ~ ANY* } on_conflict = { ^"ON" ~ ^"CONFLICT" ~ columns ~ ^"DO" ~ ^"UPDATE" ~ ^"SET" ~ assignment ~ ("," ~ assignment)* } @@ -253,22 +308,36 @@ or_op = @{ ^"OR" ~ !ident_char } and_op = @{ ^"AND" ~ !ident_char } not_op = @{ ^"NOT" ~ !ident_char } -comparison_suffix = _{ is_null_suffix | in_suffix | cmp_suffix | later } +comparison_suffix = _{ + cmp_suffix | &ASCII_ALPHA ~ (is_null_suffix | in_suffix | between_suffix | like_suffix | match_suffix | later) +} cmp_suffix = { cmp_op ~ distance_expr } cmp_op = { "=" | "!=" | "<>" | "<=" | ">=" | "<" | ">" } is_null_suffix = { ^"IS" ~ not_op? ~ ^"NULL" } -in_suffix = { not_op? ~ ^"IN" ~ "(" ~ (subquery ~ ANY* | expr ~ ("," ~ expr)* ~ ")") } +in_suffix = { not_op? ~ ^"IN" ~ "(" ~ (&subquery ~ select_stmt | expr ~ ("," ~ expr)*) ~ ")" } +// The AND between the two ends belongs to BETWEEN: it is read here, before `expr` looks for one. +between_suffix = { not_op? ~ between_op ~ distance_expr ~ and_op ~ distance_expr } +like_suffix = { not_op? ~ like_op ~ distance_expr } +// A full-text search, which no version has: it is read so that it is refused by its own kind. +match_suffix = { match_op ~ distance_expr } +// Whole words, so that a name that begins with one is still a name. +between_op = @{ ^"BETWEEN" ~ !ident_char } +like_op = @{ ^"LIKE" ~ !ident_char } +match_op = @{ ^"MATCH" ~ !ident_char } -// The distance operator binds tighter than a comparison and looser than `+` and `-`. -distance_expr = { additive_expr ~ ("<=>" ~ additive_expr)? } +// The distance operator and the two that read a field of a JSON value bind alike, as in +// Postgres: tighter than a comparison, looser than `+` and `-`, from left to right. +distance_expr = { additive_expr ~ (other_op ~ additive_expr)* } +other_op = { "<=>" | "->>" | "->" } additive_expr = { unary_minus* ~ primary_expr ~ (math_op ~ unary_minus* ~ primary_expr)* } math_op = { "+" | "-" | "*" | "/" } unary_minus = { "-" } primary_expr = _{ - function_call - | parameter + parameter + | exists + | function_call | null_lit | bool_lit | float @@ -276,6 +345,7 @@ primary_expr = _{ | string | vector_lit | column_ref + | scalar_select | parenthesized } // One expression in parentheses is that expression; two or more are a row value. One rule reads @@ -284,7 +354,15 @@ primary_expr = _{ parenthesized = { "(" ~ expr ~ ("," ~ expr)* ~ ")" } vector_lit = { "[" ~ vector_component ~ ("," ~ vector_component)* ~ "]" } vector_component = @{ "-"? ~ ASCII_DIGIT+ ~ ("." ~ ASCII_DIGIT+)? } -function_call = { as_written ~ "(" ~ (star | (expr ~ ("," ~ expr)*))? ~ ")" } +function_call = { as_written ~ "(" ~ (star | (expr ~ ("," ~ expr)*))? ~ ")" ~ over? } +// The window of a function. Any function may be written before it: the builder refuses all but +// the one this version has. +over = { ^"OVER" ~ "(" ~ partition_by? ~ order_by_clause? ~ ")" } +partition_by = { ^"PARTITION" ~ ^"BY" ~ expr ~ ("," ~ expr)* } +// A SELECT in parentheses standing as one value, and EXISTS, which no version has: it is read +// so that it is refused by its own kind. +scalar_select = { "(" ~ &subquery ~ select_stmt ~ ")" } +exists = { ^"EXISTS" ~ "(" ~ &subquery ~ select_stmt ~ ")" } column_ref = { identifier ~ ("." ~ identifier)? } // A rank formula, which no statement reads: numbers and `{column}`s joined by `+` and `*`, in diff --git a/v2/contextdb/src/sql/mod.rs b/v2/contextdb/src/sql/mod.rs index 8a6f2ca61..6d2f94d57 100644 --- a/v2/contextdb/src/sql/mod.rs +++ b/v2/contextdb/src/sql/mod.rs @@ -11,8 +11,10 @@ mod parser; pub(crate) mod plan; mod planner; -pub(crate) use ast::{Expr, Statement}; -pub(crate) use plan::{Effect, PhysicalPlan as Plan}; +pub(crate) use ast::{Expr, Statement, Statement as Plan}; +pub(crate) use parser::{MAX_EXPR_NESTING, depth_error}; +pub(crate) use plan::Effect; +pub(crate) use planner::{AGGREGATES, inside, inside_mut}; use crate::types::{Error, Result}; @@ -30,9 +32,11 @@ pub(crate) fn formula(text: &str) -> Result { parser::formula(text) } -/// Plans a parsed statement. Refuses with `PlanError`. Looks at no table and no data. -pub(crate) fn plan(statement: &Statement) -> Result { - planner::plan(statement) +/// Plans a parsed statement, which is its own plan once it passes. Refuses with `PlanError`. +/// Looks at no table and no data. +pub(crate) fn plan(statement: Statement) -> Result { + planner::stands(&statement)?; + Ok(statement) } /// The refusal of a statement, a clause or a form that a later version of the library reads, diff --git a/v2/contextdb/src/sql/parser/alter.rs b/v2/contextdb/src/sql/parser/alter.rs index 74400f195..4cb118cde 100644 --- a/v2/contextdb/src/sql/parser/alter.rs +++ b/v2/contextdb/src/sql/parser/alter.rs @@ -1,6 +1,6 @@ //! ALTER TABLE: one action, read into what it changes. -use super::ddl::{column_def, consolidation, table_option}; +use super::ddl::{column_def, compaction, table_option}; use super::{Pair, Rule, child, first_ident, ident, search_mode, signed, two_idents}; use crate::sql::ast::*; use crate::types::Result; @@ -32,12 +32,10 @@ pub(super) fn alter_table(pair: Pair<'_>) -> Result { column, max_partitions: set.as_str().to_owned(), }, - Rule::auto_index_at => AlterAction::SetAutoIndexAt(column, signed(set)), - Rule::auto_index_default => AlterAction::SetAutoIndexAt(column, None), - Rule::consolidation => { - AlterAction::SetConsolidation(column, Some(consolidation(set))) - } - Rule::consolidation_default => AlterAction::SetConsolidation(column, None), + Rule::indexing_threshold => AlterAction::SetIndexingThreshold(column, signed(set)), + Rule::indexing_threshold_default => AlterAction::SetIndexingThreshold(column, None), + Rule::compaction => AlterAction::SetCompaction(column, Some(compaction(set))), + Rule::compaction_default => AlterAction::SetCompaction(column, None), // The one clause left: SEARCH_MODE. _ => AlterAction::SetSearchMode { column, diff --git a/v2/contextdb/src/sql/parser/ddl.rs b/v2/contextdb/src/sql/parser/ddl.rs index fd35ad37f..edfba670d 100644 --- a/v2/contextdb/src/sql/parser/ddl.rs +++ b/v2/contextdb/src/sql/parser/ddl.rs @@ -256,13 +256,13 @@ pub(super) fn table_option(part: Pair<'_>, options: &mut TableOptions) -> Result Ok(()) } -/// `CONSOLIDATION NONE` or `CONSOLIDATION (...)`, which is NONE when it has no member. -pub(super) fn consolidation(clause: Pair<'_>) -> ConsolidationClause { +/// `COMPACTION NONE` or `COMPACTION (...)`, which is NONE when it has no member. +pub(super) fn compaction(clause: Pair<'_>) -> CompactionClause { let member = |rule| child(clause.clone(), rule).and_then(signed); let [change, tombstone] = [Rule::change_percent, Rule::tombstone_percent].map(member); match (change, tombstone) { - (None, None) => ConsolidationClause::None, - (change, tombstone) => ConsolidationClause::Percent { change, tombstone }, + (None, None) => CompactionClause::None, + (change, tombstone) => CompactionClause::Percent { change, tombstone }, } } @@ -285,9 +285,9 @@ pub(super) fn column_def(pair: Pair<'_>) -> Result { Rule::partition_key => vector.partition_key = idents(clause), Rule::max_partitions => vector.max_partitions = signed(clause), Rule::search_mode => vector.search_mode = Some(search_mode(&clause)), - Rule::auto_index_at => vector.auto_index_at = signed(clause), - // The one clause left: CONSOLIDATION. - _ => vector.consolidation = Some(consolidation(clause)), + Rule::indexing_threshold => vector.indexing_threshold = signed(clause), + // The one clause left: COMPACTION. + _ => vector.compaction = Some(compaction(clause)), } } DataType::Vector(number::(&dimension, "the VECTOR dimension")? as usize) diff --git a/v2/contextdb/src/sql/parser/expr.rs b/v2/contextdb/src/sql/parser/expr.rs index 4927518f7..3dc3f6b7a 100644 --- a/v2/contextdb/src/sql/parser/expr.rs +++ b/v2/contextdb/src/sql/parser/expr.rs @@ -5,9 +5,11 @@ //! once for every level of nesting, to the limit, on the caller's stack. So each is kept small: //! what is not on that path is in a function of its own, and a list is gathered with a loop. -use super::{MAX_EXPR_NESTING, Pair, Rule, depth_error, has, ident, number, string}; +use super::{ + MAX_EXPR_NESTING, Pair, Rule, child, depth_error, direction, has, ident, number, select, string, +}; use crate::sql::ast::*; -use crate::types::Result; +use crate::types::{Error, Result}; pub(super) fn expr(pair: Pair<'_>) -> Result { // `[NOT] comparison {AND | OR [NOT] comparison}`. AND binds tighter than OR: `all` gathers @@ -32,7 +34,11 @@ pub(super) fn expr(pair: Pair<'_>) -> Result { } } any.push(balanced(all, BinOp::And)); - let built = balanced(any, BinOp::Or); + within_limit(balanced(any, BinOp::Or)) +} + +/// `built`, refused when it nests deeper than the limit. +fn within_limit(built: Expr) -> Result { let depth = depth_of(&built); if depth > MAX_EXPR_NESTING { return Err(depth_error(depth)); @@ -51,22 +57,15 @@ pub(super) fn exprs(pair: Pair<'_>) -> Result> { Ok(exprs) } -/// How many expressions deep the tree goes below its root. +/// How many expressions deep the tree goes below its root. A SELECT inside it is a tree of its +/// own. fn depth_of(expr: &Expr) -> usize { - let below = match expr { - Expr::BinaryOp { left, right, .. } => depth_of(left).max(depth_of(right)), - Expr::UnaryOp { operand, .. } => depth_of(operand), - Expr::FunctionCall { args, .. } => args.iter().map(depth_of).max().unwrap_or(0), - Expr::IsNull { expr, .. } => depth_of(expr), - Expr::Distance { left, right } => depth_of(left).max(depth_of(right)), - Expr::Row(items) => items.iter().map(depth_of).max().unwrap_or(0), - Expr::InList { expr, list, .. } => { - let items = list.iter().map(depth_of).max().unwrap_or(0); - depth_of(expr).max(items) - } - Expr::Column(_) | Expr::Literal(_) | Expr::Parameter(_) => return 0, - }; - below + 1 + let leaf = matches!( + expr, + Expr::Column(_) | Expr::Literal(_) | Expr::Parameter(_) | Expr::Subquery(_) + ); + let below = crate::sql::inside(expr).into_iter().map(depth_of); + below.max().unwrap_or(0) + usize::from(!leaf) } /// Joins the operands of a run of ANDs or ORs into a tree as shallow as it can be, keeping @@ -97,66 +96,109 @@ fn not(operand: Expr) -> Expr { /// One comparison: its left side and what the grammar read after it, if anything. fn comparison_expr(left: Pair<'_>, suffix: Option>) -> Result { - let left = Box::new(distance_expr(left)?); - let Some(suffix) = suffix else { - return Ok(*left); - }; - if suffix.as_rule() == Rule::is_null_suffix { + let left = distance_expr(left)?; + match suffix { + Some(suffix) => compared(Box::new(left), suffix), + None => Ok(left), + } +} + +/// `left` with what the grammar read after it. +fn compared(left: Box, suffix: Pair<'_>) -> Result { + let negated = has(&suffix, Rule::not_op); + let rule = suffix.as_rule(); + if rule == Rule::is_null_suffix { return Ok(Expr::IsNull { expr: left, - negated: has(&suffix, Rule::not_op), + negated, }); } - if suffix.as_rule() == Rule::in_suffix { - return Ok(Expr::InList { - expr: left, - negated: has(&suffix, Rule::not_op), - list: exprs(suffix)?, + if rule == Rule::in_suffix { + return Ok(match child(suffix.clone(), Rule::select_stmt) { + Some(query) => Expr::InSubquery { + expr: left, + query: subquery(query)?, + negated, + }, + None => Expr::InList { + expr: left, + negated, + list: exprs(suffix)?, + }, }); } - let mut parts = suffix.into_inner(); - let op = match parts.next().expect("an operator").as_str() { - "=" => BinOp::Eq, - "!=" | "<>" => BinOp::Neq, - "<" => BinOp::Lt, - "<=" => BinOp::Lte, - ">" => BinOp::Gt, - _ => BinOp::Gte, - }; - Ok(Expr::BinaryOp { - left, - op, - right: Box::new(distance_expr(parts.next().expect("an operand"))?), + let mut operands = suffix + .clone() + .into_inner() + .filter(|part| part.as_rule() == Rule::distance_expr); + let mut operand = || distance_expr(operands.next().expect("an operand")).map(Box::new); + Ok(match rule { + Rule::match_suffix => return Err(Error::FullTextSearchNotSupported), + Rule::like_suffix => Expr::Like { + expr: left, + pattern: operand()?, + negated, + }, + Rule::between_suffix => Expr::Between { + expr: left, + low: operand()?, + high: operand()?, + negated, + }, + _ => Expr::BinaryOp { + left, + op: match suffix.into_inner().next().expect("an operator").as_str() { + "=" => BinOp::Eq, + "!=" | "<>" => BinOp::Neq, + "<" => BinOp::Lt, + "<=" => BinOp::Lte, + ">" => BinOp::Gt, + _ => BinOp::Gte, + }, + right: operand()?, + }, }) } -/// `sum [<=> sum]`: a sum alone, or the distance between two. +/// `sum {<=> | -> | ->> sum}`, read left to right: a distance, or a field of a JSON value. A +/// chain of operators builds a tree one deeper per operator, so its depth is checked as it +/// grows. fn distance_expr(pair: Pair<'_>) -> Result { - let mut sides = pair.into_inner(); - let left = additive_expr(sides.next().expect("an operand"))?; - let Some(right) = sides.next() else { - return Ok(left); - }; - Ok(Expr::Distance { - left: Box::new(left), - right: Box::new(additive_expr(right)?), + let mut parts = pair.into_inner(); + let mut built = additive_expr(parts.next().expect("an operand"))?; + while let Some(op) = parts.next() { + let right = additive_expr(parts.next().expect("an operand"))?; + built = distance_or_field(op.as_str(), Box::new(built), Box::new(right))?; + } + Ok(built) +} + +fn distance_or_field(op: &str, left: Box, right: Box) -> Result { + within_limit(match op { + "<=>" => Expr::Distance { left, right }, + arrow => Expr::Field { + json: left, + key: right, + as_text: arrow == "->>", + }, }) } +/// A SELECT that stands inside an expression. +fn subquery(pair: Pair<'_>) -> Result> { + select(pair).map(Box::new) +} + /// `left right` as a call of `__add`, `__sub`, `__mul` or `__div`. A chain of operators /// builds a tree one deeper per operator, so its depth is checked as it grows. fn arithmetic(op: &str, left: Expr, right: Expr) -> Result { - let depth = depth_of(&left).max(depth_of(&right)) + 1; - if depth > MAX_EXPR_NESTING { - return Err(depth_error(depth)); - } let name = match op { "+" => "__add", "-" => "__sub", "*" => "__mul", _ => "__div", }; - Ok(Expr::FunctionCall { + within_limit(Expr::FunctionCall { name: name.to_owned(), args: vec![left, right], }) @@ -236,6 +278,10 @@ fn primary_expr(primary: Pair<'_>) -> Result { _ => Expr::Row(items), }) } + Rule::exists => Err(Error::SubqueryNotSupported), + Rule::scalar_select => { + subquery(primary.into_inner().next().expect("a SELECT")).map(Expr::Subquery) + } Rule::function_call => function_call(primary), Rule::column_ref | Rule::braced => Ok(column_ref(primary)), // The parts of a rank formula. @@ -285,8 +331,49 @@ fn function_call(pair: Pair<'_>) -> Result { for arg in parts { args.push(match arg.as_rule() { Rule::star => star(), + Rule::over => return row_number(&name, &args, arg), _ => expr(arg)?, }); } Ok(Expr::FunctionCall { name, args }) } + +/// The sort keys of an ORDER BY, in written order. +pub(super) fn sort_keys(clause: Pair<'_>) -> Result> { + let mut keys = Vec::new(); + for item in clause.into_inner() { + let mut parts = item.into_inner(); + keys.push(OrderByItem { + expr: expr(parts.next().expect("a sort key"))?, + direction: direction(parts.next()), + }); + } + Ok(keys) +} + +/// The one window function, `ROW_NUMBER() OVER ([PARTITION BY ...] ORDER BY ...)`. Any other +/// function before OVER, and a window with no ORDER BY, is refused by name. +fn row_number(name: &str, args: &[Expr], over: Pair<'_>) -> Result { + let mut partition_by = Vec::new(); + let mut order_by = Vec::new(); + for part in over.into_inner() { + if part.as_rule() == Rule::partition_by { + partition_by = exprs(part)?; + continue; + } + order_by = sort_keys(part)?; + } + let form = if !name.eq_ignore_ascii_case("ROW_NUMBER") { + format!("{name} OVER") + } else if !args.is_empty() { + "ROW_NUMBER with arguments".to_owned() + } else if order_by.is_empty() { + "ROW_NUMBER without ORDER BY".to_owned() + } else { + return Ok(Expr::RowNumber { + partition_by, + order_by, + }); + }; + Err(Error::WindowFunctionNotSupported { form }) +} diff --git a/v2/contextdb/src/sql/parser/graph.rs b/v2/contextdb/src/sql/parser/graph.rs new file mode 100644 index 000000000..f5326ca17 --- /dev/null +++ b/v2/contextdb/src/sql/parser/graph.rs @@ -0,0 +1,84 @@ +//! Reads `GRAPH_TABLE(...)`: the pattern a FROM or a JOIN matches over an edge table. + +use super::select::column; +use super::{Pair, Rule, child, first_ident, has, ident, idents, number, where_clause}; +use crate::sql::ast::{EdgeDirection, EdgeStep, GraphTable, NodePattern}; +use crate::sql::not_supported; +use crate::types::{Error, Result}; + +/// The most hops one step of a pattern may ask for. +const MAX_HOPS: u32 = 10; + +pub(super) fn graph_table(pair: Pair<'_>) -> Result { + let mut graph = GraphTable { + edge_table: first_ident(pair.clone()), + filter: where_clause(pair.clone())?, + ..GraphTable::default() + }; + for part in pair.into_inner() { + match part.as_rule() { + Rule::node_pattern => graph.start = node(part)?, + Rule::edge_step => graph.steps.push(step(part)?), + Rule::graph_columns => { + graph.columns = part.into_inner().map(column).collect::>()?; + } + // The edge table and the WHERE clause, read above. + _ => {} + } + } + if graph.columns.is_empty() { + return Err(not_supported("a graph pattern with no COLUMNS")); + } + Ok(graph) +} + +/// The label or edge type written after the colon of a node or an edge. +fn label(pair: Pair<'_>) -> Option { + child(pair, Rule::label).map(|label| ident(&label.into_inner().next().expect("a label"))) +} + +/// The name written in a node's parentheses. A label there would select nothing: refused. +fn node(pair: Pair<'_>) -> Result { + if label(pair.clone()).is_some() { + return Err(not_supported("a label on a node of a pattern")); + } + let alias = idents(pair).pop(); + Ok(NodePattern { alias }) +} + +/// One edge and the node it leads to. Refuses a step with no upper bound, and one whose upper +/// bound is above `MAX_HOPS`. +fn step(pair: Pair<'_>) -> Result { + let direction = if has(&pair, Rule::incoming) { + EdgeDirection::Incoming + } else if has(&pair, Rule::outgoing) { + EdgeDirection::Outgoing + } else { + EdgeDirection::Both + }; + let edge_type = label(child(pair.clone(), Rule::edge).expect("an edge")); + let to = node(child(pair.clone(), Rule::node_pattern).expect("a node"))?; + let (min, max) = match child(pair, Rule::hops) { + None => (1, 1), + Some(hops) => { + let mut bounds = hops.into_inner(); + let (Some(min), Some(max)) = (bounds.next(), bounds.next()) else { + return Err(Error::UnboundedTraversal); + }; + (number(&min, "hop count")?, number(&max, "hop count")?) + } + }; + if max > MAX_HOPS { + return Err(Error::BfsDepthExceeded { + depth: max, + max: MAX_HOPS, + }); + } + Ok(EdgeStep { + direction, + edge_type, + min, + max, + to, + }) +} diff --git a/v2/contextdb/src/sql/parser/mod.rs b/v2/contextdb/src/sql/parser/mod.rs index 4fbaec771..cf428254e 100644 --- a/v2/contextdb/src/sql/parser/mod.rs +++ b/v2/contextdb/src/sql/parser/mod.rs @@ -8,6 +8,8 @@ mod alter; mod ddl; mod expr; +mod graph; +mod select; use std::str::FromStr; @@ -17,6 +19,7 @@ use pest::error::{InputLocation, LineColLocation}; use super::ast::*; use super::{not_carried, not_supported}; use crate::types::{Error, Result}; +use select::select; #[derive(pest_derive::Parser)] #[grammar = "sql/grammar.pest"] @@ -26,7 +29,7 @@ type Pair<'a> = pest::iterators::Pair<'a, Rule>; /// The deepest an expression may nest, in the text and in the tree built from it. It bounds the /// parser's own recursion and the recursion of everything that later walks an expression. -const MAX_EXPR_NESTING: usize = 128; +pub(crate) const MAX_EXPR_NESTING: usize = 64; pub(super) fn parse(text: &str) -> Result { check_source_nesting(text)?; @@ -38,22 +41,27 @@ pub(super) fn parse(text: &str) -> Result { let words: Vec<&str> = part.as_str().split_whitespace().collect(); words.join(" ").to_ascii_uppercase() } - Rule::subquery => "IN (SELECT ...)".to_owned(), + Rule::subquery => "INSERT ... SELECT".to_owned(), Rule::vector_options => "USE VECTOR with options".to_owned(), _ => continue, }; if matches!(&*later, "IVF" | "SEARCH") { let instead = "the index sizes its own groups and measures how far a search scans; \ for the true nearest rows write USE VECTOR EXACT or SEARCH_MODE EXACT, \ - and to move the size from which AUTO uses the index write AUTO_INDEX_AT"; + and to move the size from which AUTO uses the index write INDEXING_THRESHOLD"; return Err(not_carried(&format!("{later} (...)"), instead)); } return Err(not_supported(&later)); } - let pair = read - .flatten() - .nth(1) - .expect("the grammar's statement rule holds one statement"); + statement( + read.flatten() + .nth(1) + .expect("the statement rule holds one statement"), + ) +} + +/// The statement one rule of the grammar matched. +fn statement(pair: Pair) -> Result { match pair.as_rule() { Rule::stored_procedure => Err(Error::StoredProcNotSupported), Rule::create_table_stmt => ddl::create_table(pair).map(Statement::CreateTable), @@ -84,6 +92,10 @@ pub(super) fn parse(text: &str) -> Result { Rule::select_stmt => select(pair).map(Statement::Select), Rule::set_memory_limit => memory_limit(pair).map(Statement::SetMemoryLimit), Rule::show_vector_indexes => Ok(Statement::ShowVectorIndexes), + Rule::explain_stmt => { + let explained = pair.into_inner().next().expect("the statement explained"); + statement(explained).map(|explained| Statement::Explain(Box::new(explained))) + } Rule::show_vector_partitions => { let mut names = idents(pair.clone()).into_iter(); let count = |rule, what| { @@ -124,9 +136,9 @@ fn syntax_error(text: &str, error: &pest::error::Error) -> Error { } } -fn depth_error(depth: usize) -> Error { +pub(crate) fn depth_error(depth: usize) -> Error { refuse(format!( - "expression nesting of {depth} is deeper than the limit of {MAX_EXPR_NESTING}" + "nesting of {depth} is deeper than the limit of {MAX_EXPR_NESTING}" )) } @@ -351,58 +363,6 @@ fn direction(written: Option>) -> SortDirection { } } -fn select(pair: Pair<'_>) -> Result { + let at = pair.as_span().start(); + let mut with = Vec::new(); + let mut whole: Option { + let mut select = Select { + filter: where_clause(pair.clone())?, + ..Select::default() + }; + for part in pair.into_inner() { + match part.as_rule() { + Rule::distinct => select.distinct = true, + Rule::select_list => { + for item in part.into_inner() { + select.columns.push(match item.as_rule() { + Rule::star => SelectColumn { + expr: star(), + alias: None, + }, + _ => column(item)?, + }); + } + } + Rule::table_ref => select.from.push(table(part)), + Rule::graph_table => select.from.push(FromItem::Graph(graph_table(part)?)), + Rule::more_tables => return Err(not_supported("FROM a, b")), + Rule::join => { + let mut parts = part.into_inner(); + let kind = parts.next().expect("the kind of join"); + let kind = kind.as_str().to_ascii_uppercase(); + for other in ["RIGHT", "FULL"] { + if kind.starts_with(other) { + return Err(not_supported(&format!("{other} JOIN"))); + } + } + select.joins.push(Join { + left_outer: kind.starts_with("LEFT"), + item: table(parts.next().expect("a table")), + on: parts.next().map(expr).transpose()?, + }); + } + Rule::group_by_clause => select.group_by = exprs(part)?, + Rule::having_clause => select.having = exprs(part)?.pop(), + // The WHERE clause, read above. + _ => {} + } + } + Ok(select) +} + +/// A select item, or a column of a graph pattern, with the name it is given. +pub(super) fn column(item: Pair<'_>) -> Result { + let mut parts = item.into_inner(); + Ok(SelectColumn { + expr: expr(parts.next().expect("an expression"))?, + alias: parts.next().map(first_ident), + }) +} + +/// A table of FROM or of a JOIN, with the name the statement gives it. +fn table(pair: Pair<'_>) -> FromItem { + FromItem::Table { + alias: child(pair.clone(), Rule::alias).map(first_ident), + name: first_ident(pair), + } +} diff --git a/v2/contextdb/src/sql/parser/tests.rs b/v2/contextdb/src/sql/parser/tests.rs index 1db736552..dd706a89d 100644 --- a/v2/contextdb/src/sql/parser/tests.rs +++ b/v2/contextdb/src/sql/parser/tests.rs @@ -1,11 +1,7 @@ use super::parse; -use crate::sql::ast::{ - BinOp, ColumnRef, ConsolidationClause, DataType, Expr, Literal, Select, Statement, - VectorClauses, -}; +use crate::sql::ast::{BinOp, ColumnRef, Expr, Literal, Select, Statement}; use crate::sql::plan; -use crate::sql::plan::{Effect, PhysicalPlan}; -use crate::types::{Error, SortDirection, VectorSearchMode}; +use crate::types::Error; fn refusal(sql: &str) -> String { match parse(sql) { @@ -14,9 +10,9 @@ fn refusal(sql: &str) -> String { } } -fn planned(sql: &str) -> PhysicalPlan { +fn planned(sql: &str) -> Statement { let statement = parse(sql).unwrap_or_else(|error| panic!("{sql}\nwas refused: {error:?}")); - plan(&statement).unwrap_or_else(|error| panic!("{sql}\nwas not planned: {error:?}")) + plan(statement).unwrap_or_else(|error| panic!("{sql}\nwas not planned: {error:?}")) } #[test] @@ -29,198 +25,11 @@ fn a_refusal_names_the_word_the_grammar_stopped_at() { assert!(refusal("SELECT id\nFROM").contains("line 2, column 5: the statement ends too soon")); } -#[test] -fn nesting_is_read_to_the_limit_and_refused_past_it() { - // Each way an expression nests, on the stack a test thread has. - for (open, close) in [("(", ")"), ("COALESCE(", ", 1)"), ("NOT ", "")] { - let nested = |levels: usize| { - format!( - "SELECT id FROM t WHERE {}id{}", - open.repeat(levels), - close.repeat(levels) - ) - }; - if let Err(error) = parse(&nested(128)) { - panic!("128 levels of `{open}` were refused: {error:?}"); - } - assert!(refusal(&nested(129)).contains("deeper than the limit of 128")); - } - // A parenthesis inside quoted text or a comment is not a level. - let quoted = format!( - "SELECT '{}' /* {} */ FROM t", - "(".repeat(200), - "(".repeat(200) - ); - parse("ed).expect("quoted parentheses do not nest"); - // A chain of operators nests in the tree it builds, not in the text. - let chain = format!("SELECT id FROM t WHERE id = 1{}", " + 1".repeat(200)); - assert!(refusal(&chain).contains("deeper than the limit of 128")); - // A run of ANDs is joined into a shallow tree and is not a chain. - let run = format!( - "SELECT id FROM t WHERE id = 1{}", - " AND id = 1".repeat(2000) - ); - parse(&run).expect("a long run of ANDs is read"); -} - -#[test] -fn operators_bind_as_in_standard_sql() { - let filter = |sql: &str| { - let Statement::Select(select) = parse(&format!("SELECT id FROM t WHERE {sql}")).unwrap() - else { - panic!("not a SELECT"); - }; - format!("{:?}", select.where_clause.unwrap()) - }; - assert_eq!( - filter("a = 1 + 2 * 3 - 4"), - filter("a = ((1 + (2 * 3)) - 4)") - ); - assert_eq!( - filter("a = 8 / 4 / 2 * -b"), - filter("a = (((8 / 4) / 2) * (-b))") - ); - assert_eq!( - filter("NOT a = 1 AND b IS NOT NULL OR c <> 3"), - filter("((NOT (a = 1)) AND (b IS NOT NULL)) OR (c != 3)") - ); -} - -#[test] -fn a_table_is_read_with_its_columns_and_rules() { - let Statement::CreateTable(table) = parse( - "CREATE TABLE IF NOT EXISTS \"my codes\" (id INTEGER PRIMARY KEY, code TEXT NOT NULL \ - DEFAULT 'a''b', v VECTOR(3), at TIMESTAMP DEFAULT NOW(), UNIQUE (code))", - ) - .unwrap() else { - panic!("not a CREATE TABLE"); - }; - assert_eq!(table.name, "my codes"); - assert!(table.if_not_exists); - // A table-level UNIQUE may name one column. - assert_eq!(table.unique_constraints, [["code"]]); - let types: Vec<&DataType> = table - .columns - .iter() - .map(|column| &column.data_type) - .collect(); - assert_eq!( - types, - [ - &DataType::Integer, - &DataType::Text, - &DataType::Vector(3), - &DataType::Timestamp - ] - ); - assert!(table.columns[0].primary_key && !table.columns[1].nullable); - assert!(matches!( - &table.columns[1].default, - Some(Expr::Literal(Literal::Text(text))) if text == "a'b" - )); - assert!(refusal("CREATE TABLE t (a TEXT, UNIQUE (a, a))").contains("twice")); - assert!(refusal("CREATE TABLE t (a TEXT, UNIQUE (b))").contains("unknown column 'b'")); - assert!(refusal("CREATE TABLE t (a TEXT NOT NULL NOT NULL)").contains("duplicate NOT NULL")); -} - -#[test] -fn every_statement_is_read_planned_and_told_apart() { - for (sql, effect) in [ - ( - "CREATE TABLE t (id UUID PRIMARY KEY, n INT NULL, ok BOOL, r FLOAT, doc JSON)", - Effect::Declares, - ), - ("CREATE INDEX by_n ON t (n DESC, id)", Effect::Declares), - ( - "INSERT INTO t VALUES (1, 'a', NULL, TRUE, -2.5, [0.1, -0.2], $p)", - Effect::WritesRows, - ), - ( - "INSERT INTO t (a, b) VALUES (1, 2), (3, 4);", - Effect::WritesRows, - ), - ( - "UPDATE t SET a = 1, b = b * 2 WHERE a IS NOT NULL", - Effect::WritesRows, - ), - ("DELETE FROM t WHERE a >= 1 OR NOT ok", Effect::WritesRows), - ("DELETE FROM t", Effect::WritesRows), - ("SELECT * FROM t", Effect::Reads), - ( - "SELECT COUNT(*), MIN(n), MAX(n), SUM(n) AS total FROM t WHERE t.n < 5", - Effect::Reads, - ), - ( - "SELECT id, n + 1 AS next FROM t ORDER BY next DESC, COALESCE(n, 0), id LIMIT 3", - Effect::Reads, - ), - ("SET MEMORY_LIMIT '64M'", Effect::Sets(Some(64 << 20))), - ("SET MEMORY_LIMIT = none", Effect::Sets(None)), - ("SHOW MEMORY_LIMIT", Effect::Reads), - ] { - assert_eq!(planned(sql).effect(), effect, "{sql}"); - } - assert!(matches!( - planned("SELECT * FROM t LIMIT 1"), - PhysicalPlan::Limit { .. } - )); - assert!(matches!( - planned("SELECT a FROM t ORDER BY a"), - PhysicalPlan::Project { .. } - )); - assert!(refusal("SET MEMORY_LIMIT 99999999999999999999G").contains("out of range")); -} - -#[test] -fn a_sort_key_the_engine_cannot_work_out_is_refused_when_planned() { - for key in ["UPPER(tag)", "tag = 'a'", "1"] { - let statement = parse(&format!("SELECT tag FROM notes ORDER BY {key}")).unwrap(); - assert!( - matches!(plan(&statement), Err(Error::OrderByExpressionNotSupported)), - "{key}" - ); - } -} - -#[test] -fn comments_are_skipped_and_kept_inside_quoted_text() { - let Statement::Insert(insert) = parse( - "/* before */ INSERT INTO notes (id, body) -- the columns\n VALUES (1, '-- kept /* too */');", - ) - .unwrap() else { - panic!("not an INSERT"); - }; - assert!(matches!( - &insert.values[0][1], - Expr::Literal(Literal::Text(text)) if text == "-- kept /* too */" - )); -} - #[test] fn what_a_later_version_reads_is_refused_by_its_name() { for (sql, name) in [ ("BEGIN", "BEGIN"), ("purge FROM t WHERE id = 1", "PURGE"), - ( - "WITH recent AS (SELECT a FROM t) SELECT a FROM recent", - "WITH", - ), - ("SELECT DISTINCT a FROM t", "DISTINCT"), - ( - "SELECT a FROM t LEFT JOIN u ON t.a = u.a WHERE a = 1", - "LEFT JOIN", - ), - ("SELECT a FROM t JOIN u ON t.a = u.a", "JOIN"), - ( - "SELECT a, COUNT(*) FROM t WHERE a = 1 GROUP BY a", - "GROUP BY", - ), - ( - "SELECT a FROM GRAPH_TABLE(g MATCH (a)-[e]->(b))", - "GRAPH_TABLE", - ), - ("SELECT id FROM t WHERE a LIKE 'x%'", "LIKE"), - ("UPDATE t SET a = 1 WHERE b BETWEEN 1 AND 2", "BETWEEN"), ( "CREATE TABLE t (id UUID PRIMARY KEY, until TIMESTAMP EXPIRES)", "EXPIRES", @@ -239,12 +48,12 @@ fn what_a_later_version_reads_is_refused_by_its_name() { planned("CREATE TABLE t (id INT PRIMARY KEY, state TEXT, immutable BOOL, history TEXT)"); planned("SELECT state, history FROM t WHERE immutable ORDER BY state"); // What is neither read nor named is a syntax error. - assert!(refusal("SELECT a FROM t x").contains("unexpected 'x'")); + assert!(refusal("SELECT a FROM t x y").contains("unexpected 'y'")); // A row value is read wherever an expression is. In a select list it is refused by name // when the statement is planned. let read = parse("SELECT (a, b) FROM t") .unwrap_or_else(|error| panic!("a row value in a select list was not read: {error:?}")); - match plan(&read) { + match plan(read) { Err(Error::PlanError(text)) => { assert!(text.to_lowercase().contains("row value"), "{text}"); } @@ -271,64 +80,6 @@ fn is_distance(expr: &Expr, column: &str, parameter: &str) -> bool { of_column && matches!(&**right, Expr::Parameter(name) if name == parameter) } -#[test] -fn a_distance_is_read_as_an_expression() { - // In a select item under a name, with the search ordered by that name. - let read = select("SELECT id, v <=> $q AS distance FROM t ORDER BY distance LIMIT 3"); - assert!(is_distance(&read.columns[1].expr, "v", "q")); - assert_eq!(read.columns[1].alias.as_deref(), Some("distance")); - assert!(matches!( - &read.order_by[..], - [item] if item.direction == SortDirection::Asc - && matches!( - &item.expr, - Expr::Column(ColumnRef { table: None, column }) if column == "distance" - ) - )); - assert_eq!((read.limit, read.use_vector), (Some(3), None)); - - // Under no name, and as the ORDER BY item itself, with ASC written or not. - for order in ["v <=> $q", "v <=> $q ASC", "v<=>$q asc"] { - let read = select(&format!( - "SELECT id, v <=> $q FROM t ORDER BY {order} LIMIT 3" - )); - assert!(is_distance(&read.columns[1].expr, "v", "q"), "{order}"); - assert_eq!(read.columns[1].alias, None, "{order}"); - assert!( - matches!( - &read.order_by[..], - [item] if item.direction == SortDirection::Asc && is_distance(&item.expr, "v", "q") - ), - "{order}" - ); - } - - // Inside another expression: one minus the distance. - let read = select("SELECT id, 1 - (v <=> $q) AS similarity FROM t ORDER BY v <=> $q LIMIT 3"); - assert!(matches!( - &read.columns[1].expr, - Expr::FunctionCall { name, args } - if name == "__sub" - && matches!(&args[..], [Expr::Literal(Literal::Integer(1)), distance] - if is_distance(distance, "v", "q")) - )); - assert_eq!(read.columns[1].alias.as_deref(), Some("similarity")); - - // The vector on the right is a literal, its quoted text or a bound name. - let read = select("SELECT id FROM t ORDER BY v <=> [1.0, 0.0] LIMIT 3"); - assert!(matches!( - &read.order_by[0].expr, - Expr::Distance { right, .. } - if matches!(&**right, Expr::Literal(Literal::Vector(vector)) if vector == &[1.0, 0.0]) - )); - let read = select("SELECT id FROM t ORDER BY v <=> '[1,0]' LIMIT 3"); - assert!(matches!( - &read.order_by[0].expr, - Expr::Distance { right, .. } - if matches!(&**right, Expr::Literal(Literal::Text(text)) if text == "[1,0]") - )); -} - #[test] fn a_distance_binds_tighter_than_a_comparison_and_looser_than_a_sum() { let item = |sql: &str| { @@ -357,188 +108,6 @@ fn a_distance_binds_tighter_than_a_comparison_and_looser_than_a_sum() { )); } -#[test] -fn a_search_is_planned_as_one_step_with_its_limit() { - // Under a projection when the statement names its columns: the search holds the column, - // the vector, the limit, the filter and the mode, and no limit wraps it. - let planned_search = planned( - "SELECT id, v <=> $q AS distance FROM t WHERE a = 1 ORDER BY distance USE VECTOR EXACT \ - LIMIT 3", - ); - assert_eq!(planned_search.effect(), Effect::Reads); - let (input, columns) = match planned_search { - PhysicalPlan::Project { input, columns } => (input, columns), - other => panic!("a search with a select list is not under a projection: {other:?}"), - }; - assert!(is_distance(&columns[1].expr, "v", "q")); - assert_eq!(columns[1].alias.as_deref(), Some("distance")); - assert!(matches!( - &*input, - PhysicalPlan::VectorSearch { - table, - column, - query: Expr::Parameter(query), - k: 3, - filter: Some(_), - mode: Some(VectorSearchMode::Exact), - } if table == "t" && column == "v" && query == "q" - )); - // `SELECT *` is the search itself, and with no USE VECTOR the mode is left to the column. - for order in ["v <=> $q", "v <=> $q ASC"] { - let sql = format!("SELECT * FROM t ORDER BY {order} LIMIT 10"); - assert!( - matches!( - planned(&sql), - PhysicalPlan::VectorSearch { - k: 10, - filter: None, - mode: None, - .. - } - ), - "{sql}" - ); - } - for (mode, read) in [ - ("AUTO", VectorSearchMode::Auto), - ("exact", VectorSearchMode::Exact), - ("Indexed", VectorSearchMode::Indexed), - ] { - let sql = format!("SELECT * FROM t ORDER BY v <=> $q USE VECTOR {mode} LIMIT 1"); - assert_eq!(select(&sql).use_vector, Some(read), "{sql}"); - assert!( - matches!( - planned(&sql), - PhysicalPlan::VectorSearch { mode: Some(found), .. } if found == read - ), - "{sql}" - ); - } - // What is refused without looking at any table, when the statement is read or planned. - let refused = |sql: &str| match parse(sql) { - Ok(statement) => plan(&statement).expect_err(sql), - Err(error) => error, - }; - // A search with no LIMIT has no kind of its own: it is refused as every statement of a - // later version is. - match refused("SELECT id FROM t ORDER BY v <=> $q") { - Error::PlanError(text) => assert_eq!( - text, - "a vector search without LIMIT is not supported in this version of the library" - ), - other => panic!("a search with no LIMIT was refused as {other:?}"), - } - assert!(matches!( - refused("SELECT id FROM t ORDER BY id USE VECTOR EXACT LIMIT 3"), - Error::UseVectorRequiresVectorOrder - )); - for sql in [ - "SELECT id FROM t ORDER BY v <=> $q DESC LIMIT 3", - "SELECT id FROM t ORDER BY v <=> $q, id LIMIT 3", - "SELECT id FROM t ORDER BY $q <=> v LIMIT 3", - "SELECT id FROM t WHERE v <=> $q < 0.5", - "SELECT id, v <=> $q AS distance FROM t", - "SELECT id, v <=> $q AS distance FROM t ORDER BY id LIMIT 3", - ] { - match refused(sql) { - Error::PlanError(text) => assert!(text.contains("<=>"), "{sql}: {text}"), - other => panic!("{sql}\nwas refused as {other:?}"), - } - } -} - -#[test] -fn a_row_value_and_any_right_side_of_a_distance_are_read_and_refused_when_planned() { - // Each is read by the parser, and refused by the planner in a sentence that names it. - // The refusal of ROW_VECTOR(...) names the function and the `<=>` it stands beside. - let names: [(&str, &[&str]); 4] = [ - ("SELECT id FROM t WHERE (a, b) = (1, 2)", &["row value"]), - ( - "SELECT id FROM t WHERE (a, b) IN ((1, 2, 3))", - &["row value"], - ), - ("SELECT id FROM t ORDER BY v <=> w LIMIT 3", &["<=>"]), - ( - "SELECT id FROM t ORDER BY v <=> ROW_VECTOR('t', 'v', 1) LIMIT 3", - &["<=>", "row_vector"], - ), - ]; - for (sql, names) in names { - let read = parse(sql).unwrap_or_else(|error| panic!("{sql}\nwas not read: {error:?}")); - match plan(&read) { - Err(Error::PlanError(text)) => { - for name in names { - assert!(text.to_lowercase().contains(name), "{sql}: {text}"); - } - } - other => panic!("{sql}\nwas planned as {other:?}"), - } - } -} - -#[test] -fn the_clauses_of_a_vector_column_and_in_lists_are_read() { - let Statement::CreateTable(table) = parse( - "CREATE TABLE t (id INTEGER PRIMARY KEY, ctx TEXT NOT NULL, kind INT NOT NULL, \ - plain VECTOR(3), v VECTOR(4) PARTITION_KEY (ctx, kind) MAX_PARTITIONS 8 \ - SEARCH_MODE EXACT NOT NULL, w VECTOR(2) partition_key (ctx) max_partitions -1, \ - x VECTOR(2) SEARCH_MODE indexed)", - ) - .unwrap() else { - panic!("not a CREATE TABLE"); - }; - let clauses: Vec<&VectorClauses> = table.columns.iter().map(|column| &column.vector).collect(); - let keyed = |key: &[&str], max: Option<&str>, mode: Option| VectorClauses { - partition_key: key.iter().map(|column| (*column).to_owned()).collect(), - max_partitions: max.map(str::to_owned), - search_mode: mode, - ..VectorClauses::default() - }; - let none = VectorClauses::default(); - assert_eq!( - clauses, - [ - &none, - &none, - &none, - &none, - &keyed(&["ctx", "kind"], Some("8"), Some(VectorSearchMode::Exact)), - // The number is kept as it was written: it is `schema` that judges it. - &keyed(&["ctx"], Some("-1"), None), - &keyed(&[], None, Some(VectorSearchMode::Indexed)), - ] - ); - assert_eq!(table.columns[4].data_type, DataType::Vector(4)); - assert!(!table.columns[4].nullable && table.columns[3].nullable); - - // IN and NOT IN over a list, and over a list of row values. - let filter = |sql: &str| { - let read = select(&format!("SELECT id FROM t WHERE {sql}")); - read.where_clause.expect("a WHERE") - }; - assert!(matches!( - filter("a IN (1, 2, $p)"), - Expr::InList { expr, list, negated: false } - if matches!(&*expr, Expr::Column(_)) && list.len() == 3 - )); - assert!(matches!( - filter("a not in ('x')"), - Expr::InList { list, negated: true, .. } if list.len() == 1 - )); - assert!(matches!( - filter("(a, b) IN ((1, 'x'), (2, 'y'))"), - Expr::InList { expr, list, negated: false } - if matches!(&*expr, Expr::Row(row) if row.len() == 2) - && list.len() == 2 - && list.iter().all(|item| matches!(item, Expr::Row(row) if row.len() == 2)) - )); - // A list is an operand of AND and OR like any comparison. - assert!(matches!( - filter("a IN (1, 2) AND NOT b IN (3) OR c = 4"), - Expr::BinaryOp { op: BinOp::Or, .. } - )); -} - #[test] fn ten_thousand_operands_of_and_and_or_are_read_in_the_order_written() { /// The numbers the comparisons of a tree of ANDs and ORs hold, from left to right. @@ -565,107 +134,9 @@ fn ten_thousand_operands_of_and_and_or_are_read_in_the_order_written() { "SELECT id FROM t WHERE {}", operands.join(&format!(" {operator} ")) ); - let filter = select(&sql).where_clause.expect("a WHERE"); + let filter = select(&sql).filter.expect("a WHERE"); let mut found = Vec::new(); numbers(&filter, &mut found); assert!(found.iter().copied().eq(0..10_000), "{operator}"); } } - -#[test] -fn the_index_clauses_of_a_vector_column_are_read_as_written() { - let Statement::CreateTable(table) = parse( - "CREATE TABLE t (id INTEGER PRIMARY KEY, \ - a VECTOR(4) WITH (quantization = 'sq8') PARTITION_KEY (id) MAX_PARTITIONS 2 \ - SEARCH_MODE AUTO AUTO_INDEX_AT -5 \ - CONSOLIDATION (TOMBSTONE_PERCENT = 0, CHANGE_PERCENT = 101), \ - b VECTOR(4) auto_index_at 18446744073709551616 consolidation none, \ - c VECTOR(4) CONSOLIDATION (CHANGE_PERCENT = 7))", - ) - .unwrap() else { - panic!("not a CREATE TABLE"); - }; - // Every number and the quantization's text are kept as written: `schema` judges them. - let written = |text: &str| Some(text.to_owned()); - let wanted = [ - VectorClauses::default(), - VectorClauses { - partition_key: vec!["id".to_owned()], - max_partitions: written("2"), - search_mode: Some(VectorSearchMode::Auto), - auto_index_at: written("-5"), - consolidation: Some(ConsolidationClause::Percent { - change: written("101"), - tombstone: written("0"), - }), - quantization: written("sq8"), - }, - VectorClauses { - auto_index_at: written("18446744073709551616"), - consolidation: Some(ConsolidationClause::None), - ..VectorClauses::default() - }, - VectorClauses { - consolidation: Some(ConsolidationClause::Percent { - change: written("7"), - tombstone: None, - }), - ..VectorClauses::default() - }, - ]; - let read: Vec = table.columns.into_iter().map(|c| c.vector).collect(); - assert_eq!(read, wanted); - - // The clauses stand in one order, and a CONSOLIDATION list names one or both of its two - // members, each once. - for clauses in [ - "AUTO_INDEX_AT 5 SEARCH_MODE AUTO", - "CONSOLIDATION NONE AUTO_INDEX_AT 5", - "SEARCH_MODE AUTO WITH (quantization = 'SQ8')", - "CONSOLIDATION ()", - "CONSOLIDATION (CHANGE_PERCENT = 1, CHANGE_PERCENT = 2)", - "CONSOLIDATION (PROBES = 1)", - "AUTO_INDEX_AT", - ] { - refusal(&format!( - "CREATE TABLE t (id INTEGER PRIMARY KEY, v VECTOR(4) {clauses})" - )); - } -} - -#[test] -fn the_inspection_statements_are_planned_as_reads() { - assert!(matches!( - planned("show vector_indexes"), - PhysicalPlan::ShowVectorIndexes - )); - let partitions = |sql: &str| match planned(sql) { - PhysicalPlan::ShowVectorPartitions { - column, - limit, - offset, - } => (column, limit, offset), - other => panic!("{sql}\nwas planned as {other:?}"), - }; - let docs_v = Some(("docs".to_owned(), "v".to_owned())); - assert_eq!(partitions("SHOW VECTOR_PARTITIONS"), (None, None, 0)); - assert_eq!( - partitions("show vector_partitions for docs.v"), - (docs_v.clone(), None, 0) - ); - assert_eq!( - partitions("SHOW VECTOR_PARTITIONS LIMIT 3"), - (None, Some(3), 0) - ); - assert_eq!( - partitions("SHOW VECTOR_PARTITIONS FOR docs.v LIMIT 5 OFFSET 2"), - (docs_v, Some(5), 2) - ); - for sql in ["SHOW VECTOR_INDEXES", "SHOW VECTOR_PARTITIONS LIMIT 1"] { - assert_eq!(planned(sql).effect(), Effect::Reads, "{sql}"); - } - // OFFSET stands only after LIMIT, and FOR names a table and a column. - refusal("SHOW VECTOR_PARTITIONS OFFSET 2"); - refusal("SHOW VECTOR_PARTITIONS FOR docs"); - refusal("SHOW VECTOR_INDEXES FOR docs.v"); -} diff --git a/v2/contextdb/src/sql/plan.rs b/v2/contextdb/src/sql/plan.rs index f92ee02c6..576e6d452 100644 --- a/v2/contextdb/src/sql/plan.rs +++ b/v2/contextdb/src/sql/plan.rs @@ -3,69 +3,15 @@ /// A declaration or a write is planned as it was written: `schema` and `write` judge every /// clause of it. pub use super::ast::{ - AlterTable as AlterTablePlan, CreateIndex as CreateIndexPlan, CreateTable as CreateTablePlan, - Delete as DeletePlan, DropIndex as DropIndexPlan, DropTable as DropTablePlan, - Insert as InsertPlan, Update as UpdatePlan, + CreateIndex as CreateIndexPlan, CreateTable as CreateTablePlan, Insert as InsertPlan, }; -use super::ast::{Expr, SetMemoryLimitValue, SortDirection, VectorSearchMode}; - -#[derive(Debug, Clone)] -pub enum PhysicalPlan { - CreateTable(CreateTablePlan), - CreateIndex(CreateIndexPlan), - AlterTable(AlterTablePlan), - DropTable(DropTablePlan), - DropIndex(DropIndexPlan), - Insert(InsertPlan), - Delete(DeletePlan), - Update(UpdatePlan), - /// Every row of a table that passes the filter. `query` chooses how to reach them. - Scan { - table: String, - filter: Option, - }, - Sort { - input: Box, - keys: Vec, - }, - Project { - input: Box, - columns: Vec, - }, - Limit { - input: Box, - count: u64, - }, - /// The `k` rows of a table that pass the filter and lie nearest `query` by cosine distance - /// in a VECTOR column, nearest first. `query` decides which partitions the filter selects - /// and the vector part finds the rows. It stands where `Sort` over `Scan` stands in other - /// plans; its LIMIT is `k`, so no `Limit` wraps it. A `Project` over it may hold the - /// statement's distance expression, `column <=> query`, any number of times: each stands - /// for the distance the search found for the row. - VectorSearch { - table: String, - /// The VECTOR column on the left of `<=>`. - column: String, - /// The right of `<=>`. - query: Expr, - k: u64, - filter: Option, - /// What `USE VECTOR` asked for; `None` leaves it to the column's declaration. - mode: Option, - }, - SetMemoryLimit(SetMemoryLimitValue), - ShowMemoryLimit, - /// `SHOW VECTOR_INDEXES`: one row for each VECTOR column of the store. - ShowVectorIndexes, - /// `SHOW VECTOR_PARTITIONS [FOR table.column] [LIMIT count [OFFSET start]]`: one row for - /// each partition, of the named column or of every VECTOR column. - ShowVectorPartitions { - /// The table and column after `FOR`. - column: Option<(String, String)>, - limit: Option, - offset: u64, - }, -} +/// A SELECT, a select item, a sort key and a table or graph pattern of FROM are planned as +/// they were written too. +pub use super::ast::{ + EdgeDirection, EdgeStep, FromItem, GraphTable, NodePattern, OrderByItem as SortKey, + Select as SelectPlan, SelectColumn as ProjectColumn, +}; +use super::ast::{Expr, SetMemoryLimitValue, Statement}; /// What a planned statement does to the store. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -81,31 +27,28 @@ pub(crate) enum Effect { Reads, } -impl PhysicalPlan { +impl Statement { /// Which of these this statement is. A new kind of plan is given its answer here, in the /// one place every part asks. pub(crate) fn effect(&self) -> Effect { match self { - PhysicalPlan::CreateTable(_) - | PhysicalPlan::CreateIndex(_) - | PhysicalPlan::AlterTable(_) - | PhysicalPlan::DropTable(_) - | PhysicalPlan::DropIndex(_) => Effect::Declares, - PhysicalPlan::Insert(_) | PhysicalPlan::Delete(_) | PhysicalPlan::Update(_) => { + Statement::CreateTable(_) + | Statement::CreateIndex(_) + | Statement::AlterTable(_) + | Statement::DropTable(_) + | Statement::DropIndex(_) => Effect::Declares, + Statement::Insert(_) | Statement::Delete(_) | Statement::Update(_) => { Effect::WritesRows } - PhysicalPlan::SetMemoryLimit(SetMemoryLimitValue::Bytes(bytes)) => { + Statement::SetMemoryLimit(SetMemoryLimitValue::Bytes(bytes)) => { Effect::Sets(Some(*bytes as u64)) } - PhysicalPlan::SetMemoryLimit(SetMemoryLimitValue::None) => Effect::Sets(None), - PhysicalPlan::Scan { .. } - | PhysicalPlan::Sort { .. } - | PhysicalPlan::Project { .. } - | PhysicalPlan::Limit { .. } - | PhysicalPlan::VectorSearch { .. } - | PhysicalPlan::ShowMemoryLimit - | PhysicalPlan::ShowVectorIndexes - | PhysicalPlan::ShowVectorPartitions { .. } => Effect::Reads, + Statement::SetMemoryLimit(SetMemoryLimitValue::None) => Effect::Sets(None), + Statement::Select(_) + | Statement::ShowMemoryLimit + | Statement::ShowVectorIndexes + | Statement::Explain(_) + | Statement::ShowVectorPartitions { .. } => Effect::Reads, } } @@ -113,27 +56,35 @@ impl PhysicalPlan { /// declares, sets or reads holds for every Context, label and principal at once. pub(crate) fn admin_only(&self) -> Option<&'static str> { Some(match self { - PhysicalPlan::CreateTable(_) => "CREATE TABLE", - PhysicalPlan::CreateIndex(_) => "CREATE INDEX", - PhysicalPlan::AlterTable(_) => "ALTER TABLE", - PhysicalPlan::DropTable(_) => "DROP TABLE", - PhysicalPlan::DropIndex(_) => "DROP INDEX", - PhysicalPlan::SetMemoryLimit(_) => "SET MEMORY_LIMIT", - PhysicalPlan::ShowVectorIndexes => "SHOW VECTOR_INDEXES", - PhysicalPlan::ShowVectorPartitions { .. } => "SHOW VECTOR_PARTITIONS", + Statement::CreateTable(_) => "CREATE TABLE", + Statement::CreateIndex(_) => "CREATE INDEX", + Statement::AlterTable(_) => "ALTER TABLE", + Statement::DropTable(_) => "DROP TABLE", + Statement::DropIndex(_) => "DROP INDEX", + Statement::SetMemoryLimit(_) => "SET MEMORY_LIMIT", + Statement::ShowVectorIndexes => "SHOW VECTOR_INDEXES", + Statement::ShowVectorPartitions { .. } => "SHOW VECTOR_PARTITIONS", _ => return None, }) } -} - -#[derive(Debug, Clone)] -pub struct ProjectColumn { - pub expr: Expr, - pub alias: Option, -} -#[derive(Debug, Clone)] -pub struct SortKey { - pub expr: Expr, - pub direction: SortDirection, + /// The table an INSERT, UPDATE or DELETE names and every expression it holds: the VALUES, + /// then the assignments of `ON CONFLICT`; the SET values, then WHERE; WHERE. `None` for + /// any other statement. + pub(crate) fn written(&self) -> Option<(&String, Vec<&Expr>)> { + Some(match self { + Statement::Insert(insert) => { + let conflict = insert.on_conflict.iter().flat_map(|on| &on.assignments); + let values = insert.values.iter().flatten(); + let written = values.chain(conflict.map(|(_, value)| value)); + (&insert.table, written.collect()) + } + Statement::Update(update) => { + let set = update.assignments.iter().map(|(_, value)| value); + (&update.table, set.chain(&update.where_clause).collect()) + } + Statement::Delete(delete) => (&delete.table, delete.where_clause.iter().collect()), + _ => return None, + }) + } } diff --git a/v2/contextdb/src/sql/planner.rs b/v2/contextdb/src/sql/planner.rs index b6ba85c3d..9eb30c376 100644 --- a/v2/contextdb/src/sql/planner.rs +++ b/v2/contextdb/src/sql/planner.rs @@ -1,311 +1,194 @@ -//! Turns a parsed statement into the plan that `schema`, `write` and `query` take. +//! Refuses what no table could make right; a statement that passes is its own plan. //! //! The planner is a set of fixed rules over the statement alone. It knows no table, so it -//! chooses no index: a SELECT's plan names the table to read and the filter to apply, and -//! `query` decides how to reach the rows. +//! chooses no index, no join order and no search: a SELECT's plan says what was written, and +//! `query` decides how to answer it. -use super::ast::{ColumnRef, Expr, Literal, Select, SelectColumn, SortDirection, Statement}; -use super::not_supported; -use super::plan::*; +use super::ast::{BinOp, Expr, Literal, OrderByItem, Select, SortDirection::Asc, Statement}; +use super::{not_carried, not_supported}; use crate::types::{Error, Result}; -/// The functions an ORDER BY key may call: the ones `query` works out for every row. The four -/// `__` names are what the parser makes of `+`, `-`, `*` and `/`. -const SORTABLE_FUNCTIONS: [&str; 6] = ["__add", "__sub", "__mul", "__div", "coalesce", "now"]; +/// The functions that work one value out of many rows, in the order `query` names them. +pub(crate) const AGGREGATES: [&str; 5] = ["count", "sum", "min", "max", "avg"]; -pub(super) fn plan(statement: &Statement) -> Result { - Ok(match statement { - Statement::CreateTable(table) => PhysicalPlan::CreateTable(table.clone()), - Statement::CreateIndex(index) => PhysicalPlan::CreateIndex(index.clone()), - Statement::AlterTable(alter) => PhysicalPlan::AlterTable(alter.clone()), - Statement::DropTable(drop) => PhysicalPlan::DropTable(drop.clone()), - Statement::DropIndex(drop) => PhysicalPlan::DropIndex(drop.clone()), +/// Refuses a form of `statement`, or of a statement inside it, that is refused whatever the +/// tables hold. +pub(super) fn stands(statement: &Statement) -> Result<()> { + match statement { Statement::Insert(insert) => { - insert.values.iter().flatten().try_for_each(rows_stand)?; + insert.values.iter().flatten().try_for_each(forms_stand)?; let conflict = insert.on_conflict.iter(); let mut set = conflict.flat_map(|conflict| conflict.assignments.iter()); - set.try_for_each(|(_, value)| in_a_write(value))?; - PhysicalPlan::Insert(insert.clone()) + set.try_for_each(|(_, value)| in_a_write(value)) } - Statement::Delete(delete) => { - delete.where_clause.iter().try_for_each(in_a_write)?; - PhysicalPlan::Delete(delete.clone()) + Statement::Delete(_) | Statement::Update(_) => { + let (_, written) = statement.written().expect("an UPDATE or DELETE"); + written.into_iter().try_for_each(in_a_write) } - Statement::Update(update) => { - let values = update.assignments.iter().map(|(_, value)| value); - let mut written = values.chain(&update.where_clause); - written.try_for_each(in_a_write)?; - PhysicalPlan::Update(update.clone()) - } - Statement::Select(select) => plan_select(select)?, - Statement::SetMemoryLimit(limit) => PhysicalPlan::SetMemoryLimit(limit.clone()), - Statement::ShowMemoryLimit => PhysicalPlan::ShowMemoryLimit, - Statement::ShowVectorIndexes => PhysicalPlan::ShowVectorIndexes, - Statement::ShowVectorPartitions { - column, - limit, - offset, - } => PhysicalPlan::ShowVectorPartitions { - column: column.clone(), - limit: *limit, - offset: *offset, - }, - }) + Statement::Select(select) => select_stands(select), + Statement::Explain(statement) => stands(statement), + _ => Ok(()), + } } -/// A scan with its filter, sorted, then projected unless the statement is `SELECT *`, then cut -/// to the limit. A similarity search stands where the scan, the sort and the limit would. -fn plan_select(select: &Select) -> Result { - let written = select.columns.iter().map(|column| &column.expr); - let written = written.chain(&select.where_clause); - let written = written.chain(select.order_by.iter().map(|item| &item.expr)); - let written: Vec<&Expr> = written.collect(); - written.iter().copied().try_for_each(rows_stand)?; - let keys: Vec = select - .order_by - .iter() - .map(|item| SortKey { - expr: resolve_output_alias(&item.expr, &select.columns), - direction: item.direction, - }) - .collect(); - // A distance among several ORDER BY items is a search of a later version. - let distance = |key: &SortKey| matches!(key.expr, Expr::Distance { .. }); - if keys.len() > 1 && keys.iter().any(distance) { - return Err(not_supported("ORDER BY <=> with a second sort key")); +/// Refuses a form of the SELECT, or of a SELECT inside it, that is refused whatever the tables +/// hold. +fn select_stands(select: &Select) -> Result<()> { + let on = select.joins.iter().filter_map(|join| join.on.as_ref()); + let before_groups = on.chain(&select.filter).chain(&select.group_by); + let after_groups = select.columns.iter().map(|column| &column.expr); + let after_groups = after_groups.chain(select.order_by.iter().map(|item| &item.expr)); + for expr in before_groups.clone() { + calls_stand(expr, false)?; } - // A similarity search: the one ORDER BY item is a distance. - let mut search = None; - if let [key] = keys.as_slice() - && let Expr::Distance { left, right } = &key.expr - { - search = Some(plan_search(select, left, right, key)?); + let mut having = select.having.iter(); + having.try_for_each(|expr| calls_stand(expr, true))?; + let mut written = before_groups.chain(&select.having).chain(after_groups); + written.try_for_each(forms_stand)?; + let order_by = select.order_by.as_slice(); + let distance = |key: &OrderByItem| matches!(key.expr, Expr::Distance { .. }); + if select.use_vector.is_some() && !order_by.iter().any(distance) { + return Err(Error::UseVectorRequiresVectorOrder); } - let searching = search.is_some(); - let mut current = match search { - Some(search) => search, - None => { - if select.use_vector.is_some() { - return Err(Error::UseVectorRequiresVectorOrder); - } - for expr in written { - distances(expr, &mut |_, _| { - Err(not_supported( - "<=> anywhere but as the one ORDER BY item of a SELECT with LIMIT, and in \ - that SELECT's select list,", - )) - })?; - } - // A key `query` cannot work out for every row is refused here: sorting by it would - // treat every row as equal and hand the rows back unsorted. - let sortable = |key: &SortKey| match &key.expr { - Expr::Column(_) => true, - Expr::FunctionCall { name, .. } => SORTABLE_FUNCTIONS - .iter() - .any(|known| name.eq_ignore_ascii_case(known)), - _ => false, - }; - if !keys.iter().all(sortable) { - return Err(Error::OrderByExpressionNotSupported); - } - let scan = PhysicalPlan::Scan { - table: select.table.clone(), - filter: select.where_clause.clone(), - }; - if keys.is_empty() { - scan - } else { - PhysicalPlan::Sort { - input: Box::new(scan), - keys, - } - } + // A rank orders the rows of one search: its one sort key is the distance, nearest first. + if select.use_rank.is_some() { + if !matches!(order_by, [key] if distance(key) && key.direction == Asc) { + return Err(Error::UseRankRequiresVectorOrder); + } + if select.limit.is_none() && select.limit_name.is_none() { + return Err(Error::UseRankRequiresLimit); } - }; - let star = matches!( - select.columns.as_slice(), - [SelectColumn { expr: Expr::Column(ColumnRef { table: None, column }), alias: None }] - if column == "*" - ); - if !star { - current = PhysicalPlan::Project { - input: Box::new(current), - columns: select - .columns - .iter() - .map(|column| ProjectColumn { - expr: column.expr.clone(), - alias: column.alias.clone(), - }) - .collect(), - }; - } - if let (Some(count), false) = (select.limit, searching) { - current = PhysicalPlan::Limit { - input: Box::new(current), - count, - }; } - Ok(current) + let named = select.with.iter().map(|(_, select)| select); + let mut inner = named.chain(select.union.iter().map(|(_, select)| select)); + inner.try_for_each(select_stands) } -/// Reads a bare ORDER BY name as a select-list alias first, as standard SQL does. The sort runs -/// below the projection, where an alias does not exist yet, so the aliased expression is sorted -/// by in its place. A qualified name is a table's column and is left alone. -fn resolve_output_alias(expr: &Expr, columns: &[SelectColumn]) -> Expr { - let aliased = match expr { - Expr::Column(ColumnRef { - table: None, - column, - }) => columns - .iter() - .find(|select| select.alias.as_deref() == Some(column.as_str())), +/// Refuses a window, and an aggregate unless `grouped`, in a clause that is worked out before +/// the rows are grouped (JOIN ... ON, WHERE, GROUP BY) or, for a window, before they are numbered +/// (HAVING). +fn calls_stand(expr: &Expr, grouped: bool) -> Result<()> { + let refused = match expr { + Expr::RowNumber { .. } => Some("ROW_NUMBER() OVER"), + Expr::FunctionCall { name, .. } if !grouped => AGGREGATES + .into_iter() + .find(|known| name.eq_ignore_ascii_case(known)), _ => None, }; - aliased.map_or_else(|| expr.clone(), |select| select.expr.clone()) -} - -/// The search a SELECT asks for when its one ORDER BY item is `left <=> right`: the rows nearest -/// `right` in the column `left`. Refuses the forms of a search, and of a distance beside it, -/// that a later version reads. -fn plan_search(select: &Select, left: &Expr, right: &Expr, key: &SortKey) -> Result { - let Some(k) = select.limit else { - return Err(not_supported("a vector search without LIMIT")); - }; - if key.direction == SortDirection::Desc { - return Err(not_supported("ORDER BY <=> DESC")); - } - let Some(column) = searched_column(select, left)? else { - // No search: the statement is the sort it is written as, which `query` refuses by the - // column's name once it has found the table. - let (table, filter, keys) = (select.table.clone(), None, vec![key.clone()]); - let input = Box::new(PhysicalPlan::Scan { table, filter }); - return Ok(PhysicalPlan::Sort { input, keys }); - }; - match right { - Expr::Parameter(_) | Expr::Literal(Literal::Text(_) | Literal::Vector(_)) => {} - // `+` and its like are calls too, under names no statement writes. - Expr::FunctionCall { name, .. } if !name.starts_with("__") => { - let what = format!("<=> with the function {name} on its right"); - return Err(not_supported(&what)); - } - _ => { - return Err(not_supported( - "<=> with anything but a vector literal, its quoted text or a $name on its right", - )); - } - } - if let Some(filter) = &select.where_clause { - distances(filter, &mut |_, _| Err(not_supported("<=> in WHERE")))?; - } - for item in &select.columns { - distances(&item.expr, &mut |other: &Expr, vector: &Expr| { - let Some(other) = searched_column(select, other)? else { - return Ok(()); - }; - if other == column && same_vector(vector, right) { - return Ok(()); - } - Err(not_supported(&format!( - "<=> on the column {other} in the select list, where it is not the distance the \ - search is ordered by," - ))) - })?; - } - Ok(PhysicalPlan::VectorSearch { - table: select.table.clone(), - column: column.to_owned(), - query: right.clone(), - k, - filter: select.where_clause.clone(), - mode: select.use_vector, - }) -} - -/// The column on the left of a distance: a column of the statement's table, by its name alone or -/// with the table's before it. `None` under the name of any other table: `query` says that it -/// is not found, as it does anywhere else in the statement, after it has found the table. -fn searched_column<'a>(select: &Select, left: &'a Expr) -> Result> { - match left { - Expr::Column(ColumnRef { table, column }) - if table.as_ref().is_none_or(|table| *table == select.table) => - { - Ok(Some(column.as_str())) - } - Expr::Column(_) => Ok(None), - _ => Err(not_supported( - "<=> with anything but a column of the table on its left", - )), + if let Some(name) = refused { + return Err(Error::PlanError(format!( + "{name} stands only in a select list, in ORDER BY or, for an aggregate, in HAVING" + ))); } + let mut inner = inside(expr).into_iter(); + inner.try_for_each(|inner| calls_stand(inner, grouped)) } -/// Whether two right sides of `<=>` are written the same: the same `$name`, the same quoted text -/// or the same vector literal. -fn same_vector(one: &Expr, other: &Expr) -> bool { - match (one, other) { - (Expr::Parameter(one), Expr::Parameter(other)) => one == other, - (Expr::Literal(Literal::Text(one)), Expr::Literal(Literal::Text(other))) => one == other, - (Expr::Literal(Literal::Vector(one)), Expr::Literal(Literal::Vector(other))) => { - one == other +/// Writes `$name`, which gives the expressions directly inside an expression, as `&` or, with +/// `mut`, as `&mut` references. A SELECT inside an expression is a statement of its own. +macro_rules! inside { + ($name:ident, $iter:ident $(, $mut:tt)?) => { + pub(crate) fn $name(expr: &$($mut)? Expr) -> Vec<&$($mut)? Expr> { + match expr { + Expr::Column(_) | Expr::Literal(_) | Expr::Parameter(_) | Expr::Subquery(_) => { + Vec::new() + } + Expr::BinaryOp { left, right, .. } + | Expr::Distance { left, right } + | Expr::Like { expr: left, pattern: right, .. } + | Expr::Field { json: left, key: right, .. } => { + vec![&$($mut)? **left, &$($mut)? **right] + } + Expr::UnaryOp { operand: inner, .. } + | Expr::IsNull { expr: inner, .. } + | Expr::InSubquery { expr: inner, .. } => vec![&$($mut)? **inner], + Expr::FunctionCall { args: items, .. } | Expr::Row(items) => { + items.$iter().collect() + } + Expr::InList { expr, list, .. } => { + std::iter::once(&$($mut)? **expr).chain(list).collect() + } + Expr::Between { expr, low, high, .. } => { + vec![&$($mut)? **expr, &$($mut)? **low, &$($mut)? **high] + } + Expr::RowNumber { partition_by, order_by } => { + let order = order_by.$iter().map(|key| &$($mut)? key.expr); + partition_by.$iter().chain(order).collect() + } + } } - _ => false, - } + }; } +inside!(inside, iter); +inside!(inside_mut, iter_mut, mut); -/// The expressions directly inside `expr`. -fn inside(expr: &Expr) -> Vec<&Expr> { - match expr { - Expr::Column(_) | Expr::Literal(_) | Expr::Parameter(_) => Vec::new(), - Expr::BinaryOp { left, right, .. } | Expr::Distance { left, right } => { - vec![&**left, &**right] - } - Expr::UnaryOp { operand: inner, .. } | Expr::IsNull { expr: inner, .. } => vec![&**inner], - Expr::FunctionCall { args: items, .. } | Expr::Row(items) => items.iter().collect(), - Expr::InList { expr, list, .. } => std::iter::once(&**expr).chain(list).collect(), +/// What an expression of an UPDATE or DELETE must pass: [`forms_stand`], and no distance, which +/// a write does not carry. Refused here, the statement is refused whatever its table holds. +fn in_a_write(expr: &Expr) -> Result<()> { + fn distance(expr: &Expr) -> bool { + matches!(expr, Expr::Distance { .. }) || inside(expr).into_iter().any(distance) } -} - -/// Hands `each` the left and right side of every distance written in `expr`, at any depth. -fn distances(expr: &Expr, each: &mut dyn FnMut(&Expr, &Expr) -> Result<()>) -> Result<()> { - if let Expr::Distance { left, right } = expr { - each(left, right)?; + forms_stand(expr)?; + match distance(expr) { + true => Err(not_supported("<=> in an UPDATE or DELETE")), + false => Ok(()), } - inside(expr) - .into_iter() - .try_for_each(|inner| distances(inner, each)) -} - -/// What an expression of an UPDATE or DELETE must pass: [`rows_stand`], and no distance, which -/// only a search gives a row. Refused here, the statement is refused whatever its table holds. -fn in_a_write(expr: &Expr) -> Result<()> { - rows_stand(expr)?; - distances(expr, &mut |_, _| { - Err(not_supported("<=> in an UPDATE or DELETE")) - }) } -/// Refuses a row value that stands anywhere but on either side of `IN`, and one beside `IN` -/// that has another number of values than its partner. -fn rows_stand(expr: &Expr) -> Result<()> { +/// Refuses what is refused whatever the tables hold: a row value that stands anywhere but on +/// either side of `=`, `<>` and `IN`, one there that has another number of values than its +/// partner, a quoted text there that is no JSON beside a JSON field, which reads it as JSON, +/// and ROW_VECTOR, which no version has. A SELECT inside the expression is checked as the +/// statement it is. +fn forms_stand(expr: &Expr) -> Result<()> { let (left, list) = match expr { - Expr::InList { expr, list, .. } => (&**expr, list), - Expr::Row(_) => return Err(not_supported("a row value anywhere but beside IN")), - _ => return inside(expr).into_iter().try_for_each(rows_stand), + Expr::InList { expr, list, .. } => (&**expr, list.as_slice()), + Expr::BinaryOp { + left, + op: BinOp::Eq | BinOp::Neq, + right, + } => (&**left, std::slice::from_ref(&**right)), + Expr::Row(_) => { + return Err(not_supported( + "a row value anywhere but beside =, <> and IN", + )); + } + Expr::InSubquery { expr, query, .. } => { + select_stands(query)?; + return forms_stand(expr); + } + Expr::Subquery(query) => return select_stands(query), + Expr::FunctionCall { name, .. } if name.eq_ignore_ascii_case("row_vector") => { + let instead = "a scalar subquery supplies another row's vector"; + return Err(not_carried(&format!("{name}(...) beside <=>"), instead)); + } + _ => return inside(expr).into_iter().try_for_each(forms_stand), }; - let width = |side: &Expr| match side { - Expr::Row(values) => values.len(), - _ => 1, + // A quoted text that is no JSON, compared with a JSON field. + let word = |one: &Expr, other: &Expr| match (one, other) { + (Expr::Field { as_text: false, .. }, Expr::Literal(Literal::Text(text))) => { + let json = serde_json::from_str::(text); + json.is_err().then(|| text.clone()) + } + _ => None, }; for side in std::iter::once(left).chain(list) { - if width(side) != width(left) { + if let Some(text) = word(left, side).or_else(|| word(side, left)) { + let string = serde_json::Value::from(text.as_str()); + return Err(Error::PlanError(format!( + "'{text}' is compared with a JSON field, which reads it as JSON, and it is no \ + JSON: write '{string}' for the string" + ))); + } + if side.sides().len() != left.sides().len() { return Err(Error::PlanError( - "a row value beside IN must have as many values as its partner".to_owned(), + "a row value must have as many values as its partner".to_owned(), )); } // What a side holds is checked as any expression is: a row value holds no row value. match side { - Expr::Row(values) => values.iter().try_for_each(rows_stand)?, - _ => rows_stand(side)?, + Expr::Row(values) => values.iter().try_for_each(forms_stand)?, + _ => forms_stand(side)?, } } Ok(()) diff --git a/v2/contextdb/src/store/counts.rs b/v2/contextdb/src/store/counts.rs index 5392045bb..cd781fcf8 100644 --- a/v2/contextdb/src/store/counts.rs +++ b/v2/contextdb/src/store/counts.rs @@ -2,13 +2,11 @@ //! values as a key, holding how many rows the group has. A count that reaches zero has no //! record. -use std::cmp::Ordering; - use redb::{ReadableTable, Table}; use super::disk::{Stored, unsound}; use super::keys::{Span, stored}; -use super::{ChangeSet, CountId, KeptIter, Key, Staged, Undo, staged_in}; +use super::{ChangeSet, CountId, KeptIter, Key, Staged, Undo, overlay, staged_in}; use crate::types::Result; impl ChangeSet { @@ -38,29 +36,12 @@ pub(super) fn kept<'a>( count: CountId, span: &Span, ) -> Result> { - let mut stored = changes.base.moment.kept(count.0, span)?.peekable(); - let mut staged = staged_in(&changes.kept, count.0, span.clone()).peekable(); - Ok(Box::new(std::iter::from_fn(move || { - loop { - let stored_is = match (stored.peek(), staged.peek()) { - (None, None) => return None, - (Some(Ok((key, _))), Some((staged_key, _))) => key.cmp(staged_key), - // A failed read, or nothing staged from here on. - (Some(_), _) => Ordering::Less, - (None, Some(_)) => Ordering::Greater, - }; - let before = match stored_is { - Ordering::Less => return stored.next(), - Ordering::Equal => stored.next()?.map_or(0, |(_, count)| count), - Ordering::Greater => 0, - }; - let (key, change) = staged.next()?; - match before.saturating_add_signed(*change) { - 0 => {} - count => return Some(Ok((key.clone(), count))), - } - } - }))) + let stored = changes.base.moment.kept(count.0, span)?; + let staged = staged_in(&changes.kept, count.0, span.clone()); + let laid = |before: Option, change: &i64| { + Some(before.unwrap_or(0).saturating_add_signed(*change)).filter(|&count| count != 0) + }; + Ok(overlay(stored, staged, laid)) } /// Writes a commit's changes to the kept counts. diff --git a/v2/contextdb/src/store/disk.rs b/v2/contextdb/src/store/disk.rs index 9ea725ffa..db1af3cf6 100644 --- a/v2/contextdb/src/store/disk.rs +++ b/v2/contextdb/src/store/disk.rs @@ -21,8 +21,8 @@ use redb::{ReadOnlyTable, ReadTransaction, ReadableDatabase, ReadableTable, Tabl use super::folder::Hold; use super::keys::{self, Span, stored}; use super::{ - Beside, ChangeSet, CountId, EntryIter, IndexId, Joined, KeptIter, Key, Read, Row, RowIter, - TableId, View, + Beside, ChangeSet, CountId, EntryIter, IndexId, Joined, KeptIter, Key, Keys, Read, Row, + RowIter, TableId, View, }; use super::{VectorNumber, VectorRecord}; use super::{counts, drop, record, split}; @@ -216,14 +216,14 @@ impl Moment { } /// The records of one table, index or count inside a span, in key order, each read with - /// `read` from its key and its value. + /// `read` from its key and its value, both lent. fn scan( &self, table: &ReadOnlyTable<&'static [u8], &'static [u8]>, id: u32, (start, end): &Span, read: F, - ) -> Result> + use> + ) -> Result> + use> where F: Fn(&[u8], &[u8]) -> Option, { @@ -236,9 +236,7 @@ impl Moment { .next_lent() .map_err(|error| failed(&folder, "read", error)); Some(entry.transpose()?.and_then(|(key, record)| { - let read = read(&key[4..], record); - let read = read.ok_or_else(|| failed(&folder, "read", unsound()))?; - Ok((Key(key[4..].to_vec()), read)) + read(&key[4..], record).ok_or_else(|| failed(&folder, "read", unsound())) })) })) } @@ -249,10 +247,9 @@ impl Moment { table: u32, span: &Span, ) -> Result> + use<>> { - self.scan(&self.rows, table, span, |_, row| { - Some(Row { - cells: record::decode_row(&record::plain(row).ok()?), - }) + self.scan(&self.rows, table, span, |key, row| { + let cells = record::decode_row(&record::plain(row).ok()?); + Some((Key(key.to_vec()), Row { cells })) }) } @@ -266,15 +263,7 @@ impl Moment { span: &Span, ) -> Result> + use<>> { self.scan(&self.index, index, span, |joined, record| { - let number = - |at: usize| Some(u32::from_le_bytes(*record.get(at..)?.first_chunk()?) as usize); - let length = number(0)?; - let cut = match record.len() { - 4 => None, - 8 => Some(number(4)?), - _ => return None, - }; - (length <= joined.len() && cut.is_none_or(|cut| cut <= length)).then_some((length, cut)) + Some((Key(joined.to_vec()), entry_of(joined, record)?)) }) } @@ -284,7 +273,9 @@ impl Moment { count: u32, span: &Span, ) -> Result> + use<>> { - self.scan(&self.counts, count, span, |_, record| counts::read(record)) + self.scan(&self.counts, count, span, |key, record| { + Some((Key(key.to_vec()), counts::read(record)?)) + }) } /// Every schema record, in the order of their names. @@ -328,6 +319,18 @@ impl Moment { } } +/// What an index record holds beside its entry: see [`Moment::joined`]. +fn entry_of(joined: &[u8], record: &[u8]) -> Option { + let number = |at: usize| Some(u32::from_le_bytes(*record.get(at..)?.first_chunk()?) as usize); + let length = number(0)?; + let cut = match record.len() { + 4 => None, + 8 => Some(number(4)?), + _ => return None, + }; + (length <= joined.len() && cut.is_none_or(|cut| cut <= length)).then_some((length, cut)) +} + impl Read for View { fn commit(&self) -> TxId { self.moment.commit @@ -341,6 +344,17 @@ impl Read for View { Ok(Box::new(self.moment.rows(table.0, &keys::span(from, to))?)) } + fn counted(&self, of: Keys, from: Bound<&Key>, to: Bound<&Key>, most: usize) -> Result { + let (moment, span) = (&*self.moment, keys::span(from, to)); + let (records, id, index) = match of { + Keys::Table(table) => (&moment.rows, table.0, false), + Keys::Index(index) => (&moment.index, index.0, true), + }; + let sound = |k: &[u8], r: &[u8]| (!index || entry_of(k, r).is_some()).then_some(()); + let found = moment.scan(records, id, &span, sound)?.take(most); + found.map(|found| found.and(Ok(1))).sum() + } + fn index(&self, index: IndexId, from: Bound<&Key>, to: Bound<&Key>) -> Result> { let joined = self.moment.joined(index.0, &keys::span(from, to))?; Ok(Box::new(joined.map(split))) diff --git a/v2/contextdb/src/store/keys.rs b/v2/contextdb/src/store/keys.rs index fb400485a..21e368c6d 100644 --- a/v2/contextdb/src/store/keys.rs +++ b/v2/contextdb/src/store/keys.rs @@ -125,6 +125,54 @@ fn real(number: f64) -> [u8; 8] { ordered.to_be_bytes() } +/// The values a key of ascending columns was made from; `None` for bytes that are no such key. +pub(super) fn decode(mut key: &[u8]) -> Option> { + let whole = |bytes: [u8; 8]| i64::from_be_bytes(bytes) ^ i64::MIN; + let mut values = Vec::new(); + while let Some([tag]) = take(&mut key) { + values.push(match tag { + 0xFE => Value::Null, + 1 => Value::Bool(take::<1>(&mut key)? != [0]), + 2 => Value::Int64(whole(take(&mut key)?)), + 3 => { + let ordered = u64::from_be_bytes(take(&mut key)?); + let bits = if ordered >> 63 == 0 { + !ordered + } else { + ordered ^ (1 << 63) + }; + Value::Float64(f64::from_bits(bits)) + } + 4 => { + let mut text = Vec::new(); + loop { + match take(&mut key)? { + [0] => match take(&mut key)? { + [0] => break, + [0xFF] => text.push(0), + _ => return None, + }, + [byte] => text.push(byte), + } + } + Value::Text(String::from_utf8(text).ok()?) + } + 5 => Value::Uuid(Uuid::from_bytes(take(&mut key)?)), + 6 => Value::Timestamp(whole(take(&mut key)?)), + 7 => Value::TxId(TxId(u64::from_be_bytes(take(&mut key)?))), + _ => return None, + }); + } + Some(values) +} + +/// The next bytes of a key, `None` when it is cut short. +fn take(key: &mut &[u8]) -> Option<[u8; N]> { + let (taken, rest) = key.split_first_chunk()?; + *key = rest; + Some(*taken) +} + /// The span of keys between two bounds. A bound stands for every key that begins with it: an /// included bound takes them all in, an excluded bound leaves them all out. pub(super) fn span(from: Bound<&Key>, to: Bound<&Key>) -> Span { @@ -301,51 +349,3 @@ impl EntryShape { Ok(Entry { key: Key(key), cut }) } } - -/// The values a key of ascending columns was made from; `None` for bytes that are no such key. -pub(super) fn decode(mut key: &[u8]) -> Option> { - let whole = |bytes: [u8; 8]| i64::from_be_bytes(bytes) ^ i64::MIN; - let mut values = Vec::new(); - while let Some([tag]) = take(&mut key) { - values.push(match tag { - 0xFE => Value::Null, - 1 => Value::Bool(take::<1>(&mut key)? != [0]), - 2 => Value::Int64(whole(take(&mut key)?)), - 3 => { - let ordered = u64::from_be_bytes(take(&mut key)?); - let bits = if ordered >> 63 == 0 { - !ordered - } else { - ordered ^ (1 << 63) - }; - Value::Float64(f64::from_bits(bits)) - } - 4 => { - let mut text = Vec::new(); - loop { - match take(&mut key)? { - [0] => match take(&mut key)? { - [0] => break, - [0xFF] => text.push(0), - _ => return None, - }, - [byte] => text.push(byte), - } - } - Value::Text(String::from_utf8(text).ok()?) - } - 5 => Value::Uuid(Uuid::from_bytes(take(&mut key)?)), - 6 => Value::Timestamp(whole(take(&mut key)?)), - 7 => Value::TxId(TxId(u64::from_be_bytes(take(&mut key)?))), - _ => return None, - }); - } - Some(values) -} - -/// The next bytes of a key, `None` when it is cut short. -fn take(key: &mut &[u8]) -> Option<[u8; N]> { - let (taken, rest) = key.split_first_chunk()?; - *key = rest; - Some(*taken) -} diff --git a/v2/contextdb/src/store/mod.rs b/v2/contextdb/src/store/mod.rs index f74386e2b..cbfa88176 100644 --- a/v2/contextdb/src/store/mod.rs +++ b/v2/contextdb/src/store/mod.rs @@ -226,6 +226,13 @@ pub(crate) struct Beside { /// Rows in key order. pub(crate) type RowIter<'a> = Box> + 'a>; +/// What [`Read::counted`] counts: the rows of a table, or the entries of an index. +#[derive(Clone, Copy)] +pub(crate) enum Keys { + Table(TableId), + Index(IndexId), +} + /// Index entries in entry order, each with the key of the row it points at and the place its /// first cut value's kept bytes end, when it holds one. pub(crate) type EntryIter<'a> = Box)>> + 'a>; @@ -262,6 +269,10 @@ pub(crate) trait Read { /// those values: included, it takes them all in; excluded, it leaves them all out. fn rows(&self, table: TableId, from: Bound<&Key>, to: Bound<&Key>) -> Result>; + /// How many rows [`Read::rows`] or entries [`Read::index`] give between two keys, counted + /// no further than `most` with no row read and nothing copied. + fn counted(&self, of: Keys, from: Bound<&Key>, to: Bound<&Key>, most: usize) -> Result; + /// The entries of an index between two entries, in entry order. Costs like [`Read::rows`], /// and a bound of fewer columns means what it means there: it is never taken as one exact /// key. A bound applies to the entry alone, so an entry equal to an included bound is in @@ -743,11 +754,13 @@ fn staged_in( .flatten() } -/// Stored records with a transaction's staged ones laid over them, in key order: a staged -/// record stands in for the stored one with its key, and a staged removal, `None`, hides it. -fn overlay<'a, T: 'a>( +/// Stored records with a transaction's staged changes laid over them, in key order: `laid` +/// gives what a key holds from its stored record, if any, and its staged change, and a key it +/// gives nothing for is hidden. +fn overlay<'a, T: 'a, C: 'a>( stored: impl Iterator> + 'a, - staged: impl Iterator)> + 'a, + staged: impl Iterator + 'a, + mut laid: impl FnMut(Option, C) -> Option + 'a, ) -> Box> + 'a> { let (mut stored, mut staged) = (stored.peekable(), staged.peekable()); Box::new(std::iter::from_fn(move || { @@ -759,12 +772,13 @@ fn overlay<'a, T: 'a>( (Some(_), _) => Ordering::Less, (None, Some(_)) => Ordering::Greater, }; - match stored_is { + let before = match stored_is { Ordering::Less => return stored.next(), - Ordering::Equal => drop(stored.next()), - Ordering::Greater => {} - } - if let Some((key, Some(record))) = staged.next() { + Ordering::Equal => stored.next()?.ok().map(|(_, record)| record), + Ordering::Greater => None, + }; + let (key, change) = staged.next()?; + if let Some(record) = laid(before, change) { return Some(Ok((key.clone(), record))); } } @@ -816,17 +830,33 @@ impl Read for ChangeSet { let staged = staged.map(|(key, row)| (key, shown(row))); // A stored row is reshaped only while this change set drops something. if self.dropped.is_empty() { - return Ok(overlay(stored, staged)); + return Ok(overlay(stored, staged, |_, row| row)); } let stored = stored.map(move |row| row.map(|(key, row)| (key, self.shaped(table, row)))); - Ok(overlay(stored, staged)) + Ok(overlay(stored, staged, |_, row| row)) + } + + fn counted(&self, of: Keys, from: Bound<&Key>, to: Bound<&Key>, most: usize) -> Result { + // With nothing staged in what is counted, the stored records are counted where they are. + let found: Box>> = match of { + Keys::Table(table) if self.rows.contains_key(&table.0) => { + Box::new(self.rows(table, from, to)?.map(|found| found.map(drop))) + } + Keys::Index(index) if self.index.contains_key(&index.0) => { + Box::new(self.index(index, from, to)?.map(|found| found.map(drop))) + } + _ => return self.base.counted(of, from, to, most), + }; + found.take(most).map(|found| found.and(Ok(1))).sum() } fn index(&self, index: IndexId, from: Bound<&Key>, to: Bound<&Key>) -> Result> { let span = keys::span(from, to); let stored = self.base.moment.joined(index.0, &span)?; let staged = staged_in(&self.index, index.0, span).map(|(joined, entry)| (joined, *entry)); - Ok(Box::new(overlay(stored, staged).map(split))) + Ok(Box::new( + overlay(stored, staged, |_, entry| entry).map(split), + )) } fn kept(&self, count: CountId, from: Bound<&Key>, to: Bound<&Key>) -> Result> { diff --git a/v2/contextdb/src/store/tests.rs b/v2/contextdb/src/store/tests.rs index fb19850c1..aac05c347 100644 --- a/v2/contextdb/src/store/tests.rs +++ b/v2/contextdb/src/store/tests.rs @@ -571,6 +571,11 @@ fn a_kept_count_that_reaches_zero_leaves_no_record() { assert_eq!(records(&folder, COUNTS).len(), 1); commit_staged(&folder, |changes| { changes.add_kept(count, group.clone(), -2).expect("stage"); + let laid = kept(&*changes, count).expect("read"); + assert!( + laid.is_empty(), + "a staged -2 is laid over the stored 2: {laid:?}" + ); }); assert!( records(&folder, COUNTS).is_empty(), diff --git a/v2/contextdb/src/system/mod.rs b/v2/contextdb/src/system/mod.rs index cf5ed87f7..eef3dd877 100644 --- a/v2/contextdb/src/system/mod.rs +++ b/v2/contextdb/src/system/mod.rs @@ -46,6 +46,3 @@ pub(crate) fn now_millis(clock: &dyn Clock) -> i64 { Err(before) => -(before.duration().as_millis() as i64), } } - -#[cfg(test)] -mod tests; diff --git a/v2/contextdb/src/system/tests.rs b/v2/contextdb/src/system/tests.rs deleted file mode 100644 index 889591edc..000000000 --- a/v2/contextdb/src/system/tests.rs +++ /dev/null @@ -1,19 +0,0 @@ -use std::time::{Duration, SystemTime, UNIX_EPOCH}; - -use super::{Clock, now_millis}; - -struct At(SystemTime); - -impl Clock for At { - fn now(&self) -> SystemTime { - self.0 - } -} - -#[test] -fn the_time_of_day_is_milliseconds_since_1970_on_either_side_of_it() { - let after = At(UNIX_EPOCH + Duration::from_millis(1_700_000_000_123)); - assert_eq!(now_millis(&after), 1_700_000_000_123); - let before = At(UNIX_EPOCH - Duration::from_millis(1_500)); - assert_eq!(now_millis(&before), -1_500); -} diff --git a/v2/contextdb/src/types/mod.rs b/v2/contextdb/src/types/mod.rs index 37a43004d..5616e6023 100644 --- a/v2/contextdb/src/types/mod.rs +++ b/v2/contextdb/src/types/mod.rs @@ -6,6 +6,7 @@ use std::fmt; use std::ops::Range; use std::path::PathBuf; +use serde::{Deserialize, Serialize}; pub use uuid::Uuid; /// What every fallible call of this library returns. @@ -13,7 +14,8 @@ pub type Result = std::result::Result; /// The position the engine gave a commit. Positions rise with every commit of one store, and a /// position that reached the disk is never given out again. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(transparent)] pub struct TxId(pub u64); /// One stored or bound value. @@ -21,7 +23,7 @@ pub struct TxId(pub u64); /// `params!` and `Value::from` take these Rust types: `bool`, `i64` (not `i32`), `f64`, `&str`, /// `String`, [`Uuid`], `Vec` and `serde_json::Value`. A timestamp is written as /// `Value::Timestamp(milliseconds)`, and no value at all as `Value::Null`. -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum Value { /// No value: SQL NULL. Fits a column of any type that is not declared NOT NULL. Null, @@ -389,11 +391,20 @@ pub enum Error { column: String, policy: String, }, + /// `USE RANK` named a sort key the searched column declares no rank policy for. + RankPolicyNotFound { + index: VectorIndexRef, + sort_key: String, + }, /// A `RANK_POLICY` whose declaration cannot stand; `reason` says why. RankPolicyInvalid { index: VectorIndexRef, reason: String, }, + /// `USE RANK` was written in a SELECT that does not order by `<=>`. + UseRankRequiresVectorOrder, + /// `USE RANK` was written in a SELECT with no `LIMIT`. + UseRankRequiresLimit, /// A handle narrowed to some Contexts named, by its key, a row of another Context, or /// wrote a row outside them. ContextScopeViolation { table: String }, @@ -407,8 +418,20 @@ pub enum Error { PrincipalRequired { table: String }, /// A narrowed handle ran a statement only the handle that declared no narrowing may run. AdminRequired { statement: String }, + /// A graph pattern's upper bound is above the deepest walk the engine makes. + BfsDepthExceeded { depth: u32, max: u32 }, + /// A variable-length graph pattern was written with no upper bound. + UnboundedTraversal, + /// `WITH RECURSIVE`. + RecursiveCteNotSupported, + /// A window function other than `ROW_NUMBER() OVER ([PARTITION BY ...] ORDER BY ...)`. + WindowFunctionNotSupported { form: String }, + /// `EXISTS`, or a subquery that reads a row of the statement around it. + SubqueryNotSupported, /// `CREATE PROCEDURE` or `CREATE FUNCTION`. StoredProcNotSupported, + /// `column MATCH pattern`, a full-text search. + FullTextSearchNotSupported, /// A statement wrote a `TXID` value above its own transaction's number. TxIdOutOfRange { value: u64, max: u64 }, } @@ -629,9 +652,16 @@ impl fmt::Display for Error { column, policy, } => write!(f, "{table}.{column} is read by the rank policy {policy}"), + Error::RankPolicyNotFound { index, sort_key } => { + write!(f, "no rank policy named {sort_key} is declared on {index}") + } Error::RankPolicyInvalid { index, reason } => { write!(f, "invalid rank policy on {index}: {reason}") } + Error::UseRankRequiresVectorOrder => { + f.write_str("USE RANK requires ORDER BY embedding <=> $param in the same query") + } + Error::UseRankRequiresLimit => f.write_str("USE RANK requires LIMIT"), Error::ContextScopeViolation { table } => write!( f, "context scope violation: this row of {table} is outside the Contexts this \ @@ -656,9 +686,30 @@ impl fmt::Display for Error { "{statement} reaches every Context, label and principal: run it through the \ handle that declared no narrowing" ), + Error::BfsDepthExceeded { depth, max } => write!( + f, + "graph traversal depth {depth} is above the limit of {max}" + ), + Error::UnboundedTraversal => { + f.write_str("a variable-length pattern needs an upper bound, as in ->{1,3}") + } + Error::RecursiveCteNotSupported => f.write_str("WITH RECURSIVE is not supported"), + Error::WindowFunctionNotSupported { form } => write!( + f, + "window function not supported: {form}; ROW_NUMBER() OVER ([PARTITION BY ...] \ + ORDER BY ...) is" + ), + Error::SubqueryNotSupported => f.write_str( + "this subquery is not supported: a subquery stands inside IN, or alone as one \ + value, and reads no row of the statement around it", + ), Error::StoredProcNotSupported => { f.write_str("stored procedures and functions are not supported") } + Error::FullTextSearchNotSupported => f.write_str( + "full-text search (WHERE column MATCH pattern) is not supported; LIKE matches a \ + pattern", + ), Error::TxIdOutOfRange { value, max } => write!( f, "TXID {value} is above this transaction's own number, {max}" @@ -936,12 +987,12 @@ pub enum VectorPolicyDeclarationIssue { DimensionsNotPositive, /// `WITH (...)` gives this member a value it does not take. InvalidMember { member: &'static str }, - /// `AUTO_INDEX_AT` is zero or negative. - AutoIndexAtNotPositive, - /// `AUTO_INDEX_AT` is larger than the engine keeps. - AutoIndexAtOutOfRange, - /// A percentage of `CONSOLIDATION` is not a whole number from 1 to 100. - ConsolidationPercentOutOfRange, + /// `INDEXING_THRESHOLD` is zero or negative. + IndexingThresholdNotPositive, + /// `INDEXING_THRESHOLD` is larger than the engine keeps. + IndexingThresholdOutOfRange, + /// A percentage of `COMPACTION` is not a whole number from 1 to 100. + CompactionPercentOutOfRange, } impl fmt::Display for VectorPolicyDeclarationIssue { @@ -951,12 +1002,14 @@ impl fmt::Display for VectorPolicyDeclarationIssue { Self::InvalidMember { member } => { write!(f, "{member} has an invalid vector policy value") } - Self::AutoIndexAtNotPositive => f.write_str("AUTO_INDEX_AT must be a positive integer"), - Self::AutoIndexAtOutOfRange => { - f.write_str("AUTO_INDEX_AT is outside the persisted numeric range") + Self::IndexingThresholdNotPositive => { + f.write_str("INDEXING_THRESHOLD must be a positive integer") + } + Self::IndexingThresholdOutOfRange => { + f.write_str("INDEXING_THRESHOLD is outside the persisted numeric range") } - Self::ConsolidationPercentOutOfRange => { - f.write_str("vector consolidation percentages must be integers from 1 through 100") + Self::CompactionPercentOutOfRange => { + f.write_str("vector compaction percentages must be integers from 1 through 100") } } } @@ -966,7 +1019,7 @@ impl fmt::Display for VectorPolicyDeclarationIssue { /// `USE VECTOR` asks for in one statement. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum VectorSearchMode { - /// The engine chooses: through the index from the column's `AUTO_INDEX_AT` vectors on, + /// The engine chooses: through the index from the column's `INDEXING_THRESHOLD` vectors on, /// wherever the index is usable, and exactly otherwise. The answer is never short. #[default] Auto, diff --git a/v2/contextdb/src/vector/build.rs b/v2/contextdb/src/vector/build.rs index a5a8258a3..83bc5f506 100644 --- a/v2/contextdb/src/vector/build.rs +++ b/v2/contextdb/src/vector/build.rs @@ -376,7 +376,7 @@ pub(super) struct Ground<'a> { /// the slots left behind come to `CHANGE_PERCENT` of its slots, or the slots left behind alone /// to `TOMBSTONE_PERCENT`. In any other column only the /// slots left behind count, against every slot the partition has: the build then has one -/// group and writes no centre and no sketch. Under `CONSOLIDATION NONE` only a first grouping +/// group and writes no centre and no sketch. Under `COMPACTION NONE` only a first grouping /// of a column at its size is ever due. The slots left behind are the slots of the grouping /// and the tail less the rows with a vector that are not pending. pub(super) fn due( @@ -401,7 +401,7 @@ pub(super) fn due( grows || behind || (out + stale) * 100 >= u64::from(change) * grouped }; // A partition with no slot has nothing to group: its pending rows are sealed first. - slots > 0 && column.consolidation().is_some_and(reached) + slots > 0 && column.compaction().is_some_and(reached) } /// True when the slots rows have left behind are alone enough for a grouping to be due: they @@ -423,7 +423,7 @@ pub(super) fn left_behind( slots }; let reached = |(_, share): (u8, u8)| stale * 100 >= u64::from(share) * of; - stale > 0 && column.consolidation().is_some_and(reached) + stale > 0 && column.compaction().is_some_and(reached) } /// True when the column is at its size, `vectors` being its rows with a vector. @@ -435,12 +435,12 @@ fn sized(column: &VectorColumn, vectors: u64) -> bool { /// outside its grouping, in tail blocks and pending, are fewer than twice what makes a /// grouping due. A partition with no grouping, or with one of one group, is searched whole, /// and so while the vectors outside its grouping are fewer than twice the column's -/// `index_at`. Under `CONSOLIDATION NONE` a grouping of more groups is always usable. +/// `index_at`. Under `COMPACTION NONE` a grouping of more groups is always usable. pub(super) fn usable(partition: &Partition, pending: u64, column: &VectorColumn) -> bool { let out = partition.slots + pending; match partition.grouping.filter(|grouping| grouping.groups > 1) { None => out < column.index_at().saturating_mul(2), - Some(grouping) => column.consolidation().is_none_or(|(change, _)| { + Some(grouping) => column.compaction().is_none_or(|(change, _)| { let due = (100 * column.grouped_from()).max(u64::from(change) * grouping.slots); out.saturating_mul(100) < due.saturating_mul(2) }), diff --git a/v2/contextdb/src/vector/mod.rs b/v2/contextdb/src/vector/mod.rs index 4ce14cc4c..971e988dd 100644 --- a/v2/contextdb/src/vector/mod.rs +++ b/v2/contextdb/src/vector/mod.rs @@ -41,7 +41,7 @@ mod train; pub(crate) use build::{prepare, remaining, stage_refusal, stage_step, waiting}; pub(crate) use inspect::{Inspected, State, partitions}; pub(crate) use seal::{Sealed, seal}; -pub(crate) use search::{Nearest, Route, plan, search}; +pub(crate) use search::{Nearest, Planned, Route, plan, search}; pub(crate) use slot::{Reduced, distance}; pub(crate) use stage::stage; pub(crate) use tally::Tally; diff --git a/v2/contextdb/src/vector/search.rs b/v2/contextdb/src/vector/search.rs index 56603db81..972ac6c6d 100644 --- a/v2/contextdb/src/vector/search.rs +++ b/v2/contextdb/src/vector/search.rs @@ -25,7 +25,7 @@ pub(crate) struct Nearest<'a> { /// The table of the column, for the rows a transaction has staged. pub table: TableId, pub vector: VectorId, - /// What the column declares: `AUTO_INDEX_AT` and `CONSOLIDATION` decide what AUTO runs + /// What the column declares: `INDEXING_THRESHOLD` and `COMPACTION` decide what AUTO runs /// and when INDEXED may. pub column: &'a VectorColumn, /// The mode in force: the statement's, else the column's. @@ -41,6 +41,9 @@ pub(crate) struct Nearest<'a> { /// The filter itself is asked through `distance_of`. This says one thing more: a search /// under INDEXED that runs out of sketches to choose among is refused. pub filtered: bool, + /// Whether a rank orders the answer: a partition searched exactly then asks the distance of + /// every live vector, and screens none. + pub ranked: bool, } /// One row of an answer. @@ -73,8 +76,7 @@ pub(crate) enum Route { } /// What a search does with one of the partitions it selects, settled from the partition's -/// small records before a block is read. -#[derive(Debug, Clone, PartialEq, Eq)] +/// small records before a block is read, and how far it has gone over it. pub(crate) struct Planned { /// The partition's key tuple. pub tuple: Key, @@ -91,13 +93,7 @@ pub(crate) struct Planned { /// Whether INDEXED may be given this partition. A search under INDEXED with a partition /// that is not usable is refused whole. pub usable: bool, -} - -/// One selected partition as a search goes over it. -struct Target { partition: Partition, - /// What the plan says of it. - planned: Planned, /// The record of its grouping, read when its nearest groups are searched and it has more /// than one group. grouping: Option, @@ -107,7 +103,7 @@ struct Target { next: f64, } -impl Target { +impl Planned { /// How many sketches a search reads of it at most: one for each slot, and none of a /// partition whose slots are screened with no sketch read. fn sketches(&self) -> u64 { @@ -119,16 +115,26 @@ impl Target { } } -/// The selected partitions in the order of their numbers, each with its pending rows counted -/// and its route settled. [`directory::HELD`], its key tuple and the bytes of a `Target` are -/// taken from `reservation` for each. -fn targets( +/// What a search would do with each partition it selects, in the order of their numbers: +/// the one plan [`search`] runs and `.explain` prints. EXACT searches every slot of every +/// one. INDEXED searches the nearest groups of every one, which for a partition with no +/// grouping or a grouping of one group is every slot, through the slot screen alone. AUTO +/// searches every slot of every one while the rows with a vector in all of them together are +/// fewer than the column's `INDEXING_THRESHOLD`, and from there on the nearest groups of each +/// partition that has a grouping and is usable, and every slot of the others. A filter on +/// rows changes no route: it is asked of each row as the search visits it. +/// +/// Only partition, pending and grouping records are read; EXACT reads no grouping record and +/// answers no `probes`. What the list takes is taken from `reservation` first and stays taken +/// until the caller lets it go: [`directory::HELD`], its key tuple and the bytes of a `Planned` +/// for each. +pub(crate) fn plan( nearest: &Nearest<'_>, read: &dyn Read, reservation: &mut Reservation, -) -> Result> { +) -> Result> { let partitions = directory::selected(read, nearest.vector, nearest.scope, reservation)?; - reservation.grow((partitions.len() * size_of::()) as u64)?; + reservation.grow((partitions.len() * size_of::()) as u64)?; let live: u64 = partitions.iter().map(|(_, partition)| partition.live).sum(); let mode = match nearest.mode { VectorSearchMode::Auto if live < nearest.column.index_at() => VectorSearchMode::Exact, @@ -159,7 +165,7 @@ fn targets( } else { Route::Exact }; - let planned = Planned { + targets.push(Planned { tuple, live: partition.live, pending, @@ -168,10 +174,7 @@ fn targets( probes: grouping.as_ref().map_or(0, |grouping| grouping.probes), route, usable, - }; - targets.push(Target { partition, - planned, grouping, taken: 0, next: f64::INFINITY, @@ -180,27 +183,6 @@ fn targets( Ok(targets) } -/// What a search would do with each partition it selects, in the order of their numbers: -/// the one plan [`search`] runs and `.explain` prints. EXACT searches every slot of every -/// one. INDEXED searches the nearest groups of every one, which for a partition with no -/// grouping or a grouping of one group is every slot, through the slot screen alone. AUTO -/// searches every slot of every one while the rows with a vector in all of them together are -/// fewer than the column's `AUTO_INDEX_AT`, and from there on the nearest groups of each -/// partition that has a grouping and is usable, and every slot of the others. A filter on -/// rows changes no route: it is asked of each row as the search visits it. -/// -/// Only partition, pending and grouping records are read; EXACT reads no grouping record and -/// answers no `probes`. What the list takes is taken from `reservation` first and stays taken -/// until the caller lets it go. -pub(crate) fn plan( - nearest: &Nearest<'_>, - read: &dyn Read, - reservation: &mut Reservation, -) -> Result> { - let targets = targets(nearest, read, reservation)?; - Ok(targets.into_iter().map(|target| target.planned).collect()) -} - /// What a search reads blocks and sketches with. struct Asked<'a> { read: &'a dyn Read, @@ -526,7 +508,7 @@ const LOW: u64 = 8; /// grouping's gap and of the tail keep, or all of them where the grouping's width is 0. /// Blocks and sketches are read in place from the page cache; everything that grows is taken /// from `reservation` first. When the answer is returned, `reservation` holds 32 bytes and -/// the key's for each of its rows and nothing else of the search. +/// the key's for each of its rows and nothing else of the search but what [`plan`] took. /// /// A row is turned away when `distance_of` gives no distance for it. While the answer is short /// of `k` rows that were not turned away, the search takes four times as many sketches from @@ -534,30 +516,30 @@ const LOW: u64 = 8; /// far its last row lies below the `k`-th best slot screened, and keeps every sketch that /// reaches that row. Having kept every sketch of every group it has done the work of EXACT and /// returns what there is; under INDEXED with `nearest.filtered` it answers `None` at the step -/// that would keep them all. It answers `None` too, having read only small records, when the -/// mode is INDEXED and a selected partition is not usable. With `None` the caller lets go of -/// what `reservation` took. +/// that would keep them all. With `None` the caller lets go of what `reservation` took. +/// `targets` are what [`plan`] gave for `nearest`, and `reservation` holds what it took and +/// nothing else. /// /// A record of the index that is damaged leaves the vectors whole. Under AUTO the search is -/// then run again as EXACT, which reads no such record and answers in full, or tells the -/// damage of a block; under INDEXED the damage is the answer. Nothing is rebuilt. +/// then planned and run again as EXACT, which reads no such record and answers in full, or +/// tells the damage of a block; under INDEXED the damage is the answer. Nothing is rebuilt. pub(crate) fn search( nearest: &Nearest<'_>, read: &dyn Read, reservation: &mut Reservation, + targets: &mut Vec, distance_of: &mut dyn FnMut(&Key) -> Result>, ) -> Result> { - let before = reservation.bytes(); - match answer(nearest, read, reservation, distance_of) { + match answer(nearest, read, reservation, targets, distance_of) { Err(Error::StoreCorrupted { .. }) if nearest.mode == VectorSearchMode::Auto => { - reservation.shrink(reservation.bytes() - before); - let mode = VectorSearchMode::Exact; - answer( - &Nearest { mode, ..*nearest }, - read, - reservation, - distance_of, - ) + targets.clear(); + reservation.shrink(reservation.bytes()); + let nearest = Nearest { + mode: VectorSearchMode::Exact, + ..*nearest + }; + *targets = plan(&nearest, read, reservation)?; + answer(&nearest, read, reservation, targets, distance_of) } other => other, } @@ -568,6 +550,7 @@ fn answer( nearest: &Nearest<'_>, read: &dyn Read, reservation: &mut Reservation, + targets: &mut [Planned], distance_of: &mut dyn FnMut(&Key) -> Result>, ) -> Result> { if nearest.k == 0 { @@ -577,11 +560,7 @@ fn answer( })); } let before = reservation.bytes(); - let mut targets = targets(nearest, read, reservation)?; let indexed = nearest.mode == VectorSearchMode::Indexed; - if indexed && targets.iter().any(|target| !target.planned.usable) { - return Ok(None); - } // The vector at length one that the screen keeps: four bytes a number. reservation.grow(4 * nearest.query.len() as u64)?; let screen = Screen::new(nearest.query); @@ -607,6 +586,8 @@ fn answer( marks: BTreeMap::new(), evaluations: 0, refused: indexed && nearest.filtered, + ranked: nearest.ranked, + every: false, }; // The rows that are in no block, exactly: those the reader has staged, then the pending @@ -619,7 +600,7 @@ fn answer( return Ok(None); } let first = Key::from_values(&[], &[])?; - for target in &targets { + for target in &*targets { let run = (nearest.vector, target.partition.number); let from = VectorRecord::Pending(run.0, run.1, &first); read.vectors(from, &mut |record, _| match record { @@ -636,15 +617,15 @@ fn answer( // out lies within the gap widened by the fall, nothing left out could have entered. // Otherwise rows were turned away or counted twice, and a further pass goes on from there. let mut most = nearest.k; - let mut ended = found.pass(&asked, &mut targets, &mut wide, None, None, 0.0)?; + let mut ended = found.pass(&asked, targets, &mut wide, None, None, 0.0)?; loop { let (floor, sketches, fall) = match found.last() { // Short of `k` rows: four times the sketches, and twice the groups once every // sketch of the groups taken was kept. None => { most = most.max(ended.kept).saturating_mul(4); - let mut all = most as u64 >= targets.iter().map(Target::sketches).sum::(); - for target in &mut targets { + let mut all = most as u64 >= targets.iter().map(Planned::sketches).sum::(); + for target in &mut *targets { target.taken = target.taken.saturating_mul(if ended.all { 2 } else { 1 }); let grouping = target.grouping.as_ref(); all &= @@ -665,7 +646,7 @@ fn answer( // as far below the best centre's: twice the angle from the vector of the // search. The cover takes the groups that far out. let fall = 4.0 * (found.lows.least() - last).max(0.0); - let nearer = |target: &Target| target.next <= fall * 10_000.0; + let nearer = |target: &Planned| target.next <= fall * 10_000.0; let proven = last >= ended.threshold && last >= ended.sketches; if proven && !targets.iter().any(nearer) { break; @@ -673,7 +654,7 @@ fn answer( (last, None, fall) } }; - ended = found.pass(&asked, &mut targets, &mut wide, Some(floor), sketches, fall)?; + ended = found.pass(&asked, targets, &mut wide, Some(floor), sketches, fall)?; } let pairs = found.answer.iter(); @@ -789,6 +770,10 @@ struct Found<'a> { /// Whether the search is refused when it runs out of sketches to choose among: the mode /// is INDEXED and the statement has a filter on rows. refused: bool, + /// Whether a rank orders the answer, and whether the partition in hand is then searched + /// exactly, so that every slot of it has its row's distance asked for. + ranked: bool, + every: bool, } impl Found<'_> { @@ -848,6 +833,9 @@ impl Found<'_> { if word.is_some_and(|word| word >> (slot % 64) & 1 == 1) { return Ok(()); } + if self.every { + return self.score(&block.key(slot)); + } self.evaluations += 1; let (low, high) = asked.screen.range(block.slot(slot)); if f64::from(high) < self.threshold { @@ -930,7 +918,7 @@ impl Found<'_> { fn pass( &mut self, asked: &Asked<'_>, - targets: &mut [Target], + targets: &mut [Planned], wide: &mut Option, floor: Option, most: Option, @@ -965,6 +953,7 @@ impl Found<'_> { kept: 0, }; for target in targets.iter_mut() { + self.every = self.ranked && target.route == Route::Exact; let partition = target.partition; let tail = first_of(partition.first)..first_of(partition.blocks); let (Some(grouping), Some(grouped)) = (&target.grouping, partition.grouping) else { diff --git a/v2/contextdb/src/vector/tests.rs b/v2/contextdb/src/vector/tests.rs index a3271c87a..2f716e46a 100644 --- a/v2/contextdb/src/vector/tests.rs +++ b/v2/contextdb/src/vector/tests.rs @@ -15,7 +15,7 @@ use super::grouping::{ put_mean, }; use super::seal::seal; -use super::sketch::{Estimate, Sketches, WIDEST, sketch_len, sketches_of, write_sketch}; +use super::sketch::{Estimate, Sketches, WIDEST, sketch_len, write_sketch}; use super::slot::{Screen, distance, slot_len, write_slot}; use super::stage::stage; use super::train::{Mean, Round, first_centres, groups_for, nearest, product, sampled}; @@ -233,13 +233,7 @@ fn a_pending_record_of_a_row_with_no_vector_is_reported_as_damage() { // Which of three pending rows is left with no vector: the first, which a cycle reads to // find the partition, and a later one, which it reads to write a slot. for damaged in [1_i64, 2] { - let folder = std::env::temp_dir().join(format!( - "contextdb-pending-without-vector-{damaged}-{}", - std::process::id() - )); - if folder.exists() { - std::fs::remove_dir_all(&folder).expect("clear the folder an earlier run left"); - } + let folder = fresh(&format!("pending-without-vector-{damaged}")); // A sound store: three rows of one partition, each with a vector and each waiting on // the pending list. let db = Database::open(&folder).expect("open a fresh store"); @@ -299,10 +293,7 @@ type Misnamed = (PathBuf, Store, Budget, TableId); /// changed: the name of the column the record's VECTOR entry is for. No declaration writes such /// a record. fn a_vector_entry_named(test: &str, named: u8) -> Misnamed { - let folder = std::env::temp_dir().join(format!("contextdb-{test}-{}", std::process::id())); - if folder.exists() { - std::fs::remove_dir_all(&folder).expect("clear the folder an earlier run left"); - } + let folder = fresh(test); let db = Database::open(&folder).expect("open a fresh store"); for sql in [ "CREATE TABLE docs (id INTEGER PRIMARY KEY, n INTEGER, v VECTOR(4))", @@ -418,10 +409,7 @@ const COLUMN: VectorId = VectorId(3); /// An empty store in a folder of its own. fn a_store(test: &str) -> (PathBuf, Store, Budget) { - let folder = std::env::temp_dir().join(format!("contextdb-{test}-{}", std::process::id())); - if folder.exists() { - std::fs::remove_dir_all(&folder).expect("clear the folder an earlier run left"); - } + let folder = fresh(test); let budget = Budget::new(None).expect("a budget"); let store = Store::open_for_writing(&folder, &budget, None).expect("open a fresh store"); (folder, store, budget) @@ -510,58 +498,6 @@ fn a_partition() -> Partition { } } -#[test] -fn a_partition_record_reads_back() { - // The 73 bytes: the number, the live rows, the tail's last, first and closed blocks, its - // slots, the slots ever sealed, the flags, the grouping in force and the one being built. - let whole = a_partition(); - let mut wanted = Vec::new(); - wanted.extend(7_u32.to_le_bytes()); - wanted.extend(300_u64.to_le_bytes()); - for number in [6_u32, 2, 4] { - wanted.extend(number.to_le_bytes()); - } - wanted.extend(500_u64.to_le_bytes()); - wanted.extend(9000_u64.to_le_bytes()); - wanted.push(1 | 2 | 4); - for number in [9_u32, 3, 17] { - wanted.extend(number.to_le_bytes()); - } - wanted.extend(290_u64.to_le_bytes()); - wanted.extend(8500_u64.to_le_bytes()); - wanted.extend(11_u32.to_le_bytes()); - assert_eq!(wanted.len(), 73); - assert_eq!(whole.encode(), wanted); - - // A field its flag does not set is zero. - let bare = Partition { - number: 0x0102_0304, - live: 0x0506_0708_090A_0B0C, - blocks: 0x0D0E_0F10, - sealed: u64::MAX, - ..Partition::default() - }; - let mut wanted = vec![ - 4, 3, 2, 1, 0x0C, 0x0B, 0x0A, 9, 8, 7, 6, 5, 0x10, 0x0F, 0x0E, 0x0D, - ]; - wanted.extend([0; 16]); - wanted.extend([0xFF; 8]); - wanted.extend([0; 33]); - assert_eq!(bare.encode(), wanted); - - let (folder, store, budget) = a_store("partition-record"); - for (at, entry) in [whole, bare].into_iter().enumerate() { - let tuple = key(at as i64 + 1); - let record = VectorRecord::Partition(COLUMN, &tuple); - let view = put(&store, &budget, record, entry.encode()); - assert_eq!(partition(&view, COLUMN, &tuple).expect("read"), Some(entry)); - let other = key(50); - assert_eq!(partition(&view, COLUMN, &other).expect("read"), None); - } - drop(store); - std::fs::remove_dir_all(&folder).expect("remove the test's folder"); -} - #[test] fn a_partition_entry_that_disagrees_with_itself_is_damage() { let (folder, store, budget) = a_store("partition-damage"); @@ -622,24 +558,6 @@ fn a_grouping() -> Grouping { } } -#[test] -fn a_grouping_record_reads_back() { - let grouping = a_grouping(); - // The gap, the width and the probes, then each place as its block and its slot. - let numbers = [780_u32, 4, 2, 0, 0, 0, 200, 1, 50, 1, 300]; - let wanted: Vec = numbers.iter().flat_map(|n| n.to_le_bytes()).collect(); - assert_eq!(wanted.len(), 12 + 8 * 4); - assert_eq!(grouping.encode(), wanted); - let (folder, store, budget) = a_store("grouping-record"); - let view = put(&store, &budget, VectorRecord::Grouping(COLUMN, 9), wanted); - assert_eq!( - Grouping::read(&view, COLUMN, GROUPED).expect("read"), - grouping - ); - drop((view, store)); - std::fs::remove_dir_all(&folder).expect("remove the test's folder"); -} - #[test] fn a_grouping_that_disagrees_with_its_partition_is_damage() { let (folder, store, budget) = a_store("grouping-damage"); @@ -946,78 +864,6 @@ fn given() -> (Vec, Vec) { (counts, starts) } -#[test] -fn a_build_record_reads_back() { - let (counts, starts) = given(); - let tens = |questions: usize| vec![Place { block: 0, slot: 7 }; 10 * questions]; - let packed = |phase: Phase, questions: usize| Build { - counts: counts.clone(), - starts: starts.clone(), - tens: tens(questions), - ..a_build(phase) - }; - let builds = [ - a_build(Phase::Train { round: 3 }), - Build { - from: Some(Grouped { - number: 9, - blocks: 1, - groups: 40, - slots: 1600, - upto: 1600, - }), - tail: (2, 3), - stale: true, - needing: 4096, - ..a_build(Phase::Assign { next: 1 }) - }, - Build { - counts: counts.clone(), - starts: starts[..3].to_vec(), - ..a_build(Phase::Pack { group: 2 }) - }, - packed(Phase::Measure { done: 2, most: 150 }, 2), - packed( - Phase::Width { - gap: 150, - probes: 3, - done: 1, - asked: 10, - kept: [9; 15], - }, - 128, - ), - packed( - Phase::Switch { - gap: 150, - probes: 3, - width: 4, - }, - 128, - ), - Build { - stale: true, - ..packed(Phase::Sweep, 0) - }, - ]; - let (folder, store, budget) = a_store("build-record"); - let view = store.view().expect("a view"); - assert_eq!(Build::read(&view, COLUMN, 7).expect("read"), None); - drop(view); - for build in builds { - let view = put( - &store, - &budget, - VectorRecord::Build(COLUMN, 7), - build.encode(), - ); - let read = Build::read(&view, COLUMN, 7).expect("read the build"); - assert_eq!(read, Some(build)); - } - drop(store); - std::fs::remove_dir_all(&folder).expect("remove the test's folder"); -} - #[test] fn a_build_whose_cursor_is_past_its_blocks_is_damage() { let (counts, _) = given(); @@ -1183,32 +1029,6 @@ fn the_ranges_of_a_run_of_sketches_are_those_of_the_plain_arithmetic() { } } -#[test] -fn the_sketches_of_a_block_read_back() { - const DIMENSION: usize = 16; - let keys: Vec = (0..5).map(key).collect(); - let (mut writer, taken) = BlockWriter::new(DIMENSION, None, &keys); - assert_eq!(taken, 5); - for (n, key) in keys.iter().enumerate() { - writer.push(key, &vector(800 + n as u64, DIMENSION)); - } - let block = writer.finish(); - // Slot `place` is sketched from reference `place % 2`. - let references = [vector(900, DIMENSION), vector(901, DIMENSION)]; - let record = sketches_of(&block, DIMENSION, &mut |place| &references[place % 2]); - assert_eq!(record.len(), 4 + 5 * sketch_len(DIMENSION)); - assert_eq!(record[..4], 5_u32.to_le_bytes()); - let sketches = Sketches::new(&record, DIMENSION); - assert!(sketches.is_whole(5) && !sketches.is_whole(4) && !sketches.is_whole(6)); - assert!(!Sketches::new(&record[..record.len() - 1], DIMENSION).is_whole(5)); - let reader = BlockReader::new(&block, DIMENSION); - for place in 0..5 { - let mut wanted = vec![0_u8; sketch_len(DIMENSION)]; - write_sketch(reader.slot(place), &references[place % 2], &mut wanted); - assert_eq!(sketches.at(place), wanted.as_slice(), "sketch {place}"); - } -} - // ---- damage in a built store, through the public calls ---- const BUILT: usize = 16; @@ -1246,7 +1066,7 @@ fn insert_gathered(db: &Database, ids: std::ops::RangeInclusive) { fn a_store_with_vectors(test: &str, cycles: usize) -> (PathBuf, Database) { let folder = fresh(test); let db = Database::open(&folder).expect("open a fresh store"); - let table = "CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(16) AUTO_INDEX_AT 1000)"; + let table = "CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(16) INDEXING_THRESHOLD 1000)"; db.execute(table, &HashMap::new()).expect(table); insert_gathered(&db, 1..=2000); for _ in 0..cycles { diff --git a/v2/contextdb/src/write/commit.rs b/v2/contextdb/src/write/commit.rs index 7b1576cfb..3a215bf3c 100644 --- a/v2/contextdb/src/write/commit.rs +++ b/v2/contextdb/src/write/commit.rs @@ -6,9 +6,9 @@ use std::collections::HashMap; use std::ops::Bound; -use super::{Given, Rules, column, equal, pick}; +use super::{Given, Rules, pick}; use crate::memory::{Budget, Reservation}; -use crate::query::{self, Reader}; +use crate::query::{self, Reader, equal}; use crate::schema::{Catalog, Reference, Table}; use crate::store::{Cell, ChangeSet, Key, Read, Row, RowGuard, View}; use crate::types::{Error, Result, TxId, Value, shown}; @@ -83,7 +83,7 @@ pub(crate) fn check_at_commit( if let Some(before) = before { if let (true, Some((row, _))) = (new_key, row) { if there.is_some() { - return Err(rules.violation(rules.key_columns(), pick(&table.key, row))); + return Err(rules.violation(&table.key, row)); } } else if before.row(id, key)? != there { overtaken += 1; @@ -95,7 +95,7 @@ pub(crate) fn check_at_commit( let mut loaded = budget.reserve(0, "query")?; for &(child, reference) in children { let at = reference.parent_columns.iter(); - let at: Vec = at.map(|name| column(table, name)).collect::>()?; + let at: Vec = at.map(|name| table.column(name)).collect::>()?; let old = at.iter().map(|&at| held(table, was, at, base, &mut loaded)); let old: Vec = old.collect::>()?; let whole = !old.contains(&Value::Null); @@ -137,10 +137,11 @@ pub(crate) fn check_at_commit( } rules.acyclic(changes, rules.edge(None, row)?)?; for index in &rules.indexes { - if let Some(columns) = index.rule(row) - && rules.taken(changes, index, &index.entry(row)?, row, key)? + if index.rule(row) + && let Some(entry) = index.entry(row)? + && rules.taken(changes, index, &entry, row, key)? { - return Err(rules.violation(columns.to_owned(), pick(&index.columns, row))); + return Err(rules.violation(&index.columns, row)); } } } @@ -213,7 +214,7 @@ fn parent( let Some(rule) = rule else { return Ok(false); }; - let at = named.iter().map(|name| column(table, name)); + let at = named.iter().map(|name| table.column(name)); let at: Vec = at.collect::>()?; holds(table, rule, &at, values, read, given) } @@ -254,8 +255,7 @@ fn holds( assigned: &[], needed: &vec![false; table.meta.columns.len()], reader: given.reader, - params: &bound, - now: given.now, + ctx: query::EvalContext::new(&bound, given.now), }; let found = query::rows_for_write(&asked, None, given.catalog, read, given.budget)?; Ok(found.is_some()) diff --git a/v2/contextdb/src/write/mod.rs b/v2/contextdb/src/write/mod.rs index 4f0e5617e..67df5bd12 100644 --- a/v2/contextdb/src/write/mod.rs +++ b/v2/contextdb/src/write/mod.rs @@ -13,8 +13,8 @@ //! caller undoes a refused statement by rewinding the change set. //! //! The values that name a row or a group (a primary key, a kept count's values, a partition -//! key) are kept whole and refused past `KEY_LIMIT`. An index entry is made by -//! `EntryShape::entry`, which cuts a long value, so no row is refused for one. +//! key) are kept whole and refused past `KEY_LIMIT`. An index entry is made by `Table::entry`, +//! which cuts a long value, so no row is refused for one. mod commit; mod counts; @@ -30,14 +30,11 @@ use std::collections::{BTreeSet, HashMap}; use std::ops::Bound; use crate::memory::Budget; -use crate::query::{self, Reader, Visible}; +use crate::query::{self, Reader, Visible, equal}; use crate::schema::{Catalog, Quantization, Table}; -use crate::sql::ast::{BinOp, ColumnRef}; use crate::sql::plan::InsertPlan; use crate::sql::{Expr, Plan}; -use crate::store::{ - Beside, Cell, ChangeSet, Compact, Entry, EntryShape, IndexId, KEY_LIMIT, Key, Read, Row, -}; +use crate::store::{Beside, Cell, ChangeSet, Compact, Entry, IndexId, KEY_LIMIT, Key, Read, Row}; use crate::types::{ self, ColumnDefault, ColumnType, Error, Result, SortDirection, TxId, Value, shown, typed, }; @@ -82,23 +79,19 @@ pub(crate) fn apply( changes: &mut ChangeSet, partitions: &mut Tally, ) -> Result { - let name = match plan { - Plan::Insert(plan) => &plan.table, - Plan::Update(plan) => &plan.table, - Plan::Delete(plan) => &plan.table, - other => unreachable!("{other:?} writes no rows"), - }; + let (name, ..) = plan.written().expect("an INSERT, UPDATE or DELETE"); let table = given.catalog.table(name); let table = table.ok_or_else(|| Error::TableNotFound(name.clone()))?; - let rules = Rules::of(table, given)?; + let mut rules = Rules::of(table, given)?; rules.changeable(plan)?; - // What the reader's filter holds is given back with the statement. + // What the reader's filter and the statement's SELECTs hold is given back with it. let mut seeing = given.budget.reserve(0, "query")?; + rules.values = query::written(plan, given, &*changes, &mut seeing)?; let mut visible = Visible::new(table, given.catalog, given.reader, &mut seeing)?; let rows = match plan { Plan::Insert(plan) => rules.insert(plan, changes, partitions, &mut visible)?, Plan::Update(plan) => { - let (set, filter) = (rules.set(&plan.assignments)?, plan.where_clause.as_ref()); + let (set, filter) = (table.set(&plan.assignments)?, plan.where_clause.as_ref()); let params = given.params; rules.change(&set, filter, params, changes, partitions, &mut visible)? } @@ -114,8 +107,8 @@ pub(crate) fn apply( } /// Stages an entry in a new index for every row the table already has, a batch of rows at a -/// time, so that what is held here does not grow with the table. An index that holds no -/// entries (the primary key's, or one over a JSON path) is passed over. +/// time, so that what is held here does not grow with the table. The primary key's index, +/// which holds no entries, is passed over. pub(crate) fn fill_index( table: &Table, index: IndexId, @@ -142,21 +135,11 @@ pub(crate) fn fill_index( } let asked = rules.asked(None, ¶ms, &[], &needed, &reader); rules.each(&asked, changes, |changes, key, cells| { - changes.put_index(index.id, index.entry(&split(cells).0)?, key) + let entry = index.entry(&split(cells).0)?; + entry.map_or(Ok(()), |entry| changes.put_index(index.id, entry, key)) }) } -/// Where a column a statement or an index names is in a row of the table. -fn column(table: &Table, name: &str) -> Result { - let mut columns = table.meta.columns.iter(); - columns - .position(|column| column.name == name) - .ok_or_else(|| Error::ColumnNotFound { - table: table.name.clone(), - column: name.to_owned(), - }) -} - /// What a write needs to know about its table, worked out once for a statement. struct Rules<'a> { table: &'a Table, @@ -175,6 +158,8 @@ struct Rules<'a> { reduced: Vec, /// The rows that are to follow the rows whose state the statement has changed so far. followed: RefCell>, + /// The values of the SELECTs inside the statement, read before it changed a row. + values: query::Values, } /// One index of a table as a write uses it. @@ -182,30 +167,25 @@ struct Index<'a> { id: IndexId, /// Where its columns are in a row, in index order. columns: Vec, - /// How its entries are made. - shape: &'a EntryShape, - /// The columns of the unique rule this index is behind, as a refusal names them. `schema` - /// makes one index for each unique rule and names it `__unique_...`. - unique: Option, + /// Its table, and where it is among the table's indexes: how its entries are made. + table: &'a Table, + at: usize, + /// Whether it is the index of a unique rule, which `schema` names `__unique_...`. + unique: bool, } impl<'a> Rules<'a> { fn of(table: &'a Table, given: &'a Given<'a>) -> Result> { let held = table.meta.indexes.iter().enumerate().zip(&table.index_ids); - let held = held.filter(|((_, index), _)| { - !index.name.starts_with("__pk_") && index.json_path.is_empty() - }); + let held = held.filter(|((_, index), _)| !index.name.starts_with("__pk_")); let indexes = held.map(|((at, index), &id)| { - let names: Vec<&str> = index.columns.iter().map(|(name, _)| &**name).collect(); - let columns = names.iter().map(|name| column(table, name)); + let columns = index.columns.iter().map(|(name, _)| table.column(name)); Ok(Index { id, columns: columns.collect::>()?, - shape: table.entry_shape(at), - unique: index - .name - .starts_with("__unique_") - .then(|| names.join(", ")), + table, + at, + unique: index.name.starts_with("__unique_"), }) }); let counts = table.rules.counts.iter(); @@ -215,7 +195,7 @@ impl<'a> Rules<'a> { let vectors = vectors.filter(|vector| !vector.partition_key.is_empty()); let partitions = vectors.map(|vector| { let names = std::iter::once(&vector.column).chain(&vector.partition_key); - names.map(|name| column(table, name)).collect() + names.map(|name| table.column(name)).collect() }); Ok(Rules { table, @@ -226,9 +206,10 @@ impl<'a> Rules<'a> { .collect(), partitions: partitions.collect::>()?, reduced: reduced - .map(|vector| column(table, &vector.column)) + .map(|vector| table.column(&vector.column)) .collect::>()?, followed: RefCell::default(), + values: Vec::new(), }) } @@ -247,8 +228,7 @@ impl<'a> Rules<'a> { assigned, needed, reader, - params, - now: self.given.now, + ctx: query::EvalContext::new(params, self.given.now).over(&self.values), } } @@ -274,30 +254,6 @@ impl<'a> Rules<'a> { Ok(()) } - /// Where each assigned column is in a row, with its new value. - fn set<'e>(&self, assignments: &'e [(String, Expr)]) -> Result> { - self.targets(assignments.iter().map(|(name, value)| (name, value))) - } - - /// Where each column a statement writes is in a row, with what is written to it; one - /// named twice is refused. - fn targets<'n, T>( - &self, - named: impl Iterator, - ) -> Result> { - let mut targets: Vec<(usize, T)> = Vec::new(); - for (name, with) in named { - let at = column(self.table, name)?; - if targets.iter().any(|(target, _)| *target == at) { - let table = &self.table.name; - let refusal = format!("{name} is named twice as a column {table} is written in"); - return Err(Error::PlanError(refusal)); - } - targets.push((at, with)); - } - Ok(targets) - } - fn insert( &self, plan: &InsertPlan, @@ -307,12 +263,7 @@ impl<'a> Rules<'a> { ) -> Result { let (table, given) = (self.table, self.given); let columns = &table.meta.columns; - let named: Vec = if plan.columns.is_empty() { - (0..columns.len()).collect() - } else { - let named = self.targets(plan.columns.iter().map(|name| (name, ())))?; - named.into_iter().map(|(at, ())| at).collect() - }; + let (named, conflict) = table.insert(plan)?; // A column the statement leaves out starts at its default, or at NULL. let mut blank = vec![Value::Null; columns.len()]; for (at, column) in columns.iter().enumerate() { @@ -325,43 +276,12 @@ impl<'a> Rules<'a> { None => {} } } - // `ON CONFLICT` names the primary key or a whole UNIQUE rule, in any order. - let conflict = match &plan.on_conflict { - Some(conflict) => { - let on = conflict.columns.iter().map(|name| column(table, name)); - let mut on: Vec = on.collect::>()?; - on.sort_unstable(); - let is_on = |columns: &[usize]| { - let mut columns = columns.to_vec(); - columns.sort_unstable(); - columns == on - }; - let mut unique = self.indexes.iter().filter(|index| index.unique.is_some()); - if !is_on(&table.key) && !unique.any(|index| is_on(&index.columns)) { - return Err(Error::PlanError(format!( - "ON CONFLICT ({}) names neither the primary key nor a UNIQUE rule of {}", - conflict.columns.join(", "), - table.name - ))); - } - Some((on, self.set(&conflict.assignments)?)) - } - None => None, - }; let (mut stored, scope) = (0, table.scope()); + let ctx = query::EvalContext::new(given.params, given.now).over(&self.values); for values in &plan.values { - if values.len() != named.len() { - return Err(Error::PlanError(format!( - "INSERT INTO {} gives {} values for {} columns", - table.name, - values.len(), - named.len() - ))); - } let mut row = blank.clone(); for (&at, value) in named.iter().zip(values) { - let ctx = query::EvalContext::new(given.params, given.now); row[at] = query::eval(value, &scope, &[], &ctx)?; } let row = row.into_iter().enumerate(); @@ -407,7 +327,7 @@ impl<'a> Rules<'a> { let assigned: Vec = set.iter().map(|&(at, _)| at).collect(); let mut needed = vec![false; table.meta.columns.len()]; for &(_, value) in set { - query::reads(value, table, given.params, &mut needed)?; + query::reads(value, &table.scope(), given.params, &mut needed)?; } visible.reads(&mut needed); let state = self.state(&assigned, &mut needed)?; @@ -415,7 +335,7 @@ impl<'a> Rules<'a> { // A row whose key changes is a new row at its new key, and one whose key or unique // value is still held by a row this statement has yet to change is taken out and put // back last: either is written whole. - let unique = self.indexes.iter().filter(|index| index.unique.is_some()); + let unique = self.indexes.iter().filter(|index| index.unique); let named = table .key .iter() @@ -437,10 +357,10 @@ impl<'a> Rules<'a> { held + size_of_val(row) as u64 }; // Every new value is worked out from the row as it was. + let ctx = query::EvalContext::new(given.params, given.now).over(&self.values); let assign = |old: &[Value]| -> Result> { let mut row = old.to_vec(); for &(at, value) in set { - let ctx = query::EvalContext::new(given.params, given.now); row[at] = self.settle(at, query::eval(value, &scope, old, &ctx)?)?; } Ok(row) @@ -551,7 +471,9 @@ impl<'a> Rules<'a> { visible.may_write(&row, &*changes)?; self.count(changes, Some(&row), None)?; for index in &self.indexes { - changes.delete_index(index.id, &index.entry(&row)?.key, key)?; + if let Some(entry) = index.entry(&row)? { + changes.delete_index(index.id, &entry.key, key)?; + } } changes.delete_row(self.table.id, key) } @@ -661,7 +583,7 @@ impl<'a> Rules<'a> { // A new row, or a row whose key changed: the transaction must find no row at this key. let new_key = was.is_none_or(|(old, _)| *old != key); if new_key && changes.row(table.id, &key)?.is_some() { - return Err(self.violation(self.key_columns(), pick(&table.key, &row))); + return Err(self.violation(&table.key, &row)); } self.count(changes, was.map(|(_, old)| old), Some(&row))?; let own = was.map_or(&key, |(old, _)| old); @@ -672,15 +594,20 @@ impl<'a> Rules<'a> { } let entry = index.entry(&row)?; if changed - && let Some(columns) = index.rule(&row) - && self.taken(&*changes, index, &entry, &row, own)? + && index.rule(&row) + && let Some(entry) = &entry + && self.taken(&*changes, index, entry, &row, own)? + { + return Err(self.violation(&index.columns, &row)); + } + if let Some((_, old)) = was + && let Some(old) = index.entry(old)? { - return Err(self.violation(columns.to_owned(), pick(&index.columns, &row))); + changes.delete_index(index.id, &old.key, own)?; } - if let Some((_, old)) = was { - changes.delete_index(index.id, &index.entry(old)?.key, own)?; + if let Some(entry) = entry { + changes.put_index(index.id, entry, key.clone())?; } - changes.put_index(index.id, entry, key.clone())?; } // Noted once nothing can refuse the row any more. if new_key || self.partitions.iter().any(|group| differs(group)) { @@ -744,35 +671,29 @@ impl<'a> Rules<'a> { Ok(found.is_some_and(|(rows, _)| rows.iter().any(|(key, _)| key != own))) } - /// The columns of the primary key, as a refusal names them. - fn key_columns(&self) -> String { - let columns = &self.table.meta.columns; - let key = self.table.key.iter(); - let names: Vec<&str> = key.map(|&at| &*columns[at].name).collect(); - names.join(", ") - } - - fn violation(&self, column: String, key: Vec) -> Error { + /// The refusal of a row whose values in `columns`, its key or a unique rule's, another row + /// holds: the columns are named between commas. + fn violation(&self, columns: &[usize], row: &[Value]) -> Error { + let names: Vec<&str> = (columns.iter()) + .map(|&at| &*self.table.meta.columns[at].name) + .collect(); Error::UniqueViolation { table: self.table.name.clone(), - column, - key: shown(&key), + column: names.join(", "), + key: shown(&pick(columns, row)), } } } impl Index<'_> { - /// The row's entry in this index. - fn entry(&self, row: &[Value]) -> Result { - self.shape.entry(&pick(&self.columns, row)) + /// The row's entry in this index, if it has one. + fn entry(&self, row: &[Value]) -> Result> { + self.table.entry(self.at, &pick(&self.columns, row)) } - /// The columns of the unique rule this index holds the row to. A NULL in any column of the - /// rule takes the row out of it. - fn rule(&self, row: &[Value]) -> Option<&str> { - let columns = self.unique.as_deref()?; - let whole = !self.columns.iter().any(|&at| row[at] == Value::Null); - whole.then_some(columns) + /// Whether its unique rule holds the row: a NULL in any column of the rule takes it out. + fn rule(&self, row: &[Value]) -> bool { + self.unique && !self.columns.iter().any(|&at| row[at] == Value::Null) } } @@ -781,32 +702,6 @@ fn pick(columns: &[usize], row: &[Value]) -> Vec { columns.iter().map(|&at| row[at].clone()).collect() } -/// What passes exactly the rows that hold `values` in `columns`, side by side, and the -/// parameters it reads them from: each under its column's name. -fn equal(table: &Table, columns: &[usize], values: &[Value]) -> (Expr, HashMap) { - let mut bound = HashMap::new(); - let each = columns.iter().zip(values).map(|(&at, value)| { - let name = &table.meta.columns[at].name; - bound.insert(name.clone(), value.clone()); - let column = ColumnRef { - table: None, - column: name.clone(), - }; - Expr::BinaryOp { - left: Box::new(Expr::Column(column)), - op: BinOp::Eq, - right: Box::new(Expr::Parameter(name.clone())), - } - }); - let filter = each.reduce(|left, right| Expr::BinaryOp { - left: Box::new(left), - op: BinOp::And, - right: Box::new(right), - }); - let filter = filter.expect("a key and a UNIQUE rule have a column"); - (filter, bound) -} - /// A row's values in column order, with NULL for each large value that was left beside the /// row, and those cells with the columns they are of. fn split(cells: Vec) -> (Vec, Vec<(usize, Beside)>) { diff --git a/v2/contextdb/src/write/propagate.rs b/v2/contextdb/src/write/propagate.rs index 64c58f06b..0fadc75e6 100644 --- a/v2/contextdb/src/write/propagate.rs +++ b/v2/contextdb/src/write/propagate.rs @@ -14,9 +14,9 @@ use std::collections::VecDeque; -use super::{Given, Rules, column, equal, split}; +use super::{Given, Rules, split}; use crate::memory::Reservation; -use crate::query::{Reader, Visible}; +use crate::query::{Reader, Visible, equal}; use crate::schema::Table; use crate::sql::ast::{EdgePropagation, Propagation}; use crate::store::{Beside, ChangeSet, Read}; @@ -59,7 +59,7 @@ impl Rules<'_> { let Some(machine) = &table.meta.state_machine else { return Ok(()); }; - let at = column(table, &machine.column)?; + let at = table.column(&machine.column)?; let Value::Text(state) = &row[at] else { return Ok(()); }; @@ -92,7 +92,7 @@ impl Rules<'_> { let rule = reference.on_state.as_ref(); if reference.parent == table.name && rule.is_some_and(|r| r.on_state == *state) { let columns = reference.parent_columns.iter(); - let columns = columns.map(|name| column(table, name)); + let columns = columns.map(|name| table.column(name)); step( child, Via::Reference(place), @@ -103,7 +103,7 @@ impl Rules<'_> { } for (place, edge) in table.rules.propagate_edges.iter().enumerate() { if edge.rule.on_state == *state { - step(table, Via::Edge(place), &[column(table, "id")?])?; + step(table, Via::Edge(place), &[table.column("id")?])?; } } Ok(()) @@ -187,14 +187,14 @@ impl Walk<'_> { return Ok(()); } let given = self.given; - let key = [column(table, "id")?]; + let key = [table.column("id")?]; for edges in given.catalog.tables() { let mut indexes = edges.meta.indexes.iter(); if !indexes.any(|index| index.name.starts_with("__graph_edge_")) { continue; } - let ends = [column(edges, "source_id")?, column(edges, "target_id")?]; - let kind = column(edges, "edge_type")?; + let ends = [edges.column("source_id")?, edges.column("target_id")?]; + let kind = edges.column("edge_type")?; let rules = Rules::of(edges, given)?; for (near, far) in [(0, 1), (1, 0)] { if edge.direction == ["INCOMING", "OUTGOING"][near] { @@ -216,8 +216,8 @@ impl Walk<'_> { /// Moves to the state `rule` sets every row of `table` that holds `values` in `columns` /// and whose state lists that state as a next one, and notes who follows each. A row /// already in that state is passed by. A row in any other state is left as it is, or, - /// under `ABORT ON FAILURE`, refuses the statement; so is every row of a table whose rows - /// make no move: one with no state machine, and one that is IMMUTABLE or whose state is. + /// under `ABORT ON FAILURE`, refuses the statement; so is every row of a table with no + /// state machine. fn shift( &mut self, table: &Table, @@ -231,11 +231,7 @@ impl Walk<'_> { return Ok(()); } let machine = table.meta.state_machine.as_ref(); - let state = match machine { - Some(machine) if !table.meta.immutable => Some(column(table, &machine.column)?), - _ => None, - }; - let state = state.filter(|at| !table.rules.immutable_columns.contains(at)); + let state = machine.map(|m| table.column(&m.column)).transpose()?; if state.is_none() && !rule.abort_on_failure { return Ok(()); } diff --git a/v2/contextdb/src/write/rules.rs b/v2/contextdb/src/write/rules.rs index 0513f6bab..39ed58eea 100644 --- a/v2/contextdb/src/write/rules.rs +++ b/v2/contextdb/src/write/rules.rs @@ -4,8 +4,8 @@ use std::collections::BTreeSet; -use super::{Rules, column, equal}; -use crate::query::{self, Reader}; +use super::Rules; +use crate::query::{self, Reader, equal}; use crate::sql::{Expr, Plan}; use crate::store::{Cell, Key, Read}; use crate::types::{Error, Result, Uuid, Value}; @@ -37,11 +37,7 @@ impl Rules<'_> { }); } for (name, _) in assignments { - if table - .rules - .immutable_columns - .contains(&column(table, name)?) - { + if table.rules.immutable_columns.contains(&table.column(name)?) { return Err(Error::ImmutableColumn { table: table.name.clone(), column: name.clone(), @@ -58,7 +54,7 @@ impl Rules<'_> { let Some(machine) = &self.table.meta.state_machine else { return Ok(None); }; - let at = column(self.table, &machine.column)?; + let at = self.table.column(&machine.column)?; let moves = assigned.contains(&at); needed[at] |= moves; Ok(moves.then_some(at)) @@ -116,7 +112,7 @@ impl Rules<'_> { /// Where an edge's source, target and type are in a row. fn edge_columns(&self) -> Result<[usize; 3]> { let [source, target, kind] = - ["source_id", "target_id", "edge_type"].map(|name| column(self.table, name)); + ["source_id", "target_id", "edge_type"].map(|name| self.table.column(name)); Ok([source?, target?, kind?]) } diff --git a/v2/contextdb/src/write/tests.rs b/v2/contextdb/src/write/tests.rs index 6e1b1b404..e1c4b8f5c 100644 --- a/v2/contextdb/src/write/tests.rs +++ b/v2/contextdb/src/write/tests.rs @@ -1,10 +1,8 @@ -//! Tests of this part's two pure functions: reading a moment, and bringing a value to a type. - -use serde_json::json; +//! Tests of this part's two pure functions: reading a moment, and refusing a wrong type. use super::typed; use crate::types::timestamp_millis; -use crate::types::{ColumnDef, ColumnType, Error, Uuid, Value}; +use crate::types::{ColumnDef, ColumnType, Error, Value}; #[test] fn an_iso_8601_moment_is_read_as_milliseconds_since_1970_utc() { @@ -45,7 +43,7 @@ fn an_iso_8601_moment_is_read_as_milliseconds_since_1970_utc() { } #[test] -fn a_value_is_brought_to_its_columns_type_or_refused() { +fn a_value_of_another_type_is_refused_naming_the_type_expected_and_the_one_given() { let typed = |column_type, value| { let column = ColumnDef { name: "c".to_owned(), @@ -59,39 +57,7 @@ fn a_value_is_brought_to_its_columns_type_or_refused() { }; let text = |text: &str| Value::Text(text.to_owned()); - // The documented conversions, and a value that already is of the type. - for (column_type, given, stored) in [ - (ColumnType::Real, Value::Int64(2), Value::Float64(2.0)), - ( - ColumnType::Uuid, - text("550E8400-E29B-41D4-A716-446655440000"), - Value::Uuid(Uuid::from_u128(0x550e_8400_e29b_41d4_a716_4466_5544_0000)), - ), - ( - ColumnType::Timestamp, - text("1970-01-01T00:00:01Z"), - Value::Timestamp(1_000), - ), - ( - ColumnType::Json, - text(r#"[1, "two"]"#), - Value::Json(json!([1, "two"])), - ), - ( - ColumnType::Vector(3), - text("[1, 2.5, -3]"), - Value::Vector(vec![1.0, 2.5, -3.0]), - ), - (ColumnType::Text, text("kept"), text("kept")), - (ColumnType::Integer, Value::Null, Value::Null), - ] { - assert_eq!( - typed(column_type, given).expect("a value that fits"), - stored - ); - } - - // Anything else is refused by the column's name, and says what was expected and given. + // A value of another type is refused by the column's name, and says what was expected and given. for (column_type, given, expected, actual) in [ (ColumnType::Integer, text("three"), "INTEGER", "Text"), ( diff --git a/v2/contextdb/tests/alter.rs b/v2/contextdb/tests/alter.rs index df4a63f1c..45263c84b 100644 --- a/v2/contextdb/tests/alter.rs +++ b/v2/contextdb/tests/alter.rs @@ -5,15 +5,14 @@ mod support; -use std::fs; use std::path::Path; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use contextdb::serde_json::json; -use contextdb::{Clock, Database, DatabaseOpenOptions, Error, ReadSession, Value, params}; -use support::Call; +use contextdb::{Clock, Database, DatabaseOpenOptions, Error, Value, params}; +use support::{Call, data_file, printed, words}; /// A clock that always shows the same second. struct At(u64); @@ -30,60 +29,12 @@ fn open_at(folder: &Path, second: u64) -> Database { support::open_with(folder, options).expect("open the store with a clock") } -/// The length of a store's data file, in bytes. -fn data_file(folder: &Path) -> u64 { - fs::metadata(folder.join("data")) - .expect("the store's data file") - .len() -} - -/// What a table is printed back as. -fn printed(db: &Database, table: &str) -> String { - db.declaration(table) - .unwrap_or_else(|error| panic!("the declaration of {table} was refused: {error:?}")) -} - -/// The words of a declaration, in lower case, and its quoted texts: what it says, whatever -/// the spacing and the punctuation it says it in. -fn words(sql: &str) -> Vec { - let mut found = Vec::new(); - let mut rest = sql.chars().peekable(); - while let Some(first) = rest.next() { - if first == '\'' || first == '"' { - let mut text = String::from(first); - loop { - let next = rest.next().expect("a quoted text ends with its quote"); - text.push(next); - if next == first && rest.next_if_eq(&first).is_none() { - break; - } - } - found.push(text); - } else if first.is_ascii_alphanumeric() || first == '_' { - let mut word = String::from(first.to_ascii_lowercase()); - while let Some(next) = rest.next_if(|c| c.is_ascii_alphanumeric() || *c == '_') { - word.push(next.to_ascii_lowercase()); - } - found.push(word); - } - } - found -} - /// Whether a printed declaration says this clause: the clause's words, one after the other. fn says(declaration: &str, clause: &str) -> bool { let (text, clause) = (words(declaration), words(clause)); text.windows(clause.len()).any(|window| window == clause) } -/// The statements of a printed declaration. -fn statements(text: &str) -> Vec<&str> { - let ended = text.split(";\n"); - ended - .filter(|statement| !statement.trim().is_empty()) - .collect() -} - #[test] fn an_added_column_reads_its_default_from_a_row_written_before_it() { let folder = support::folder("added-column-default"); @@ -134,26 +85,26 @@ fn an_added_column_reads_its_default_from_a_row_written_before_it() { ); // A filter, a sort and a new index read the same defaults. - let ids = |sql: &str| -> Vec { - let rows = support::rows(&db, sql); - rows.iter() - .map(|row| match row[0] { - Value::Int64(id) => id, - ref other => panic!("{sql}\nreturned {other:?} for an id"), - }) - .collect() - }; assert_eq!( - ids("SELECT id FROM t WHERE n = 7 AND word = 'none' ORDER BY id"), + support::ids( + &db, + "SELECT id FROM t WHERE n = 7 AND word = 'none' ORDER BY id" + ), [1, 2, 3] ); assert_eq!( - ids("SELECT id FROM t WHERE plain IS NULL ORDER BY n, id"), + support::ids(&db, "SELECT id FROM t WHERE plain IS NULL ORDER BY n, id"), [1, 2, 3] ); support::run(&db, "CREATE INDEX t_by_n ON t (n, id)"); - assert_eq!(ids("SELECT id FROM t WHERE n = 7 ORDER BY id"), [1, 2, 3]); - assert_eq!(ids("SELECT id FROM t WHERE n = 8 ORDER BY id"), [0_i64; 0]); + assert_eq!( + support::ids(&db, "SELECT id FROM t WHERE n = 7 ORDER BY id"), + [1, 2, 3] + ); + assert_eq!( + support::ids(&db, "SELECT id FROM t WHERE n = 8 ORDER BY id"), + [0_i64; 0] + ); // A statement that changes another column of an older row leaves what the row reads in // the added ones; one that assigns an added column changes that column alone. @@ -165,8 +116,14 @@ fn an_added_column_reads_its_default_from_a_row_written_before_it() { support::rows(&db, all), [older(1, "renamed"), second.clone(), older(3, "c")] ); - assert_eq!(ids("SELECT id FROM t WHERE n = 7 ORDER BY id"), [1, 3]); - assert_eq!(ids("SELECT id FROM t WHERE n = 8 ORDER BY id"), [2]); + assert_eq!( + support::ids(&db, "SELECT id FROM t WHERE n = 7 ORDER BY id"), + [1, 3] + ); + assert_eq!( + support::ids(&db, "SELECT id FROM t WHERE n = 8 ORDER BY id"), + [2] + ); support::close(db); // Under a later clock the older rows read the time they read before, a row written now @@ -310,8 +267,7 @@ fn an_added_vector_column_is_null_on_older_rows_and_no_search_returns_them() { // The same once the vectors are in blocks, and after close and open. assert_eq!(support::seal_all(&db), 3); assert_eq!(found(&db, ""), ids(&[2, 5, 7])); - support::close(db); - let db = support::open(&folder); + let db = support::reopen(db, &folder); assert_eq!(found(&db, ""), ids(&[2, 5, 7])); assert_eq!(found(&db, "WHERE ctx = 'b'"), ids(&[5])); let with_vector = vectors(&db) @@ -354,10 +310,7 @@ fn a_dropped_columns_bytes_leave_the_store() { let store = |test: &str, drop: bool| -> u64 { let folder = support::folder(test); let db = support::open(&folder); - support::run( - &db, - "CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT)", - ); + support::run(&db, support::NOTES); fill(&db, "notes", "body", true, 0); if drop { support::run(&db, "ALTER TABLE notes DROP COLUMN body"); @@ -427,7 +380,7 @@ fn a_dropped_table_leaves_no_record() { // Nothing answers for the dropped table: not the writer, not a reader, not after close // and open; and a table declared under its name starts empty, with none of its indexes. let db = support::open(&folder); - let reader = ReadSession::open(&folder).expect("open the store for reading"); + let reader = support::open_reader(&folder, None); assert_eq!(db.table_names(), ["two"]); assert_eq!(reader.table_names().expect("a reader's tables"), ["two"]); let missing = |error: Error, what: &str| { @@ -539,8 +492,6 @@ enum Refused { /// `DropBlockedByRankPolicy` for this table and the policy of `ranked`, and for this /// column where the statement names one. Ranked(&'static str, Option<&'static str>), - /// `TableNotFound` for the table `nope`. - NoTable, } impl Refused { @@ -578,7 +529,6 @@ impl Refused { && policy == "effective_confidence" && named.is_none_or(|named| column == named) } - (Refused::NoTable, Error::TableNotFound(name)) => name == "nope", _ => false, } } @@ -618,14 +568,10 @@ fn each_dependent_refusal_names_what_depends_and_changes_nothing() { ), // A column of the key, a table another references, and a column that makes a DAG // table a table of edges. - ("ALTER TABLE t DROP COLUMN id", Refused::Invalid), - ("ALTER TABLE t RENAME COLUMN id TO key", Refused::Invalid), ( "ALTER TABLE parents DROP COLUMN id CASCADE", Refused::Invalid, ), - ("DROP TABLE parents", Refused::Invalid), - ("DROP TABLE IF EXISTS parents", Refused::Invalid), ("ALTER TABLE edges DROP COLUMN source_id", Refused::Invalid), ( "ALTER TABLE edges DROP COLUMN target_id CASCADE", @@ -658,15 +604,6 @@ fn each_dependent_refusal_names_what_depends_and_changes_nothing() { ), // A column that may hold no NULL, with no default, on a table that has rows; a name // that is taken; a second key. - ( - "ALTER TABLE t ADD COLUMN must TEXT NOT NULL", - Refused::Invalid, - ), - ("ALTER TABLE t ADD COLUMN a INTEGER", Refused::Invalid), - ( - "ALTER TABLE t ADD COLUMN k INTEGER PRIMARY KEY", - Refused::Invalid, - ), ("ALTER TABLE t RENAME COLUMN a TO b", Refused::Invalid), // Options that cannot stand. ( @@ -675,11 +612,6 @@ fn each_dependent_refusal_names_what_depends_and_changes_nothing() { ), ("ALTER TABLE t SET MAINTAIN COUNT (kind)", Refused::Invalid), ("ALTER TABLE t SET MAINTAIN COUNT (id)", Refused::Invalid), - // What is not there. - ("DROP TABLE nope", Refused::NoTable), - ("ALTER TABLE nope ADD COLUMN c TEXT", Refused::NoTable), - ("ALTER TABLE nope DROP COLUMN c", Refused::NoTable), - ("DROP INDEX t_first ON nope", Refused::NoTable), ]; for (sql, refused) in &cases { let error = support::refusal(&db, sql); @@ -715,31 +647,17 @@ fn each_dependent_refusal_names_what_depends_and_changes_nothing() { other => panic!("{sql}\nwas refused as {other:?}"), } } - // A limit on partitions below the partitions the column has. No document says which of - // the two kinds this is. + // A limit on partitions below the partitions the column has. let error = support::refusal(&db, "ALTER TABLE t ALTER COLUMN v SET MAX_PARTITIONS 1"); assert!( matches!( &error, - Error::VectorPartitionLimitExceeded { index, .. } - | Error::InvalidVectorPartitionDeclaration { index, .. } + Error::VectorPartitionLimitExceeded { index, max_partitions: 1 } if index.table == "t" && index.column == "v" ), "a limit of one partition on a column that has two was refused as {error:?}" ); assert!(state(&db) == before); - // With IF EXISTS, a table or an index that is not there is nothing to do, and changes - // no declaration and no row. - for sql in [ - "DROP TABLE IF EXISTS nope", - "DROP INDEX IF EXISTS nope ON t", - ] { - let result = support::run(&db, sql); - assert_eq!(result.rows_affected(), 0, "{sql}"); - assert!(result.rows().is_empty(), "{sql}"); - } - let after = state(&db); - assert!(after.0 == before.0 && after.1 == before.1 && after.2 == before.2); } #[test] @@ -885,7 +803,9 @@ fn an_altered_table_is_printed_as_what_it_now_declares() { let mut db = db; for (number, (sql, now, no_longer)) in steps.iter().enumerate() { support::run(&db, sql); - let text = printed(&db, "t"); + // The printed texts declare the same two tables in an empty store. + let prefix = format!("altered-printed-{number}"); + let text = support::assert_roundtrips(&prefix, &db, &["parents", "t"]).remove(1); for clause in *now { assert!( says(&text, clause), @@ -898,20 +818,6 @@ fn an_altered_table_is_printed_as_what_it_now_declares() { "after {sql}\nstill `{clause}` in:\n{text}" ); } - // The printed texts declare the same two tables in an empty store. - let again = support::open(&support::folder(&format!("altered-printed-again-{number}"))); - for table in ["parents", "t"] { - let declared = printed(&db, table); - for statement in statements(&declared) { - support::run(&again, statement); - } - } - assert_eq!(printed(&again, "t"), text, "after {sql}, declared again"); - assert_eq!( - printed(&again, "parents"), - printed(&db, "parents"), - "after {sql}" - ); // And the store says the same after close and open. support::close(db); db = support::open(&folder); @@ -996,8 +902,7 @@ fn a_renamed_vector_column_keeps_its_declaration_and_its_vectors() { } other => panic!("a fourth partition gave {other:?}"), } - support::close(db); - let db = support::open(&folder); + let db = support::reopen(db, &folder); assert_eq!( nearest(&db, "embedding", "WHERE ctx = 'a'").expect("a search"), of_a @@ -1107,9 +1012,7 @@ fn a_vector_column_far_larger_than_the_memory_limit_is_dropped_under_it() { let held = data_file(&folder); // 9 MiB is what a store needs to open at all. The 192 KiB above it are less than // a tenth of the vectors, which is 256,000 bytes. - let mut options = DatabaseOpenOptions::default(); - options.memory_limit = Some(9 * MIB + 192 * KIB); - let db = support::open_with(&folder, options).expect("open under the limit"); + let db = support::open_limited(&folder, 9 * MIB + 192 * KIB); let sql = "ALTER TABLE docs DROP COLUMN v"; if let Err(error) = db.execute(sql, ¶ms! {}) { panic!("{sql}\nof {VECTORS} vectors was refused under the limit: {error:?}"); @@ -1147,10 +1050,7 @@ fn a_column_added_and_dropped_in_one_transaction_leaves_nothing_stored() { let store = |test: &str, churn: bool| -> u64 { let folder = support::folder(test); let db = support::open(&folder); - support::run( - &db, - "CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT)", - ); + support::run(&db, support::NOTES); fill(&db, "notes", "body", true, 0); if churn { let before = printed(&db, "notes"); diff --git a/v2/contextdb/tests/clock.rs b/v2/contextdb/tests/clock.rs index f29bcc77f..a8e145836 100644 --- a/v2/contextdb/tests/clock.rs +++ b/v2/contextdb/tests/clock.rs @@ -81,6 +81,25 @@ fn default_now_stores_the_time_the_clock_door_gives() { support::int(&db, "SELECT COUNT(*) FROM events WHERE created < NOW()"), 1 ); + + // A clock set before 1970 gives a negative number of milliseconds, not zero or a refusal. + struct Before; + impl Clock for Before { + fn now(&self) -> SystemTime { + UNIX_EPOCH - Duration::from_millis(1_500) + } + } + let mut options = DatabaseOpenOptions::default(); + options.clock = Some(Arc::new(Before)); + let early = support::open_with(&support::folder("clock-before-1970"), options) + .expect("open the store under a clock before 1970"); + let declared = "CREATE TABLE e (id INTEGER PRIMARY KEY, made TIMESTAMP NOT NULL DEFAULT NOW())"; + support::run(&early, declared); + support::run(&early, "INSERT INTO e (id) VALUES (1)"); + assert_eq!( + support::rows(&early, "SELECT made FROM e"), + [[Value::Timestamp(-1_500)]] + ); } #[test] diff --git a/v2/contextdb/tests/counted_work.rs b/v2/contextdb/tests/counted_work.rs index db6053a52..36bc157a8 100644 --- a/v2/contextdb/tests/counted_work.rs +++ b/v2/contextdb/tests/counted_work.rs @@ -22,10 +22,7 @@ fn store(name: &str) -> (PathBuf, Database) { "CREATE TABLE events (id INTEGER PRIMARY KEY, kind TEXT NOT NULL, seq INTEGER NOT NULL, \ note TEXT)", ); - support::run( - &db, - "CREATE INDEX events_kind_seq ON events (kind ASC, seq DESC)", - ); + support::run(&db, support::EVENTS_INDEX); let tx = db.transaction().expect("begin"); support::insert(&tx, 1..=1000); for n in 1..=1000_i64 { @@ -87,6 +84,10 @@ fn a_lookup_by_primary_key_reads_one_row() { let missing = support::run(&db, "SELECT id, name, tag FROM t WHERE id = 5000"); assert!(missing.rows().is_empty()); assert_eq!(missing.rows_examined(), 0); + let sql = "SELECT id FROM t WHERE id IN (SELECT id FROM events WHERE id = 5)"; + let found = support::run(&db, sql); + assert_eq!(found.rows(), [[Value::Int64(5)]]); + assert_eq!(found.rows_examined(), 2, "a key from a SELECT"); } #[test] diff --git a/v2/contextdb/tests/crash/main.rs b/v2/contextdb/tests/crash/main.rs index bda57b41a..52e945dcd 100644 --- a/v2/contextdb/tests/crash/main.rs +++ b/v2/contextdb/tests/crash/main.rs @@ -16,7 +16,8 @@ mod support; use std::collections::BTreeSet; use std::fs; use std::io; -use std::path::PathBuf; +use std::ops::RangeInclusive; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; @@ -27,6 +28,36 @@ use contextdb::{ use support::{Call, Child, Run}; +/// Runs the child `role` of `test` over `folder` to its end, and returns what it announced: the +/// storage calls made when the work under test began (announced under the word `begins`, none +/// for 0), the calls in all, and every line. +fn learned(test: &str, role: &str, folder: &Path, begins: Option<&str>) -> (u64, u64, Vec) { + let lines = Child::start(test, &format!("{role} stop_at=0"), folder).end(); + let announced = |word: &str| { + support::last_number(&lines, word).unwrap_or_else(|| panic!("the {role} announces {word}")) + }; + (begins.map_or(0, announced), announced("calls"), lines) +} + +/// For each storage call in `calls`: makes a store, runs the child `role` of `test` over it until +/// it stops before that call, kills it, and gives `after` the call, the store and the lines the +/// child announced before it stopped. +fn for_each_stop( + test: &str, + role: &str, + calls: RangeInclusive, + store: impl Fn(u64) -> PathBuf, + mut after: impl FnMut(u64, &Path, &[String]), +) { + for k in calls { + let folder = store(k); + let mut child = Child::start(test, &format!("{role} stop_at={k}"), &folder); + let announced = child.until("stopped"); + child.kill(); + after(k, &folder, &announced); + } +} + #[test] fn a_kill_at_any_storage_call_of_a_commit_leaves_all_or_nothing() { if let Some(role) = support::role() { @@ -34,19 +65,15 @@ fn a_kill_at_any_storage_call_of_a_commit_leaves_all_or_nothing() { } let test = "a_kill_at_any_storage_call_of_a_commit_leaves_all_or_nothing"; // Run once to the end to learn how many storage calls five commits make. - let lines = Child::start(test, "writer stop_at=0", &store_with_rows("kill-count", 0)).end(); - let calls = support::last_number(&lines, "calls").expect("the writer announces its calls"); + let (_, calls, _) = learned(test, "writer", &store_with_rows("kill-count", 0), None); assert!(calls >= 5, "five commits made {calls} writes and syncs"); - for k in 1..=calls { - let folder = store_with_rows(&format!("kill-at-{k}"), 0); - let mut writer = Child::start(test, &format!("writer stop_at={k}"), &folder); - let before = writer.until("stopped"); - writer.kill(); + let store = |k| store_with_rows(&format!("kill-at-{k}"), 0); + for_each_stop(test, "writer", 1..=calls, store, |k, folder, before| { // Commits that had returned before the kill. - let committed = support::last_number(&before, "committed").unwrap_or(0) as i64; + let committed = support::last_number(before, "committed").unwrap_or(0) as i64; - let db = support::open(&folder); // it must open: there is nothing to mend by hand + let db = support::open(folder); // it must open: there is nothing to mend by hand let rows = support::int(&db, "SELECT COUNT(*) FROM t"); assert!( rows == committed || rows == committed + 1, @@ -56,16 +83,13 @@ fn a_kill_at_any_storage_call_of_a_commit_leaves_all_or_nothing() { // The store goes on from the state it reopened at. support::insert(&db, rows + 1..=rows + 1); support::assert_rows_are(&db, 1..=rows + 1); - } + }); } /// Commits rows 1 to 5, one commit each, announcing `committed ` after each one returns, and /// `calls ` once the store is closed. fn five_commits(role: support::Role) { - let (storage, calls) = stopping_before_call(role.number("stop_at")); - let mut options = DatabaseOpenOptions::default(); - options.storage = Some(storage); - let db = support::open_with(&role.folder, options).expect("open"); + let (db, calls) = open_stopping(&role); for n in 1..=5 { support::insert(&db, n..=n); support::say(format!("committed {n}")); @@ -81,48 +105,42 @@ fn a_kill_inside_a_commit_of_many_rows_keeps_rows_index_and_count_together() { } let test = "a_kill_inside_a_commit_of_many_rows_keeps_rows_index_and_count_together"; // Run once to the end to learn which storage calls belong to the large commit. - let lines = Child::start( - test, - "writer stop_at=0", - &store_with_rows("kill-large-count", 10), - ) - .end(); - let begins = support::last_number(&lines, "committing").expect("the writer announces it"); - let calls = support::last_number(&lines, "calls").expect("the writer announces its calls"); + let folder = store_with_rows("kill-large-count", 10); + let (begins, calls, _) = learned(test, "writer", &folder, Some("committing")); assert!( calls > begins, "a commit of a thousand rows made no write and no sync" ); - for k in begins + 1..=calls { - let folder = store_with_rows(&format!("kill-large-at-{k}"), 10); - let mut writer = Child::start(test, &format!("writer stop_at={k}"), &folder); - let before = writer.until("stopped"); - writer.kill(); - let returned = before.iter().any(|line| line == "committed"); - - // The store holds the rows from before the commit or the rows from after it, and in - // either case its rows, its index and its kept count say the same. - let db = support::open(&folder); - match support::int(&db, "SELECT COUNT(*) FROM t") { - 10 if !returned => support::assert_rows_are(&db, 1..=10), - 1005 => support::assert_rows_are(&db, 6..=1010), - rows => panic!( - "killed at storage call {k}: {rows} rows are there; the commit had {}returned", - if returned { "" } else { "not " } - ), - } - } + let store = |k| store_with_rows(&format!("kill-large-at-{k}"), 10); + for_each_stop( + test, + "writer", + begins + 1..=calls, + store, + |k, folder, before| { + let returned = before.iter().any(|line| line == "committed"); + + // The store holds the rows from before the commit or the rows from after it, and in + // either case its rows, its index and its kept count say the same. + let db = support::open(folder); + match support::int(&db, "SELECT COUNT(*) FROM t") { + 10 if !returned => support::assert_rows_are(&db, 1..=10), + 1005 => support::assert_rows_are(&db, 6..=1010), + rows => panic!( + "killed at storage call {k}: {rows} rows are there; the commit had {}returned", + if returned { "" } else { "not " } + ), + } + }, + ); } /// In one transaction removes rows 1 to 5 and adds rows 11 to 1010. Announces `committing ` /// with the storage calls made so far when the commit is about to begin, `committed` when it /// has returned, and `calls ` once the store is closed. fn one_large_commit(role: support::Role) { - let (storage, calls) = stopping_before_call(role.number("stop_at")); - let mut options = DatabaseOpenOptions::default(); - options.storage = Some(storage); - let db = support::open_with(&role.folder, options).expect("open"); + let (db, calls) = open_stopping(&role); let tx = db.transaction().expect("begin"); support::run(&tx, "DELETE FROM t WHERE id <= 5"); support::insert(&tx, 11..=1010); @@ -290,7 +308,7 @@ fn a_commit_on_disk_is_reported_and_served_though_the_read_after_it_fails() { }; let db = support::open_with(&folder, options()).expect("open"); support::declare(&db); - // A second table four times the size of that 8 MiB page cache, in rows small enough to be + // A second table twice the size of that 8 MiB page cache, in rows small enough to be // kept in the table's own pages and of text that no compressor shortens, so that a row takes // the room it is written with. Reading all of it leaves the cache full of its pages, so // the pages a commit writes afterwards have to be read back from the file. @@ -508,9 +526,7 @@ fn a_kill_at_any_storage_call_of_a_seal_leaves_every_vector_found() { let folder = store_with_vectors("kill-seal-count"); let rows = searches_agree(&support::open(&folder), "before the cycle"); assert_eq!(rows.len(), 300); - let lines = Child::start(test, "sealer stop_at=0", &folder).end(); - let begins = support::last_number(&lines, "sealing").expect("the sealer announces it"); - let calls = support::last_number(&lines, "calls").expect("the sealer announces its calls"); + let (begins, calls, lines) = learned(test, "sealer", &folder, Some("sealing")); assert!( lines.iter().any(|line| line == "sealed 200 0"), "one cycle was to seal the 200 pending vectors: {lines:?}" @@ -520,53 +536,53 @@ fn a_kill_at_any_storage_call_of_a_seal_leaves_every_vector_found() { "a cycle that sealed 200 vectors made no write and no sync" ); - for k in begins + 1..=calls { - let folder = store_with_vectors(&format!("kill-seal-at-{k}")); - let mut sealer = Child::start(test, &format!("sealer stop_at={k}"), &folder); - let before = sealer.until("stopped"); - sealer.kill(); - let returned = before.iter().any(|line| line.starts_with("sealed ")); - - // The store opens with nothing to mend, every row is there, and every search finds - // exactly the vectors of those rows, whether the seal's commit is there or not. - let db = support::open(&folder); - let state = format!("killed at storage call {k} of a seal"); - assert!( - searches_agree(&db, &state) == rows, - "{state}: the rows of docs" - ); - // The next cycles finish the sealing: all 200 vectors when the killed commit is not - // there, none when it is. A cycle that had returned is there. - let sealed = support::seal_all(&db); - assert!( - sealed == 0 || sealed == 200 && !returned, - "{state}: the next cycles sealed {sealed} vectors; the killed cycle had {}returned", - if returned { "" } else { "not " } - ); - let report = db.run_maintenance_cycle().expect("one more cycle").vector; - assert_eq!( - ( - report.maintenance_vectors_done, - report.maintenance_vectors_remaining - ), - (0, 0), - "{state}: a cycle after the sealing was finished" - ); - assert!( - searches_agree(&db, &state) == rows, - "{state}: the rows after sealing" - ); - } + let store = |k| store_with_vectors(&format!("kill-seal-at-{k}")); + for_each_stop( + test, + "sealer", + begins + 1..=calls, + store, + |k, folder, before| { + let returned = before.iter().any(|line| line.starts_with("sealed ")); + + // The store opens with nothing to mend, every row is there, and every search finds + // exactly the vectors of those rows, whether the seal's commit is there or not. + let db = support::open(folder); + let state = format!("killed at storage call {k} of a seal"); + assert!( + searches_agree(&db, &state) == rows, + "{state}: the rows of docs" + ); + // The next cycles finish the sealing: all 200 vectors when the killed commit is not + // there, none when it is. A cycle that had returned is there. + let sealed = support::seal_all(&db); + assert!( + sealed == 0 || sealed == 200 && !returned, + "{state}: the next cycles sealed {sealed} vectors; the killed cycle had {}returned", + if returned { "" } else { "not " } + ); + let report = db.run_maintenance_cycle().expect("one more cycle").vector; + assert_eq!( + ( + report.maintenance_vectors_done, + report.maintenance_vectors_remaining + ), + (0, 0), + "{state}: a cycle after the sealing was finished" + ); + assert!( + searches_agree(&db, &state) == rows, + "{state}: the rows after sealing" + ); + }, + ); } /// Runs one maintenance cycle. Announces `sealing ` with the storage calls made so far when /// the cycle is about to begin, `sealed ` when it has returned, and /// `calls ` once the store is closed. fn one_seal(role: support::Role) { - let (storage, calls) = stopping_before_call(role.number("stop_at")); - let mut options = DatabaseOpenOptions::default(); - options.storage = Some(storage); - let db = support::open_with(&role.folder, options).expect("open"); + let (db, calls) = open_stopping(&role); support::say(format!("sealing {}", calls.load(Ordering::SeqCst))); let report = db.run_maintenance_cycle().expect("a cycle").vector; support::say(format!( @@ -588,9 +604,7 @@ fn a_kill_inside_a_commit_of_vectors_keeps_rows_and_vectors_together() { let untouched = store_with_vectors("kill-vectors-before"); let before = searches_agree(&support::open(&untouched), "before the commit"); let folder = store_with_vectors("kill-vectors-count"); - let lines = Child::start(test, "writer stop_at=0", &folder).end(); - let begins = support::last_number(&lines, "committing").expect("the writer announces it"); - let calls = support::last_number(&lines, "calls").expect("the writer announces its calls"); + let (begins, calls, _) = learned(test, "writer", &folder, Some("committing")); assert!( calls > begins, "a commit of sixty vectors made no write and no sync" @@ -598,33 +612,36 @@ fn a_kill_inside_a_commit_of_vectors_keeps_rows_and_vectors_together() { let after = searches_agree(&support::open(&folder), "after the commit"); assert_eq!((before.len(), after.len()), (300, 358)); - for k in begins + 1..=calls { - let folder = store_with_vectors(&format!("kill-vectors-at-{k}")); - let mut writer = Child::start(test, &format!("writer stop_at={k}"), &folder); - let told = writer.until("stopped"); - writer.kill(); - let returned = told.iter().any(|line| line == "committed"); - - // The rows are those of before the commit or those of after it, and the searches - // answer from the vectors of exactly those rows: never rows of one and vectors of the - // other. A commit that had returned is there. - let db = support::open(&folder); - let state = format!("killed at storage call {k} of a commit of vectors"); - let rows = searches_agree(&db, &state); - assert!( - rows == after || rows == before && !returned, - "{state}: {} rows are there, of neither state or of the wrong one; the commit had \ + let store = |k| store_with_vectors(&format!("kill-vectors-at-{k}")); + for_each_stop( + test, + "writer", + begins + 1..=calls, + store, + |k, folder, told| { + let returned = told.iter().any(|line| line == "committed"); + + // The rows are those of before the commit or those of after it, and the searches + // answer from the vectors of exactly those rows: never rows of one and vectors of the + // other. A commit that had returned is there. + let db = support::open(folder); + let state = format!("killed at storage call {k} of a commit of vectors"); + let rows = searches_agree(&db, &state); + assert!( + rows == after || rows == before && !returned, + "{state}: {} rows are there, of neither state or of the wrong one; the commit had \ {}returned", - rows.len(), - if returned { "" } else { "not " } - ); - // The store goes on from there: what waits is sealed, and the answers stay. - support::seal_all(&db); - assert!( - searches_agree(&db, &state) == rows, - "{state}: the rows after sealing" - ); - } + rows.len(), + if returned { "" } else { "not " } + ); + // The store goes on from there: what waits is sealed, and the answers stay. + support::seal_all(&db); + assert!( + searches_agree(&db, &state) == rows, + "{state}: the rows after sealing" + ); + }, + ); } /// In one transaction adds rows 301 to 360, a third of them under a context that has rows and @@ -633,10 +650,7 @@ fn a_kill_inside_a_commit_of_vectors_keeps_rows_and_vectors_together() { /// `committing ` with the storage calls made so far when the commit is about to begin, /// `committed` when it has returned, and `calls ` once the store is closed. fn one_commit_of_vectors(role: support::Role) { - let (storage, calls) = stopping_before_call(role.number("stop_at")); - let mut options = DatabaseOpenOptions::default(); - options.storage = Some(storage); - let db = support::open_with(&role.folder, options).expect("open"); + let (db, calls) = open_stopping(&role); let tx = db.transaction().expect("begin"); support::insert_docs(&tx, 301..=360, DIMENSION, |n| { ["c0", "new", "newer"][(n % 3) as usize].to_owned() @@ -784,9 +798,7 @@ fn a_kill_inside_a_commit_keeps_references_counts_and_long_entries_with_their_ro let test = "a_kill_inside_a_commit_keeps_references_counts_and_long_entries_with_their_rows"; // Run once to the end to learn which storage calls belong to the commit. let folder = store_with_children("kill-children-count"); - let lines = Child::start(test, "writer stop_at=0", &folder).end(); - let begins = support::last_number(&lines, "committing").expect("the writer announces it"); - let calls = support::last_number(&lines, "calls").expect("the writer announces its calls"); + let (begins, calls, _) = learned(test, "writer", &folder, Some("committing")); assert!(calls > begins, "the commit made no write and no sync"); assert_children_are( &support::open(&folder), @@ -794,42 +806,45 @@ fn a_kill_inside_a_commit_keeps_references_counts_and_long_entries_with_their_ro "after the whole commit", ); - for k in begins + 1..=calls { - let folder = store_with_children(&format!("kill-children-at-{k}")); - let mut writer = Child::start(test, &format!("writer stop_at={k}"), &folder); - let before = writer.until("stopped"); - writer.kill(); - let returned = before.iter().any(|line| line == "committed"); - - // The store holds what it held before the commit, or everything the commit brought. - let db = support::open(&folder); - let when = format!("killed at storage call {k}"); - let committed = match support::int(&db, "SELECT COUNT(*) FROM children") { - 6 if !returned => false, - 16 => true, - rows => panic!( - "{when}: {rows} children are there; the commit had {}returned", - if returned { "" } else { "not " } - ), - }; - assert_children_are(&db, &children(committed), &when); - let parents = support::int(&db, "SELECT COUNT(*) FROM parents"); - assert_eq!( - parents, - if committed { 3 } else { 2 }, - "{when}: the parents" - ); - - // The store goes on from that state, and its rules with it. - let mut wanted = children(committed); - wanted.push((50, 1, body(50))); - insert_child(&db, (50, 1, body(50))).expect("insert a child after reopening"); - assert_children_are(&db, &wanted, &format!("{when}, and one more child")); - assert!(matches!( - insert_child(&db, (51, 404, body(51))), - Err(Error::ForeignKeyViolation { .. }) - )); - } + let store = |k| store_with_children(&format!("kill-children-at-{k}")); + for_each_stop( + test, + "writer", + begins + 1..=calls, + store, + |k, folder, before| { + let returned = before.iter().any(|line| line == "committed"); + + // The store holds what it held before the commit, or everything the commit brought. + let db = support::open(folder); + let when = format!("killed at storage call {k}"); + let committed = match support::int(&db, "SELECT COUNT(*) FROM children") { + 6 if !returned => false, + 16 => true, + rows => panic!( + "{when}: {rows} children are there; the commit had {}returned", + if returned { "" } else { "not " } + ), + }; + assert_children_are(&db, &children(committed), &when); + let parents = support::int(&db, "SELECT COUNT(*) FROM parents"); + assert_eq!( + parents, + if committed { 3 } else { 2 }, + "{when}: the parents" + ); + + // The store goes on from that state, and its rules with it. + let mut wanted = children(committed); + wanted.push((50, 1, body(50))); + insert_child(&db, (50, 1, body(50))).expect("insert a child after reopening"); + assert_children_are(&db, &wanted, &format!("{when}, and one more child")); + assert!(matches!( + insert_child(&db, (51, 404, body(51))), + Err(Error::ForeignKeyViolation { .. }) + )); + }, + ); } /// In one transaction adds a parent and twelve children, removes two children, gives one another @@ -837,10 +852,7 @@ fn a_kill_inside_a_commit_keeps_references_counts_and_long_entries_with_their_ro /// when the commit is about to begin, `committed` when it has returned, and `calls ` once /// the store is closed. fn one_commit_of_children(role: support::Role) { - let (storage, calls) = stopping_before_call(role.number("stop_at")); - let mut options = DatabaseOpenOptions::default(); - options.storage = Some(storage); - let db = support::open_with(&role.folder, options).expect("open"); + let (db, calls) = open_stopping(&role); let tx = db.transaction().expect("begin"); support::run(&tx, "INSERT INTO parents (id) VALUES (3)"); for child in children(true).split_off(4) { @@ -865,13 +877,23 @@ fn store_with_rows(name: &str, rows: i64) -> PathBuf { let folder = support::folder(name); let db = support::open(&folder); support::declare(&db); - let tx = db.transaction().expect("begin"); - support::insert(&tx, 1..=rows); - tx.commit().expect("commit"); + support::insert_together(&db, 1..=rows); support::close(db); folder } +/// Opens the child's store through a door that stops before the call the role names, and gives +/// the store with the door's count of calls. +fn open_stopping(role: &support::Role) -> (Database, Arc) { + let (storage, calls) = stopping_before_call(role.number("stop_at")); + let mut options = DatabaseOpenOptions::default(); + options.storage = Some(storage); + ( + support::open_with(&role.folder, options).expect("open"), + calls, + ) +} + /// A storage door that counts the writes and syncs of the data file. Before call number /// `stop_at` it announces `stopped` and waits there to be killed, so that call and every later /// one never reach the file. `stop_at` 0 never stops. Returns the door and its count. @@ -898,7 +920,7 @@ fn stopping_before_call(stop_at: u64) -> (WrapStorage, Arc) { fn store_to_build(name: &str, rows: i64) -> PathBuf { let folder = support::folder(name); let db = support::open(&folder); - support::declare_docs(&db, DIMENSION, &format!("AUTO_INDEX_AT {}", rows / 3)); + support::declare_docs(&db, DIMENSION, &format!("INDEXING_THRESHOLD {}", rows / 3)); support::load_docs(&db, 1..=rows, "a", |n| support::gathered(n, DIMENSION)); support::close(db); folder @@ -940,26 +962,27 @@ fn a_kill_at_any_storage_call_of_a_build_leaves_every_vector_found() { const ROWS: i64 = 12; // Run once to the end to learn which storage calls belong to the cycles of the build. let folder = store_to_build("kill-build-count", ROWS); - let lines = Child::start(test, "builder stop_at=0", &folder).end(); - let begins = support::last_number(&lines, "building").expect("the builder announces it"); - let calls = support::last_number(&lines, "calls").expect("the builder announces its calls"); + let (begins, calls, lines) = learned(test, "builder", &folder, Some("building")); assert_eq!(support::last_number(&lines, "cycles"), Some(16)); assert_eq!(groups(&support::open(&folder)), Value::Int64(3)); - for k in begins + 1..=calls { - let folder = store_to_build(&format!("kill-build-at-{k}"), ROWS); - let mut builder = Child::start(test, &format!("builder stop_at={k}"), &folder); - builder.until("stopped"); - builder.kill(); - // The store opens with nothing to mend and every vector is found, whichever step's - // commit the kill fell in; the next cycles finish the build. - let db = support::open(&folder); - let state = format!("killed at storage call {k} of a build"); - every_vector_is_found(&db, ROWS as usize, &state); - support::upkeep(&db); - assert_eq!(groups(&db), Value::Int64(3), "{state}"); - every_vector_is_found(&db, ROWS as usize, &format!("{state}, then built")); - } + let store = |k| store_to_build(&format!("kill-build-at-{k}"), ROWS); + for_each_stop( + test, + "builder", + begins + 1..=calls, + store, + |k, folder, _| { + // The store opens with nothing to mend and every vector is found, whichever step's + // commit the kill fell in; the next cycles finish the build. + let db = support::open(folder); + let state = format!("killed at storage call {k} of a build"); + every_vector_is_found(&db, ROWS as usize, &state); + support::upkeep(&db); + assert_eq!(groups(&db), Value::Int64(3), "{state}"); + every_vector_is_found(&db, ROWS as usize, &format!("{state}, then built")); + }, + ); } #[test] @@ -969,9 +992,7 @@ fn a_killed_build_goes_on_from_its_record() { } let test = "a_killed_build_goes_on_from_its_record"; let folder = store_to_build("killed-build-count", 300); - let lines = Child::start(test, "builder stop_at=0", &folder).end(); - let begins = support::last_number(&lines, "building").expect("the builder announces it"); - let calls = support::last_number(&lines, "calls").expect("the builder announces its calls"); + let (begins, calls, lines) = learned(test, "builder", &folder, Some("building")); let whole = support::last_number(&lines, "cycles").expect("the builder counts its cycles"); assert_eq!(whole, 16); @@ -1002,10 +1023,7 @@ fn a_killed_build_goes_on_from_its_record() { /// calls made so far before the first, `cycles ` as each returns, and `calls ` once /// the store is closed. fn one_build(role: support::Role) { - let (storage, calls) = stopping_before_call(role.number("stop_at")); - let mut options = DatabaseOpenOptions::default(); - options.storage = Some(storage); - let db = support::open_with(&role.folder, options).expect("open"); + let (db, calls) = open_stopping(&role); support::say(format!("building {}", calls.load(Ordering::SeqCst))); for cycles in 1_u64.. { let report = support::cycle(&db); diff --git a/v2/contextdb/tests/declarations.rs b/v2/contextdb/tests/declarations.rs index 3a2ad33e2..c33ae4aeb 100644 --- a/v2/contextdb/tests/declarations.rs +++ b/v2/contextdb/tests/declarations.rs @@ -7,7 +7,8 @@ mod support; use std::collections::{BTreeMap, BTreeSet}; -use contextdb::{Database, Error, ReadSession}; +use contextdb::{Database, Error}; +use support::{printed, words}; /// The declarations of a program built on this library, as that program writes them. const CONSUMER_SCHEMA: &str = include_str!("fixtures/consumer_schema.sql"); @@ -69,49 +70,6 @@ fn referenced(sql: &str) -> BTreeSet { parents.filter(|parent| *parent != own).collect() } -/// The words of a declaration in lower case and its quoted texts as they are written: what the -/// declaration says, whatever the order, the spacing and the punctuation it says it in. A type -/// is given the name it is printed under, and a quoted name that needs no quotes loses them. -fn words(sql: &str) -> Vec { - let mut found = Vec::new(); - let mut rest = sql.chars().peekable(); - while let Some(first) = rest.next() { - if first == '\'' || first == '"' { - let mut text = String::from(first); - loop { - let next = rest.next().expect("a quoted text ends with its quote"); - text.push(next); - // The quote written twice is one quote of the text. - if next == first && rest.next_if_eq(&first).is_none() { - break; - } - } - let inner = &text[1..text.len() - 1]; - let plain = first == '"' - && inner.starts_with(|c: char| c.is_ascii_lowercase() || c == '_') - && inner - .chars() - .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'); - found.push(if plain { inner.to_owned() } else { text }); - } else if first.is_ascii_alphanumeric() || first == '_' { - let mut word = String::from(first.to_ascii_lowercase()); - while let Some(next) = - rest.next_if(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '.') - { - word.push(next.to_ascii_lowercase()); - } - match word.as_str() { - "int" => found.push("integer".to_owned()), - "bool" => found.push("boolean".to_owned()), - "float" => found.push("real".to_owned()), - "state_machine" => found.extend(["state".to_owned(), "machine".to_owned()]), - _ => found.push(word), - } - } - } - found -} - /// Asserts that the text a table is printed back as says everything its author wrote and /// nothing else. `written` is the table's `CREATE TABLE` and each `CREATE INDEX` on it. fn assert_prints_what_was_written(written: &[&str], printed: &str, table: &str) { @@ -155,12 +113,6 @@ fn declare>(db: &Database, statements: impl IntoIterator } } -/// What a table is printed back as. -fn printed(db: &Database, table: &str) -> String { - db.declaration(table) - .unwrap_or_else(|error| panic!("the declaration of {table} was refused: {error:?}")) -} - /// The statements for each table, the table's own first, with the tables in the order they /// were declared. fn by_table(statements: &[String]) -> Vec<(String, Vec<&str>)> { @@ -178,6 +130,11 @@ fn by_table(statements: &[String]) -> Vec<(String, Vec<&str>)> { tables } +/// The tables' names, in the order they were declared. +fn names_in_order<'a>(tables: &'a [(String, Vec<&str>)]) -> Vec<&'a str> { + tables.iter().map(|(table, _)| table.as_str()).collect() +} + /// Declares `written` in a fresh store and asserts, of every table: that it is printed back /// with what was written and nothing else; that what was printed, declared in an empty store, /// is printed the same; and that it is printed the same after the store is closed and opened, @@ -187,7 +144,7 @@ fn assert_declared_and_printed_back(test: &str, written: &[String]) -> BTreeMap< let db = support::open(&folder); declare(&db, written); let tables = by_table(written); - let mut names: Vec<&str> = tables.iter().map(|(table, _)| table.as_str()).collect(); + let mut names = names_in_order(&tables); names.sort_unstable(); assert_eq!(db.table_names(), names, "the tables of the store"); @@ -198,21 +155,10 @@ fn assert_declared_and_printed_back(test: &str, written: &[String]) -> BTreeMap< texts.insert(table.clone(), text); } - let again = support::open(&support::folder(&format!("{test}-again"))); - for (table, _) in &tables { - declare(&again, statements(&texts[table])); - } - for (table, text) in &texts { - assert_eq!( - &printed(&again, table), - text, - "{table}, declared from its printed text in an empty store, is printed differently" - ); - } + support::assert_roundtrips(test, &db, &names_in_order(&tables)); - support::close(db); - let db = support::open(&folder); - let reader = ReadSession::open(&folder).expect("open the store for reading"); + let db = support::reopen(db, &folder); + let reader = support::open_reader(&folder, None); for (table, text) in &texts { assert_eq!(&printed(&db, table), text, "{table} after close and open"); let read = reader.declaration(table).expect("a reader's declaration"); @@ -418,11 +364,7 @@ fn a_name_without_quotes_is_stored_in_lower_case_and_a_quoted_name_as_written() "CREATE TABLE \"Mixed Case\" (\n \"Id\" INTEGER PRIMARY KEY,\n \"two words\" TEXT\n);\n" ); // The printed texts declare the same two tables in an empty store. - let again = support::open(&support::folder("declared-names-again")); - for table in ["Mixed Case", "folded"] { - declare(&again, statements(&printed(&db, table))); - assert_eq!(printed(&again, table), printed(&db, table)); - } + support::assert_roundtrips("declared-names", &db, &["Mixed Case", "folded"]); // The table is found by its stored name alone. for missing in ["Folded", "FOLDED", "mixed case"] { assert!( @@ -491,8 +433,7 @@ CREATE INDEX by_stars ON notes (stars DESC, \"made at\"); CREATE INDEX by_body ON notes (body); "; assert_eq!(printed(&db, "notes"), text); - support::close(db); - let db = support::open(&folder); + let db = support::reopen(db, &folder); assert_eq!(printed(&db, "notes"), text, "after close and open"); } @@ -502,10 +443,6 @@ enum Refused { Schema(&'static [&'static str]), /// `ParseError`, with a sentence that holds each of these. Parse(&'static [&'static str]), - /// `ParseError` or `SchemaInvalid`: no document says which of the two. - ParseOrSchema, - /// `StoredProcNotSupported`. - StoredProcedure, } #[test] @@ -617,20 +554,12 @@ fn a_refused_declaration_says_why_and_declares_nothing() { // One key to a table. ( "CREATE TABLE gauges (a INTEGER PRIMARY KEY, b TEXT, PRIMARY KEY (a, b))".to_owned(), - Refused::ParseOrSchema, + Refused::Schema(&["gauges", "PRIMARY KEY"]), ), ( "CREATE TABLE gauges (a INTEGER, b TEXT, PRIMARY KEY (a, b), PRIMARY KEY (a))" .to_owned(), - Refused::ParseOrSchema, - ), - ( - "CREATE PROCEDURE tidy () AS 'DELETE FROM plans'".to_owned(), - Refused::StoredProcedure, - ), - ( - "create function one () RETURNS INTEGER AS 'SELECT 1'".to_owned(), - Refused::StoredProcedure, + Refused::Parse(&["PRIMARY KEY"]), ), ]; let declared = printed(&db, "plans"); @@ -640,8 +569,6 @@ fn a_refused_declaration_says_why_and_declares_nothing() { let as_expected = match (refused, &error) { (Refused::Schema(holds), Error::SchemaInvalid { reason }) => says(reason, holds), (Refused::Parse(holds), Error::ParseError(text)) => says(text, holds), - (Refused::ParseOrSchema, Error::ParseError(_) | Error::SchemaInvalid { .. }) => true, - (Refused::StoredProcedure, Error::StoredProcNotSupported) => true, _ => false, }; assert!(as_expected, "{sql}\nwas refused as {error:?}"); @@ -787,7 +714,7 @@ fn a_declaration_that_says_a_thing_twice_or_two_ways_is_a_parse_error_that_names "{name} (...) is not part of this library: the index sizes its own groups and \ measures how far a search scans; for the true nearest rows write USE VECTOR \ EXACT or SEARCH_MODE EXACT, and to move the size from which AUTO uses the \ - index write AUTO_INDEX_AT" + index write INDEXING_THRESHOLD" ), "{sql}" ), diff --git a/v2/contextdb/tests/docs.rs b/v2/contextdb/tests/docs.rs new file mode 100644 index 000000000..45c0d8aac --- /dev/null +++ b/v2/contextdb/tests/docs.rs @@ -0,0 +1,384 @@ +//! Runs the SQL examples of the documentation: every fenced `sql` block of `README.md` and +//! `docs/*.md` at the repository's root, each page top to bottom in a fresh store. +//! +//! A statement ends at a `;` that ends a line, and a new one begins at an unindented line that +//! starts with a statement's first word (the unindented `SELECT` that closes a `WITH` belongs to +//! it). `BEGIN` opens one transaction and `COMMIT` or `ROLLBACK` ends it; `.explain` runs the +//! statement it is given. A `CREATE TABLE` of a name the page has already declared starts that +//! table again: the earlier one is dropped first. A `$name` is bound from `bound`. +//! +//! A statement must do what its page shows in the comments that follow it: `-- Err(...)` is the +//! refusal, as `Debug` prints it; `-- Error: ...` is the refusal's sentence; `-- refused` is any +//! refusal; lines of cells two spaces apart that begin with the result's first column name are +//! the result; anything else means the statement runs. `tests/docs/expected.tsv` lists the +//! blocks that do not, with what the named statements do now (`ok`, `refused`, or the beginning +//! of the refusal's `Debug` text; `*` is every statement not named). A block that is not listed +//! and differs from its page fails, and so does a listed block that does what its page shows. + +use std::collections::HashMap; +use std::path::Path; + +use contextdb::serde_json::json; +use contextdb::{Database, QueryResult, Transaction, Uuid, Value}; + +const FIRST_WORDS: [&str; 16] = [ + "ALTER", "BEGIN", "COMMIT", "CREATE", "DECLARE", "DELETE", "DISCARD", "DROP", "INSERT", + "PURGE", "ROLLBACK", "SELECT", "SET", "SHOW", "UPDATE", "WITH", +]; + +/// The value every `$name` of the pages is bound to. A name that is not listed is an id. +fn bound(name: &str) -> Value { + match name { + "query" | "query_vector" => Value::Vector(unit_vector()), + name if name.ends_with("embedding") => Value::Vector(unit_vector()), + "data" => Value::Json(json!({"region": "us-east-1"})), + "name" | "name1" | "name2" | "session" => Value::Text(name.to_string()), + "edge_type" => Value::Text("CITES".to_string()), + "cutoff" => Value::Timestamp(0), + "n" | "m" => Value::Int64(1), + "include_drafts" => Value::Bool(true), + id => Value::Uuid(Uuid::from_u128(id.bytes().fold(0, |sum: u128, byte| { + sum.wrapping_mul(257).wrapping_add(byte.into()) + }))), + } +} + +/// The pages' vector columns that take a bound value all have 384 numbers. +fn unit_vector() -> Vec { + (0..384).map(|at| if at == 0 { 1.0 } else { 0.0 }).collect() +} + +#[derive(Default)] +struct Statement { + text: String, + /// The comments on and after the statement, up to the next one. + notes: Vec, +} + +enum Got { + Done(Option), + Refused { kind: String, sentence: String }, +} + +#[derive(Debug)] +enum Want { + Done, + Refused, + Kind(String), + Sentence(String), +} + +#[test] +fn every_sql_example_of_the_documentation_does_what_its_page_shows() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let mut pages: Vec = std::fs::read_dir(root.join("docs")) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .filter(|name| name.ends_with(".md")) + .map(|name| format!("docs/{name}")) + .collect(); + pages.push("README.md".to_string()); + pages.sort(); + let mut expected = expected(); + let (mut blocks, mut failures) = (0, Vec::new()); + for page in &pages { + let text = std::fs::read_to_string(root.join(page)).unwrap(); + let store = Path::new(env!("CARGO_TARGET_TMPDIR")).join(page.replace('/', "-")); + if store.exists() { + std::fs::remove_dir_all(&store).unwrap(); + } + let db = Database::open(&store).expect("a fresh store opens"); + let mut transaction = None; + let (mut number, mut begins, mut block) = (0, 0, None::); + for (at, line) in text.lines().enumerate() { + let Some(body) = &mut block else { + if line.trim() == "```sql" { + (begins, block) = (at + 1, Some(String::new())); + } + continue; + }; + if line.trim() != "```" { + body.push_str(line); + body.push('\n'); + continue; + } + number += 1; + blocks += 1; + let listed = expected.remove(&(page.clone(), number)); + let mut as_the_page_shows = true; + for (at, statement) in statements(body).iter().enumerate() { + let got = run(&db, &mut transaction, &statement.text); + let differs = wrong(&shown(statement), &got, &statement.notes); + as_the_page_shows &= differs.is_none(); + let now = listed.as_ref().and_then(|listed| { + let named = |which: &str| listed.iter().find(|(named, _)| named == which); + named(&(at + 1).to_string()).or_else(|| named("*")) + }); + let wrong = match now { + Some((_, now)) => wrong(&listed_as(now), &got, &[]), + None => differs, + }; + if let Some(wrong) = wrong { + failures.push(format!( + "{page}:{begins} block {number} statement {}: {wrong}\n {}", + at + 1, + statement.text.lines().next().unwrap_or_default() + )); + } + } + if listed.is_some() && as_the_page_shows { + failures.push(format!( + "{page}:{begins} block {number} is listed in expected.tsv and does what its \ + page shows: take its row out" + )); + } + (transaction, block) = (None, None); + } + } + let mut unused: Vec = expected + .keys() + .map(|(page, number)| format!("expected.tsv lists block {number} of {page}: no such block")) + .collect(); + unused.sort(); + failures.extend(unused); + assert!(blocks > 0, "the pages have no sql block"); + let report = failures.join("\n"); + assert!(report.is_empty(), "of {blocks} blocks:\n{report}"); +} + +/// The rows of `expected.tsv`: for a page and a block of it, what the named statements do now. +fn expected() -> HashMap<(String, usize), Vec<(String, String)>> { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/docs/expected.tsv"); + let text = std::fs::read_to_string(path).unwrap(); + let mut rows = HashMap::new(); + for line in text.lines().skip(1) { + let cells: Vec<&str> = line.split('\t').collect(); + assert!( + cells.len() == 5, + "expected.tsv: a row is five cells: {line}" + ); + assert!( + ["later", "changed", "page"].contains(&cells[2]), + "expected.tsv: list: {line}" + ); + let now = cells[3] + .split("; ") + .map(|entry| { + entry + .split_once('=') + .expect("expected.tsv: an entry is which=what") + }) + .map(|(which, what)| (which.to_string(), what.to_string())) + .collect(); + let block = cells[1].parse().expect("expected.tsv: a block is a number"); + assert!( + rows.insert((cells[0].to_string(), block), now).is_none(), + "listed twice: {line}" + ); + } + rows +} + +/// The code of a line and the comment after it. +fn split_comment(line: &str) -> (&str, &str) { + let mut quoted = false; + for (at, character) in line.char_indices() { + quoted ^= character == '\''; + if !quoted && line[at..].starts_with("--") { + return (&line[..at], line[at + 2..].trim()); + } + } + (line, "") +} + +fn statements(block: &str) -> Vec { + let mut block = block.to_string(); + while let Some(from) = block.find("/*") { + let Some(len) = block[from..].find("*/") else { + break; + }; + block.replace_range(from..from + len + 2, ""); + } + let (mut done, mut open, mut waits_for_select) = (Vec::new(), None::, false); + for line in block.lines() { + let (code, note) = split_comment(line); + if code.trim().is_empty() { + if let Some(statement) = open + .as_mut() + .or(done.last_mut()) + .filter(|_| !note.is_empty()) + { + statement.notes.push(note.to_string()); + } + continue; + } + let first = code + .split(|c: char| !c.is_ascii_alphabetic()) + .next() + .unwrap_or_default(); + let first = first.to_ascii_uppercase(); + let command = code.starts_with('.'); + let closes_with = first == "SELECT" && waits_for_select; + if command || (FIRST_WORDS.contains(&first.as_str()) && !closes_with) { + done.extend(open.take()); + } + if open.is_none() || closes_with { + waits_for_select = open.is_none() && first == "WITH"; + } + let statement = open.get_or_insert_with(Statement::default); + let code = code.trim_end(); + statement.text.push_str(code.trim_end_matches(';')); + statement.text.push('\n'); + if !note.is_empty() { + statement.notes.push(note.to_string()); + } + if command || code.ends_with(';') { + done.extend(open.take()); + } + } + done.extend(open); + done +} + +fn run<'db>(db: &'db Database, open: &mut Option>, text: &str) -> Got { + let text = text.trim().strip_prefix(".explain").unwrap_or(text).trim(); + let upper = text.to_ascii_uppercase(); + let result = match (upper.as_str(), open.take()) { + ("BEGIN", None) => db.transaction().map(|transaction| { + *open = Some(transaction); + None + }), + ("COMMIT", Some(transaction)) => transaction.commit().map(|()| None), + ("ROLLBACK", Some(transaction)) => { + transaction.rollback(); + Ok(None) + } + (_, transaction) => { + *open = transaction; + let again = upper.strip_prefix("CREATE TABLE ").map(|rest| { + let name: String = rest + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_') + .collect(); + name.to_ascii_lowercase() + }); + let params: HashMap = text + .split('$') + .skip(1) + .map(|rest| { + rest.chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_') + .collect() + }) + .map(|name: String| (name.clone(), bound(&name))) + .collect(); + let dropped = match again.filter(|name| db.table_names().contains(name)) { + Some(name) => drop_table(db, &name), + None => Ok(()), + }; + dropped + .and_then(|()| match open { + Some(transaction) => transaction.execute(text, ¶ms), + None => db.execute(text, ¶ms), + }) + .map(Some) + } + }; + match result { + Ok(result) => Got::Done(result), + Err(error) => Got::Refused { + kind: format!("{error:?}"), + sentence: error.to_string(), + }, + } +} + +/// What the page shows a statement doing. +fn shown(statement: &Statement) -> Want { + for note in &statement.notes { + if let Some(kind) = note + .strip_prefix("Err(") + .and_then(|rest| rest.strip_suffix(')')) + { + return Want::Kind(kind.to_string()); + } + if let Some(sentence) = note.strip_prefix("Error: ") { + return Want::Sentence(sentence.to_string()); + } + if note.starts_with("refused") { + return Want::Refused; + } + } + Want::Done +} + +fn listed_as(now: &str) -> Want { + match now { + "ok" => Want::Done, + "refused" => Want::Refused, + kind => Want::Kind(kind.to_string()), + } +} + +/// How what a statement did differs from what was wanted, if it does. +fn wrong(want: &Want, got: &Got, notes: &[String]) -> Option { + match (want, got) { + (Want::Done, Got::Done(result)) => { + result.as_ref().and_then(|result| wrong_rows(result, notes)) + } + (Want::Refused, Got::Refused { .. }) => None, + (Want::Kind(kind), Got::Refused { kind: got, .. }) if got.starts_with(kind) => None, + (Want::Sentence(sentence), Got::Refused { sentence: got, .. }) if got == sentence => None, + (want, Got::Done(_)) => Some(format!("wanted {want:?}, and it ran")), + (want, Got::Refused { kind, sentence }) => { + Some(format!("wanted {want:?}, got {kind}: {sentence}")) + } + } +} + +/// How a result differs from the one the comments after its statement show, if they show one. +fn wrong_rows(result: &QueryResult, notes: &[String]) -> Option { + let cells = |line: &String| -> Vec { + line.split(" ") + .map(str::trim) + .filter(|cell| !cell.is_empty()) + .map(String::from) + .collect() + }; + let at = notes.iter().position(|note| { + let cells = cells(note); + cells.len() > 1 && cells.first() == result.columns().first() + })?; + let shown: Vec> = notes[at..].iter().map(cells).collect(); + let mut got = vec![result.columns().to_vec()]; + got.extend(result.rows().iter().map(|row| { + row.iter() + .map(|value| match value { + Value::Null => "NULL".to_string(), + Value::Text(text) => text.clone(), + Value::Int64(number) => number.to_string(), + Value::Float64(number) => format!("{number:?}"), + Value::Uuid(id) => id.to_string(), + other => format!("{other:?}"), + }) + .collect() + })); + (shown != got).then(|| format!("the page shows the rows {shown:?}, got {got:?}")) +} + +/// Drops a table the page declares again, and first every table that refers to it: a page's +/// later example may declare a table an earlier one of the page's tables refers to. +fn drop_table(db: &Database, name: &str) -> contextdb::Result<()> { + let reference = format!("references {name}("); + for other in db.table_names() { + let refers = other != name + && db + .declaration(&other) + .is_ok_and(|text| text.to_ascii_lowercase().contains(&reference)); + if refers { + drop_table(db, &other)?; + } + } + db.execute(&format!("DROP TABLE {name}"), &HashMap::new()) + .map(drop) +} diff --git a/v2/contextdb/tests/docs/expected.tsv b/v2/contextdb/tests/docs/expected.tsv new file mode 100644 index 000000000..a9d2f31b9 --- /dev/null +++ b/v2/contextdb/tests/docs/expected.tsv @@ -0,0 +1,63 @@ +page block list now why +README.md 1 changed 5=refused ROW_VECTOR is not read: a scalar subquery supplies another row's vector +docs/cli.md 1 page 3=TableNotFound; 4=TableNotFound the page declares no such table before this block +docs/getting-started.md 1 page 4=InvalidStateTransition the page prints a shorter sentence for this refusal than the engine does +docs/getting-started.md 2 page 4=ImmutableColumn the page prints another sentence for this refusal than the engine does +docs/sync-two-machines.md 1 later 3=refused a later version reads sync, tenant policy and delivery statements +docs/sync-two-machines.md 2 later 1=refused a later version reads sync, tenant policy and delivery statements +docs/sync-two-machines.md 3 later 2=refused a later version reads sync, tenant policy and delivery statements +docs/sync-two-machines.md 4 later 1=refused a later version reads sync, tenant policy and delivery statements +docs/why-contextdb.md 2 page *=refused a syntax outline or a clause on its own, not a statement +docs/why-contextdb.md 3 page *=refused a syntax outline or a clause on its own, not a statement +docs/why-contextdb.md 4 page *=refused a syntax outline or a clause on its own, not a statement +docs/why-contextdb.md 5 page *=refused a syntax outline or a clause on its own, not a statement +docs/why-contextdb.md 6 page *=TableNotFound the page declares no such table before this block +docs/query-language.md 4 page *=refused a syntax outline or a clause on its own, not a statement +docs/query-language.md 5 page *=TableNotFound the page declares no such table before this block +docs/query-language.md 6 later *=refused a later version reads triggers and the disk, maintenance, cache and compaction settings +docs/query-language.md 7 page *=TableNotFound the page declares no such table before this block +docs/query-language.md 9 page *=TableNotFound the page declares no such table before this block +docs/query-language.md 10 page *=refused a syntax outline or a clause on its own, not a statement +docs/query-language.md 12 page 1=ColumnNotFound the page's items table has no tag column +docs/query-language.md 13 page 1=ColumnNotFound the page's items table has no score column +docs/query-language.md 14 changed 1=ColumnNotFound { table: "x", column: "name" } a qualifier that names no table of the statement is reported as written +docs/query-language.md 15 page 2=TableNotFound the page declares no such table before this block +docs/query-language.md 16 page 1=ColumnNotFound; 2=ColumnNotFound the page's items table has no active column +docs/query-language.md 17 page *=TableNotFound the page declares no such table before this block +docs/query-language.md 18 changed 1=refused ORDER BY takes any expression, so the kind shown is gone; the page declares no readings table and UPPER is no function of this version +docs/query-language.md 20 page *=TableNotFound the page declares no such table before this block +docs/query-language.md 21 page 3=refused the block shows two endings of one transaction, and the second has none to end +docs/query-language.md 22 later 1=refused; 5=refused; 6=refused; 7=refused; 8=refused; 9=refused; 10=refused a later version reads triggers and the disk, maintenance, cache and compaction settings; a later version reads sync, tenant policy and delivery statements +docs/query-language.md 23 later *=refused a later version reads triggers and the disk, maintenance, cache and compaction settings +docs/query-language.md 24 later *=refused a later version reads triggers and the disk, maintenance, cache and compaction settings +docs/query-language.md 25 later 1=refused a later version reads the vector index options and SHOW VECTOR_INDEXES / SHOW VECTOR_PARTITIONS +docs/query-language.md 26 later 1=refused a later version reads the vector index options and SHOW VECTOR_INDEXES / SHOW VECTOR_PARTITIONS +docs/query-language.md 27 page 2=TableNotFound the page declares no such table before this block +docs/query-language.md 28 page *=refused a syntax outline or a clause on its own, not a statement +docs/query-language.md 31 page 1=ok the page shows rows it never inserts +docs/query-language.md 32 page 1=ok the page shows rows it never inserts +docs/query-language.md 41 page 2=UniqueViolation the page prints an Err without the key field the engine reports +docs/query-language.md 56 page 1=SchemaInvalid the page says in its prose, not in the block, that this is refused +docs/query-language.md 62 page *=refused a syntax outline or a clause on its own, not a statement +docs/query-language.md 64 page *=refused a syntax outline or a clause on its own, not a statement +docs/query-language.md 65 page *=refused a syntax outline or a clause on its own, not a statement +docs/query-language.md 66 page *=refused a syntax outline or a clause on its own, not a statement +docs/query-language.md 67 page *=refused a syntax outline or a clause on its own, not a statement +docs/query-language.md 68 changed 2=ok NOW() is a value an INSERT may write +docs/query-language.md 70 page *=TableNotFound the page declares no such table before this block +docs/query-language.md 71 page *=refused a syntax outline or a clause on its own, not a statement +docs/query-language.md 72 page *=refused a syntax outline or a clause on its own, not a statement +docs/query-language.md 73 page *=refused a syntax outline or a clause on its own, not a statement +docs/query-language.md 78 changed 1=refused ROW_VECTOR is not read: a scalar subquery supplies another row's vector +docs/query-language.md 80 later 1=refused a later version reads the vector index options and SHOW VECTOR_INDEXES / SHOW VECTOR_PARTITIONS +docs/query-language.md 81 later *=refused a later version reads the vector index options and SHOW VECTOR_INDEXES / SHOW VECTOR_PARTITIONS +docs/query-language.md 82 page 1=TableNotFound the page declares no such table before this block +docs/query-language.md 84 page 1=ColumnNotFound the page's latest documents table has no bucket column +docs/query-language.md 85 page 1=IndexNotFound the index was never made: the page's latest documents table has no bucket column +docs/query-language.md 86 page *=TableNotFound the page declares no such table before this block +docs/query-language.md 87 later *=refused a later version reads sync, tenant policy and delivery statements +docs/query-language.md 88 later *=refused a later version reads sync, tenant policy and delivery statements +docs/usage-scenarios.md 6 page 2=ok the page inserts no row for the refused transition to meet +docs/usage-scenarios.md 20 page 3=UniqueViolation binds an edge id that an earlier block of the page already inserted +docs/usage-scenarios.md 23 page 2=UniqueViolation binds an edge id that an earlier block of the page already inserted +docs/usage-scenarios.md 30 page 2=UniqueViolation binds an edge id that an earlier block of the page already inserted diff --git a/v2/contextdb/tests/explain.rs b/v2/contextdb/tests/explain.rs new file mode 100644 index 000000000..a21b62465 --- /dev/null +++ b/v2/contextdb/tests/explain.rs @@ -0,0 +1,256 @@ +//! `Database::explain`: the path a statement would take, said in the documented words, without +//! running it. + +mod support; + +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; + +use contextdb::{ContextId, Database, Uuid, params}; + +/// A store with the usual table `t` and its index on `tag`, forty rows. +fn store(name: &str) -> (PathBuf, Database) { + let folder = support::folder(name); + let db = support::open(&folder); + support::declare(&db); + support::insert(&db, 1..=40); + (folder, db) +} + +/// What `explain` says of a statement. It must answer. +fn explained(db: &Database, sql: &str) -> String { + db.explain(sql) + .unwrap_or_else(|error| panic!("{sql}\nwas not explained: {error:?}")) +} + +/// Fails unless the explanation holds each of these, naming the statement and the whole text. +fn assert_says(db: &Database, sql: &str, words: &[&str]) { + let text = explained(db, sql); + for word in words { + assert!(text.contains(word), "{sql}\ndoes not say `{word}`:\n{text}"); + } +} + +/// Every file under a folder with its bytes, in name order. +fn bytes_of(folder: &Path) -> Vec<(PathBuf, Vec)> { + let mut files = Vec::new(); + for name in support::listing(folder) { + let path = folder.join(name); + if path.is_dir() { + files.extend(bytes_of(&path)); + } else { + let bytes = std::fs::read(&path).expect("read a file of the store"); + files.push((path, bytes)); + } + } + files +} + +#[test] +fn a_search_is_explained_with_its_mode_and_partition_key() { + let (_, db) = store("explain-search"); + support::declare_docs(&db, 3, "PARTITION_KEY (ctx) SEARCH_MODE EXACT"); + support::insert_docs(&db, 1..=8, 3, |n| format!("c{}", n % 2)); + assert_says( + &db, + "SELECT id FROM docs WHERE ctx = 'c1' ORDER BY v <=> [1.0, 0.0, 0.0] LIMIT 3", + &["EXACT", "exact", "ctx"], + ); + // A filter on a column no index leads with is said to take no path, and the statement that + // would give it one; once the index is there the search says the path it takes. + let by_tag = "SELECT id FROM docs WHERE tag = 3 ORDER BY v <=> [1.0, 0.0, 0.0] LIMIT 3"; + assert_says( + &db, + by_tag, + &[ + "filter_path: none", + "recovery: CREATE INDEX docs_tag_idx ON docs (tag)", + ], + ); + support::run(&db, "CREATE INDEX docs_tag_idx ON docs (tag)"); + assert_says( + &db, + by_tag, + &[ + "filter_path: IndexScan { index: docs_tag_idx }", + "small_set: yes", + ], + ); + // A vector read from a subquery leaves the filter path the search's own; the inner one is told once. + let q = "SELECT id FROM docs WHERE tag = 3 ORDER BY v <=> (SELECT v FROM docs WHERE id = 1) LIMIT 3"; + let text = explained(&db, q); + let path = text.lines().find(|line| line.contains("filter_path:")); + assert_eq!( + path.map(str::trim), + Some("filter_path: IndexScan { index: docs_tag_idx }"), + "{text}" + ); + assert_eq!(text.matches("__pk_id").count(), 1, "{text}"); + // A filter that reaches more rows than the statement asks for is not a small set. + assert_says( + &db, + "SELECT id FROM docs WHERE tag >= 0 ORDER BY v <=> [1.0, 0.0, 0.0] LIMIT 1", + &["small_set: no"], + ); + // The rows asked for are the limit, the offset and a second sort key's lookahead: tags 5 to + // 8 are four rows, as many as LIMIT 2 OFFSET 2 asks for. + assert_says( + &db, + "SELECT id FROM docs WHERE tag >= 5 ORDER BY v <=> [1.0, 0.0, 0.0] LIMIT 2 OFFSET 2", + &["small_set: yes"], + ); + // Refused as running is; an unbound $x is a PlanError, open only as a search's vector or key. + let mut told = Vec::new(); + for (head, kind) in [ + ("SELECT nope FROM docs @ LIMIT 3", "ColumnNotFound"), + ("SELECT id FROM docs WHERE 1 = 'x' @ LIMIT 3", "PlanError"), + ( + "SELECT id FROM docs @ USE RANK nothing LIMIT 3", + "RankPolicy", + ), + ("SELECT id FROM docs WHERE tag = $x @ LIMIT 3", "PlanError"), + ("SELECT id, $x FROM docs @ LIMIT 3", "PlanError"), + ( + "SELECT id FROM docs WHERE ctx LIKE $x @ LIMIT 3", + "PlanError", + ), + ("SELECT id FROM docs WHERE id = $x", "PlanError"), + ("DELETE FROM docs WHERE id = $x", "PlanError"), + ] { + let sql = head.replace('@', "ORDER BY v <=> $q"); + let error = format!("{:?}", db.explain(&sql).err()); + if !error.contains(kind) { + told.push(format!("{sql}\ngave {error}")); + } + } + let open = "SELECT id FROM docs WHERE ctx = $c ORDER BY v <=> $q LIMIT 3"; + explained(&db, open); + // A bound value of the wrong type or width is refused as running refuses it. + let sql = "SELECT id FROM docs WHERE tag = $x ORDER BY v <=> $q LIMIT 3"; + for bound in [ + params! { "x" => "text", "q" => support::vector(1, 3) }, + params! { "x" => 1, "q" => support::vector(1, 2) }, + ] { + let ran = format!("{:?}", db.execute(sql, &bound).err()); + let said = format!("{:?}", db.execute(&format!("EXPLAIN {sql}"), &bound).err()); + if said != ran { + told.push(format!("ran: {ran}\nexplained: {said}")); + } + } + assert!(told.is_empty(), "{told:#?}"); +} + +#[test] +fn explaining_a_statement_changes_nothing_in_the_store() { + let (folder, db) = store("explain-changes-nothing"); + let before = bytes_of(&folder); + for sql in [ + "SELECT name FROM t WHERE id = 7", + "DELETE FROM t WHERE id = 7", + "UPDATE t SET name = 'gone' WHERE tag = 3", + "INSERT INTO t (id, name, tag) VALUES (41, 'new', 1)", + ] { + explained(&db, sql); + // No file is written, made or removed by the asking. + assert!( + bytes_of(&folder) == before, + "{sql}\nchanged a file of the store" + ); + } + // Nothing the statements name was done. + support::assert_rows_are(&db, 1..=40); +} + +#[test] +fn a_narrowed_handle_is_told_no_row_or_count_of_what_it_may_not_see() { + let (_, db) = store("explain-narrowed"); + support::run( + &db, + "CREATE TABLE passages (id INTEGER PRIMARY KEY, context_id UUID NOT NULL CONTEXT_ID, \ + v VECTOR(3) PARTITION_KEY (context_id) SEARCH_MODE EXACT, UNIQUE (context_id, id)) \ + MAINTAIN COUNT (context_id)", + ); + // Three passages in the context the handle is given and 137 in one it is not: 140 in all. + let (own, hidden) = (Uuid::from_u128(1), Uuid::from_u128(2)); + let tx = db.transaction().expect("begin"); + for n in 1..=140_i64 { + tx.execute( + "INSERT INTO passages (id, context_id, v) VALUES ($id, $ctx, $v)", + ¶ms! { + "id" => 1000 + n, "ctx" => if n <= 3 { own } else { hidden }, + "v" => support::vector(n, 3), + }, + ) + .expect("insert a passage"); + } + tx.commit().expect("commit"); + let narrowed = db.scoped_with_contexts(BTreeSet::from([ContextId::new(own)])); + let count = support::int(&narrowed, "SELECT COUNT(*) AS n FROM passages"); + assert_eq!(count, 3, "the rows of its own Context"); + // Explaining a search through a WITH answers like any other statement. + let with = "WITH x AS (SELECT id, v FROM passages) SELECT id FROM x ORDER BY v <=> [1.0, 0.0, 0.0] LIMIT 1"; + explained(&db, with); + // It is told no key, route or refusal: each would show the state of rows it may not see. + let own_search = "SELECT id FROM passages ORDER BY v <=> [1.0, 0.0, 0.0] LIMIT 2"; + let bare = |reader: &Database, sql: &str| { + let text = explained(reader, sql); + for line in ["key:", "route:", "refusal:"] { + assert!(!text.contains(line), "told `{line}`:\n{text}"); + } + text + }; + bare(&narrowed, own_search); + bare(&db.scoped_with_contexts(BTreeSet::new()), own_search); + for sql in [ + own_search, + "SELECT COUNT(*) AS n FROM passages", + "SELECT context_id, COUNT(*) AS n FROM passages GROUP BY context_id", + ] { + let text = explained(&narrowed, sql); + for secret in [hidden.to_string(), "137".to_owned(), "140".to_owned()] { + assert!(!text.contains(&secret), "{sql}\nsays `{secret}`:\n{text}"); + } + } + // Writes to rows it may not see change neither what it is told nor what INDEXED search gives. + for (t, key, n) in [("m", "", 1), ("d", "PARTITION_KEY (c)", 4)] { + let make = format!( + "CREATE TABLE {t} (id INTEGER PRIMARY KEY, c UUID NOT NULL CONTEXT_ID, v VECTOR(3) {key} INDEXING_THRESHOLD {n})" + ); + support::run(&db, &make); + let put = |ids: std::ops::Range, who: Uuid, v: &str| { + for n in ids { + support::run(&db, &format!("INSERT INTO {t} VALUES ({n}, '{who}', {v})")); + } + }; + let sql = + format!("SELECT id FROM {t} ORDER BY v <=> [1.0, 0.0, 0.0] USE VECTOR INDEXED LIMIT 2"); + let ask = || (bare(&narrowed, &sql), support::rows(&narrowed, &sql)); + put(1..4, own, "[1.0, 0.0, 0.0]"); + support::seal_all(&db); + let before = ask(); + put(4..6, hidden, "[1.0, 0.0, 0.0]"); + assert_eq!(ask(), before, "{t}: unindexed hidden rows"); + support::seal_all(&db); + assert_eq!(ask(), before, "{t}: indexed hidden rows"); + put(6..8, own, "[0.0, 1.0, 0.0]"); + assert_eq!(ask(), before, "{t}: own rows further away"); + } +} + +#[test] +fn explaining_a_write_also_says_the_path_of_the_select_inside_it() { + let (_, db) = store("explain-write-select"); + support::run( + &db, + "CREATE TABLE owners (id INTEGER PRIMARY KEY, t_id INTEGER NOT NULL)", + ); + support::run(&db, "CREATE INDEX owners_t ON owners (t_id)"); + let inner = "(SELECT t_id FROM owners WHERE t_id = 3)"; + for write in [ + format!("DELETE FROM t WHERE id = 7 AND tag IN {inner}"), + format!("UPDATE t SET name = 'x' WHERE id = 7 AND tag IN {inner}"), + ] { + // The write's own table by its key, and the inner table through its index. + assert_says(&db, &write, &["index: __pk_id }", "index: owners_t }"]); + } +} diff --git a/v2/contextdb/tests/graph.rs b/v2/contextdb/tests/graph.rs new file mode 100644 index 000000000..0033322b9 --- /dev/null +++ b/v2/contextdb/tests/graph.rs @@ -0,0 +1,601 @@ +//! Graph patterns through the library: the work a pattern does and the memory it may take, the +//! rule that keeps a DAG's edges free of cycles, and what a narrowed handle is shown. A node is +//! hidden from a handle when a table with a Context column, labels or an access-control column +//! has a row whose `id` is the node's id and that row is hidden from the handle; a node no row +//! carries is hidden from nobody. Whatever is hidden is taken out before the pattern is matched. + +mod support; + +use contextdb::{Database, Error, Principal, Uuid, Value, params}; + +use support::{Run, context, in_contexts, label_set}; + +/// An edge table whose rows are each under a Context. +const EDGES: &str = "CREATE TABLE edges (id INTEGER PRIMARY KEY, source_id UUID NOT NULL, \ + target_id UUID NOT NULL, edge_type TEXT NOT NULL, context_id UUID CONTEXT_ID)"; + +/// A table of nodes, each under a Context. +const THINGS: &str = "CREATE TABLE things (id UUID PRIMARY KEY, context_id UUID CONTEXT_ID)"; + +const GRANTS: &str = "CREATE TABLE acl_grants (id UUID PRIMARY KEY, principal_kind TEXT, \ + principal_id TEXT, acl_id UUID)"; +const FILES: &str = + "CREATE TABLE files (id UUID PRIMARY KEY, acl_id UUID ACL REFERENCES acl_grants(acl_id))"; + +fn node(n: u128) -> Uuid { + Uuid::from_u128(n) +} + +/// A fresh store with these tables. +fn store(name: &str, tables: &[&str]) -> Database { + let db = support::open(&support::folder(name)); + for table in tables { + support::run(&db, table); + } + db +} + +/// Writes edge `id`, of type `E`, from one node to another, under Context `of`. +fn edge(on: &impl Run, id: i64, from: u128, to: u128, of: u128) { + typed_edge(on, id, from, to, "E", of); +} + +fn typed_edge(on: &impl Run, id: i64, from: u128, to: u128, edge_type: &str, of: u128) { + let values = params! { + "id" => id, "from" => node(from), "to" => node(to), "type" => edge_type, + "context" => context(of), + }; + let sql = "INSERT INTO edges (id, source_id, target_id, edge_type, context_id) \ + VALUES ($id, $from, $to, $type, $context)"; + if let Err(error) = on.run(sql, &values) { + panic!("edge {id} from {from} to {to} was refused: {error:?}"); + } +} + +/// A pattern over `edges` that names its far node `b`, with the id and the depth of each node +/// reached, nearest first. +fn pattern(pattern: &str, filter: &str) -> String { + format!( + "SELECT b_id, depth FROM GRAPH_TABLE(edges MATCH {pattern} {filter} \ + COLUMNS (b.id AS b_id, depth AS depth)) ORDER BY depth, b_id" + ) +} + +/// The same pattern, started at one node. +fn from(start: u128, pattern_text: &str) -> String { + pattern(pattern_text, &format!("WHERE a.id = '{}'", node(start))) +} + +/// The rows a pattern must return: each node's number and its depth. +fn reached(wanted: &[(u128, i64)]) -> Vec> { + wanted + .iter() + .map(|(n, depth)| vec![Value::Uuid(node(*n)), Value::Int64(*depth)]) + .collect() +} + +/// A store whose nodes 1, 3, 4, 5 and 7 are under Context 1 and whose node 2 is under Context +/// 2; node 6 has no row. Every edge row is under Context 1 except the edge from 1 to 7. +/// +/// ```text +/// 1 -> 2 -> 3 1 -> 6 +/// 2 -> 5 1 -> 7 (the edge row is under Context 2) +/// 1 -> 4 -> 5 4 -> 1 +/// 1 -> 4 again, of type F +/// ``` +fn partly_hidden(name: &str) -> Database { + let db = store(name, &[EDGES, THINGS]); + for (n, of) in [(1, 1), (2, 2), (3, 1), (4, 1), (5, 1), (7, 1)] { + db.execute( + "INSERT INTO things (id, context_id) VALUES ($id, $context)", + ¶ms! { "id" => node(n), "context" => context(of) }, + ) + .expect("insert a node"); + } + let edges = [ + (1, 1, 2, 1), + (2, 2, 3, 1), + (3, 1, 4, 1), + (4, 4, 5, 1), + (5, 2, 5, 1), + (6, 1, 6, 1), + (7, 1, 7, 2), + (8, 4, 1, 1), + ]; + for (id, from, to, of) in edges { + edge(&db, id, from, to, of); + } + typed_edge(&db, 9, 1, 4, "F", 1); + db +} + +// ---- the work and the memory of a pattern ---- + +#[test] +fn a_pinned_single_hop_reads_the_nodes_degree_in_rows() { + let db = store("graph-pinned-degree", &[EDGES]); + let tx = db.transaction().expect("begin"); + for n in 0..200 { + edge(&tx, n, 1_000 + n as u128, 2_000 + n as u128, 1); + } + // Node 1 has three edges out and two in. + for (id, from, to) in [ + (500, 1, 2), + (501, 1, 3), + (502, 1, 4), + (503, 5, 1), + (504, 6, 1), + ] { + edge(&tx, id, from, to, 1); + } + tx.commit().expect("commit the edges"); + + let out = support::run(&db, &from(1, "(a)-[:E]->(b)")); + assert_eq!(out.rows(), reached(&[(2, 1), (3, 1), (4, 1)])); + assert_eq!(out.rows_examined(), 3, "rows read for three edges out"); + let into = support::run(&db, &from(1, "(a)<-[:E]-(b)")); + assert_eq!(into.rows(), reached(&[(5, 1), (6, 1)])); + assert_eq!(into.rows_examined(), 2, "rows read for two edges in"); +} + +#[test] +fn a_walk_whose_visited_set_is_over_the_limit_is_refused_and_one_that_fits_is_answered() { + // Node 1 has 8,000 edges out, and one of the nodes they reach has an edge to node 2. Node 3 + // has three edges out, and one of the nodes they reach has an edge to node 4. A walk of + // exactly two steps returns one row from either start, and remembers every node it met. + const WIDE: u128 = 8_000; + let db = store("graph-walk-memory", &[EDGES]); + let tx = db.transaction().expect("begin"); + for n in 0..WIDE { + edge(&tx, n as i64, 1, 10_000 + n, 1); + } + edge(&tx, 20_000, 10_000, 2, 1); + for n in 0..3 { + edge(&tx, 30_000 + n as i64, 3, 40_000 + n, 1); + } + edge(&tx, 50_000, 40_000, 4, 1); + tx.commit().expect("commit the edges"); + + // 64 KiB of room: the 8,001 nodes of the wide walk take more than 300 KiB to remember. + let limit = db.memory_used() + (64 << 10); + db.set_memory_limit(Some(limit)).expect("set the limit"); + let wide = from(1, "(a)-[:E]->{2,2}(b)"); + match db.execute(&wide, ¶ms! {}) { + Err(Error::MemoryBudgetExceeded { .. }) => {} + other => panic!("a walk over 8,001 nodes in 64 KiB got {other:?}"), + } + assert_eq!( + support::rows(&db, &from(3, "(a)-[:E]->{2,2}(b)")), + reached(&[(4, 2)]), + "a walk over five nodes under the same limit" + ); + db.set_memory_limit(None).expect("lift the limit"); + assert_eq!(support::rows(&db, &wide), reached(&[(2, 2)])); +} + +#[test] +fn a_transaction_walks_the_edges_it_staged_and_not_the_ones_it_deleted() { + let db = store("graph-staged-edges", &[EDGES]); + let tx = db.transaction().expect("begin"); + edge(&tx, 1, 1, 2, 1); + edge(&tx, 2, 2, 3, 1); + let hop = from(1, "(a)-[:E]->(b)"); + let walk = from(1, "(a)-[:E]->{1,2}(b)"); + let every = pattern("(a)-[:E]->(b)", ""); + assert_eq!(support::rows(&tx, &hop), reached(&[(2, 1)])); + assert_eq!(support::rows(&tx, &walk), reached(&[(2, 1), (3, 2)])); + assert_eq!(support::rows(&tx, &every), reached(&[(2, 1), (3, 1)])); + assert_eq!( + support::rows(&db, &walk), + reached(&[]), + "outside the transaction" + ); + + support::run(&tx, "DELETE FROM edges WHERE id = 2"); + assert_eq!(support::rows(&tx, &walk), reached(&[(2, 1)])); + assert_eq!(support::rows(&tx, &every), reached(&[(2, 1)])); + support::run(&tx, "DELETE FROM edges WHERE id = 1"); + assert_eq!(support::rows(&tx, &hop), reached(&[])); +} + +// ---- a DAG's edges ---- + +fn dag(name: &str) -> Database { + let table = format!("{EDGES} DAG('E')"); + store(name, &[table.as_str()]) +} + +fn assert_cycle(result: contextdb::Result, what: &str) { + match result { + Err(Error::CycleDetected { table, edge_type }) => { + assert_eq!( + (table.as_str(), edge_type.as_str()), + ("edges", "E"), + "{what}" + ); + } + other => panic!("{what} got {other:?}"), + } +} + +/// An INSERT of one edge of type `E`, written out. +fn insert_edge(id: i64, from: u128, to: u128) -> String { + format!( + "INSERT INTO edges (id, source_id, target_id, edge_type, context_id) \ + VALUES ({id}, '{}', '{}', 'E', '{}')", + node(from), + node(to), + context(1) + ) +} + +#[test] +fn an_edge_that_closes_a_cycle_with_another_commits_edge_is_refused_at_commit() { + let db = dag("graph-dag-commit"); + let first = db.transaction().expect("begin"); + let second = db.transaction().expect("begin"); + // Neither transaction sees the other's edge, so each statement is taken. + support::run(&first, &insert_edge(1, 1, 2)); + support::run(&second, &insert_edge(2, 2, 1)); + first + .commit() + .expect("the first of two transactions commits"); + assert_cycle(second.commit(), "the commit of the other half of a cycle"); + assert_eq!( + support::rows(&db, "SELECT id FROM edges"), + [[Value::Int64(1)]] + ); +} + +// ---- what a narrowed handle is shown ---- + +#[test] +fn a_handle_allowed_to_see_everything_gets_the_rows_an_unconstrained_handle_gets() { + let db = partly_hidden("graph-same-rows"); + let all = in_contexts(&db, &[1, 2]); + let asked = [ + pattern("(a)-[]->(b)", ""), + pattern("(a)-[:E]-(b)", ""), + from(1, "(a)-[]->(b)"), + from(1, "(a)-[:E]->{1,3}(b)"), + from(5, "(a)<-[:E]-(b)"), + pattern("(a)-[:E]->{1,2}(b)", ""), + ]; + for sql in &asked { + let wanted = support::rows(&db, sql); + assert!(!wanted.is_empty(), "{sql}\nreturns no row to compare"); + assert_eq!(support::rows(&all, sql), wanted, "{sql}"); + } + // What both are held to: one row for each edge, and the start again when a cycle returns. + assert_eq!( + support::rows(&all, &from(1, "(a)-[]->(b)")), + reached(&[(2, 1), (4, 1), (4, 1), (6, 1), (7, 1)]) + ); + assert_eq!( + support::rows(&all, &from(1, "(a)-[:E]->{1,3}(b)")), + reached(&[(2, 1), (4, 1), (6, 1), (7, 1), (1, 2), (3, 2), (5, 2)]) + ); +} + +#[test] +fn a_handle_narrowed_to_a_context_is_shown_the_graph_without_what_it_may_not_see() { + // One store, four rules of what a narrowed handle may follow, each over the same graph. + let db = partly_hidden("graph-hidden-nodes"); + let narrowed = in_contexts(&db, &[1]); + a_hidden_edge_row_is_not_followed(&db, &narrowed); + an_edge_whose_row_is_visible_and_whose_target_is_hidden_is_not_reported(&narrowed); + a_walk_does_not_pass_through_a_hidden_node_to_a_visible_one_behind_it(&db, &narrowed); + a_hidden_node_reached_on_the_way_is_left_out_with_no_error(&db, &narrowed); +} + +/// Over [`partly_hidden`], read through a handle narrowed to Context 1. +fn a_hidden_edge_row_is_not_followed(db: &Database, narrowed: &Database) { + // Node 7 is the handle's to see, and the only edge to it is not. + assert_eq!( + support::rows( + narrowed, + &format!("SELECT id FROM things WHERE id = '{}'", node(7)) + ), + [[Value::Uuid(node(7))]] + ); + let seven = [Value::Uuid(node(7)), Value::Int64(1)]; + for sql in [from(1, "(a)-[:E]->(b)"), from(1, "(a)-[:E]->{1,3}(b)")] { + assert!(support::rows(db, &sql).contains(&seven.to_vec()), "{sql}"); + assert!( + !support::rows(narrowed, &sql).contains(&seven.to_vec()), + "{sql}" + ); + } + assert_eq!( + support::rows(narrowed, &from(7, "(a)<-[:E]-(b)")), + reached(&[]), + "against the hidden edge" + ); +} + +/// Over [`partly_hidden`], read through a handle narrowed to Context 1. +fn an_edge_whose_row_is_visible_and_whose_target_is_hidden_is_not_reported(narrowed: &Database) { + // The handle reads the row of the edge from node 1 to node 2, and may not see node 2. + assert_eq!( + support::int(narrowed, "SELECT id FROM edges WHERE id = 1"), + 1 + ); + assert_eq!( + support::rows(narrowed, &from(1, "(a)-[:E]->(b)")), + reached(&[(4, 1), (6, 1)]) + ); + // Nor is an edge reported whose hidden node is the one it leaves. + assert_eq!( + support::rows(narrowed, &from(3, "(a)<-[:E]-(b)")), + reached(&[]) + ); + assert_eq!( + support::rows(narrowed, &pattern("(a)-[:E]->(b)", "")), + reached(&[(1, 1), (4, 1), (5, 1), (6, 1)]) + ); +} + +/// Over [`partly_hidden`], read through a handle narrowed to Context 1. +fn a_walk_does_not_pass_through_a_hidden_node_to_a_visible_one_behind_it( + db: &Database, + narrowed: &Database, +) { + let walk = from(1, "(a)-[:E]->{1,3}(b)"); + // Node 3 is reached only through node 2; node 5 through node 2 and through node 4. + let (three, five) = (reached(&[(3, 2)]), reached(&[(5, 2)])); + let unconstrained = support::rows(db, &walk); + assert!(unconstrained.contains(&three[0]) && unconstrained.contains(&five[0])); + assert_eq!( + support::rows(narrowed, &walk), + reached(&[(4, 1), (6, 1), (1, 2), (5, 2)]) + ); + // Written out step by step it is the same: no row goes through node 2. + let steps = format!( + "SELECT b_id, c_id FROM GRAPH_TABLE(edges MATCH (a)-[:E]->(b)-[:E]->(c) \ + WHERE a.id = '{}' COLUMNS (b.id AS b_id, c.id AS c_id)) ORDER BY c_id", + node(1) + ); + assert_eq!( + support::rows(narrowed, &steps), + [ + [Value::Uuid(node(4)), Value::Uuid(node(1))], + [Value::Uuid(node(4)), Value::Uuid(node(5))] + ] + ); +} + +/// Over [`partly_hidden`], read through a handle narrowed to Context 1. +fn a_hidden_node_reached_on_the_way_is_left_out_with_no_error(db: &Database, narrowed: &Database) { + // Back from node 5: nodes 2 and 4 are one step away, node 1 two. + let back = from(5, "(a)<-[:E]-{1,2}(b)"); + assert_eq!(support::rows(db, &back), reached(&[(2, 1), (4, 1), (1, 2)])); + match narrowed.execute(&back, ¶ms! {}) { + Ok(result) => assert_eq!(result.rows(), reached(&[(4, 1), (1, 2)])), + Err(error) => panic!("a walk that meets a hidden node was refused: {error:?}"), + } +} + +#[test] +fn a_pattern_pinned_to_a_hidden_node_is_refused_by_the_rule_that_hid_it() { + // Hidden by its Context. + let db = partly_hidden("graph-pinned-context"); + let narrowed = in_contexts(&db, &[1]); + let by_subquery = format!( + "WHERE a.id = (SELECT id FROM things WHERE id = '{}')", + node(2) + ); + for sql in [ + from(2, "(a)-[:E]->(b)"), + from(2, "(a)-[:E]->{1,3}(b)"), + pattern("(a)-[:E]->(b)", &by_subquery), + ] { + match narrowed.execute(&sql, ¶ms! {}) { + Err(Error::ContextScopeViolation { .. }) => {} + other => panic!("{sql}\ngot {other:?}"), + } + } + // A node no row carries is hidden from nobody: the pattern is answered. + assert_eq!( + support::rows(&narrowed, &from(6, "(a)<-[:E]-(b)")), + reached(&[(1, 1)]) + ); + assert_eq!( + support::rows(&narrowed, &from(99, "(a)-[:E]->(b)")), + reached(&[]) + ); + // A list of keys is a list read: the hidden key is left out of it. + let (one, two) = (node(1), node(2)); + for filter in [ + format!("a.id = '{one}' OR a.id = '{two}'"), + format!("a.id IN ('{one}', '{two}')"), + ] { + let sql = pattern("(a)-[:E]->(b)", &format!("WHERE {filter}")); + assert_eq!(support::rows(&narrowed, &sql), reached(&[(4, 1), (6, 1)])); + } + + // A table of nodes under a Context whose key and indexes do not begin with `id` cannot be + // asked who may see a node, so a handle narrowed to Contexts is refused the pattern. + let db = store( + "graph-no-id-key", + &[ + EDGES, + "CREATE TABLE nodes (id UUID NOT NULL, context_id UUID CONTEXT_ID, PRIMARY KEY (context_id, id))", + ], + ); + let asked = in_contexts(&db, &[1]).execute(&from(1, "(a)-[:E]->(b)"), ¶ms! {}); + assert!(matches!(asked, Err(Error::PlanError(_))), "{asked:?}"); + + // Hidden by a grant the principal does not hold: node 11 is granted, node 12 is not. + let db = store("graph-pinned-grant", &[EDGES, GRANTS, FILES]); + db.execute( + "INSERT INTO acl_grants (id, principal_kind, principal_id, acl_id) \ + VALUES ($id, 'Agent', 'ann', $acl)", + ¶ms! { "id" => node(900), "acl" => node(801) }, + ) + .expect("grant"); + for (n, acl) in [(11, 801), (12, 802)] { + db.execute( + "INSERT INTO files (id, acl_id) VALUES ($id, $acl)", + ¶ms! { "id" => node(n), "acl" => node(acl) }, + ) + .expect("insert a file"); + } + edge(&db, 1, 11, 12, 1); + edge(&db, 2, 11, 13, 1); + edge(&db, 3, 12, 13, 1); + let ann = db.scoped_with_constraints(None, None, Some(Principal::Agent("ann".to_owned()))); + match ann.execute(&from(12, "(a)-[:E]->(b)"), ¶ms! {}) { + Err(Error::AclDenied { .. }) => {} + other => panic!("a pattern pinned to a node with no grant got {other:?}"), + } + assert_eq!( + support::rows(&ann, &from(11, "(a)-[:E]->(b)")), + reached(&[(13, 1)]) + ); + + // Hidden by its label: node 21 is read under 'public', node 22 under 'internal'. + let db = store( + "graph-pinned-label", + &[ + EDGES, + "CREATE TABLE papers (id UUID PRIMARY KEY, label TEXT SCOPE_LABEL_READ ('public', \ + 'internal') WRITE ('internal'))", + ], + ); + for (n, label) in [(21, "public"), (22, "internal")] { + db.execute( + "INSERT INTO papers (id, label) VALUES ($id, $label)", + ¶ms! { "id" => node(n), "label" => label }, + ) + .expect("insert a paper"); + } + edge(&db, 1, 21, 22, 1); + edge(&db, 2, 22, 23, 1); + let labels = label_set(&["public"]); + let public = db.scoped_with_constraints(None, Some(labels), None); + match public.execute(&from(22, "(a)-[:E]->(b)"), ¶ms! {}) { + Err(Error::ScopeLabelViolation { .. }) => {} + other => panic!("a pattern pinned to a node under another label got {other:?}"), + } + assert_eq!( + support::rows(&public, &from(21, "(a)-[:E]->{1,2}(b)")), + reached(&[]) + ); +} + +#[test] +fn no_refusal_text_and_no_count_tells_of_a_hidden_node() { + let db = partly_hidden("graph-tells-nothing"); + let narrowed = in_contexts(&db, &[1]); + let error = support::refusal(&narrowed, &from(2, "(a)-[:E]->(b)")); + let words = format!("{error} {error:?}"); + for hidden in [node(2), context(2), node(3), node(5)] { + assert!( + !words.contains(&hidden.to_string()), + "the refusal names {hidden}: {words}" + ); + } + // A count over a walk counts what the handle is shown: nodes 4, 6, 1 and 5 of the seven. + let count = format!( + "WITH met AS (SELECT b_id FROM GRAPH_TABLE(edges MATCH (a)-[:E]->{{1,3}}(b) \ + WHERE a.id = '{}' COLUMNS (b.id AS b_id))) SELECT COUNT(*) FROM met", + node(1) + ); + assert_eq!(support::int(&db, &count), 7); + assert_eq!(support::int(&narrowed, &count), 4); +} + +#[test] +fn a_pattern_that_meets_a_row_needing_a_grant_is_refused_unless_another_rule_hid_the_row() { + let db = store( + "graph-principal-required", + &[ + EDGES, + GRANTS, + FILES, + "CREATE TABLE docs (id UUID PRIMARY KEY, \ + acl_id UUID ACL REFERENCES acl_grants(acl_id), context_id UUID CONTEXT_ID)", + ], + ); + // Node 30 is a file; node 41 is a document of Context 2, nodes 51 and 62 of Context 1. Every + // edge is under Context 1. The nodes 10, 11, 20, 40, 50 and 60 have no row. + db.execute( + "INSERT INTO files (id, acl_id) VALUES ($id, $acl)", + ¶ms! { "id" => node(30), "acl" => node(801) }, + ) + .expect("a file"); + for (n, of) in [(41, 2), (51, 1), (62, 1)] { + db.execute( + "INSERT INTO docs (id, acl_id, context_id) VALUES ($id, $acl, $context)", + ¶ms! { "id" => node(n), "acl" => node(801), "context" => context(of) }, + ) + .expect("a document"); + } + for (id, (a, b)) in [(10, 11), (20, 30), (40, 41), (50, 51), (60, 61), (61, 62)] + .into_iter() + .enumerate() + { + edge(&db, id as i64 + 1, a, b, 1); + } + let narrowed = in_contexts(&db, &[1]); + let system = db.scoped_with_constraints(None, None, Some(Principal::System)); + let required = |table: &str| Error::PrincipalRequired { + table: table.to_owned(), + }; + let step = "(a)-[:E]->(b)"; + let walk = "(a)-[:E]->{1,2}(b)"; + + assert_eq!( + support::rows(&narrowed, &from(10, step)), + reached(&[(11, 1)]), + "a pattern that reaches only nodes no such row carries is answered" + ); + for (reader, start, pattern_text, wanted, why) in [ + ( + &narrowed, + 20, + step, + required("files"), + "a reach to a row of an access-controlled table", + ), + ( + &narrowed, + 50, + step, + required("docs"), + "a document of the reader's Context at depth 1", + ), + ( + &narrowed, + 60, + walk, + required("docs"), + "a document of the reader's Context at depth 2", + ), + ( + &system, + 20, + step, + required("files"), + "the principal System holds no grants", + ), + ] { + assert_eq!( + support::refusal(reader, &from(start, pattern_text)).to_string(), + wanted.to_string(), + "{why} needs a handle that names a principal able to hold grants" + ); + } + assert_eq!( + support::rows(&narrowed, &from(40, step)), + reached(&[]), + "a document outside the reader's Contexts is hidden by that rule: no row and no error" + ); + assert!( + matches!( + support::refusal(&narrowed, &from(41, step)), + Error::ContextScopeViolation { .. } + ), + "a start named that the Context rule hides is that rule's refusal" + ); +} diff --git a/v2/contextdb/tests/large_values.rs b/v2/contextdb/tests/large_values.rs index 37e785df7..57fd16c94 100644 --- a/v2/contextdb/tests/large_values.rs +++ b/v2/contextdb/tests/large_values.rs @@ -2,25 +2,19 @@ //! byte whether or not the store keeps it compressed; text that repeats takes less room in //! the data file than its own bytes and text that does not shrink takes no more than it did; //! a value longer than 1 MiB and a vector are never compressed; the memory limit holds while -//! a compressed value is read and while one is written; and a damaged length is reported as -//! damage. +//! a compressed value is read and while one is written. //! //! Nothing here names compression, because nothing in the library does: a test sees it in //! what a statement returns, in the length of the data file and in the memory counted. mod support; -use std::fs; use std::path::Path; -use std::sync::Arc; -use std::sync::atomic::{AtomicU64, Ordering}; use contextdb::serde_json; -use contextdb::{ - Database, DatabaseOpenOptions, Error, ReadSession, ReadSessionOptions, Value, params, -}; +use contextdb::{Database, Error, Value, params}; -use support::{Call, Child, Kind, Run}; +use support::{Child, Kind, Run, data_file}; const KIB: usize = 1 << 10; const MIB: usize = 1 << 20; @@ -31,44 +25,6 @@ const LONGEST_COMPRESSED: usize = 1_048_576; // ---- shared by the tests of this file ---- -fn open_limited(folder: &Path, limit: usize) -> Database { - let mut options = DatabaseOpenOptions::default(); - options.memory_limit = Some(limit); - match support::open_with(folder, options) { - Ok(db) => db, - Err(error) => panic!("an open under a limit of {limit} bytes was refused: {error:?}"), - } -} - -fn read_limited(folder: &Path, limit: Option) -> ReadSession { - let mut options = ReadSessionOptions::default(); - options.memory_limit = limit; - match ReadSession::open_with_options(folder, options) { - Ok(reader) => reader, - Err(error) => panic!("a reader under a limit of {limit:?} was refused: {error:?}"), - } -} - -/// The bytes `SHOW MEMORY_LIMIT` reports as used. -fn used(on: &impl Run) -> usize { - let report = support::run(on, "SHOW MEMORY_LIMIT"); - let at = report.columns().iter().position(|name| name == "used"); - match (at, report.rows()) { - (Some(at), [row]) => match row[at] { - Value::Int64(bytes) => bytes as usize, - ref other => panic!("SHOW MEMORY_LIMIT reports {other:?} as used"), - }, - _ => panic!("SHOW MEMORY_LIMIT did not return one row with a column `used`"), - } -} - -/// The length of the store's data file, in bytes. -fn data_file(folder: &Path) -> u64 { - fs::metadata(folder.join("data")) - .expect("the store's data file") - .len() -} - /// The outcome of a statement that selects large values, with the rows left out of what a /// failure prints: a megabyte of text does not belong in a test's output. fn answered(on: &impl Run, sql: &str, id: i64) -> contextdb::Result>> { @@ -314,7 +270,7 @@ fn large_text_and_json_come_back_byte_for_byte() { /// Opens the store for reading, checks every row of `docs` against the content made from its /// id, and announces `matched `. fn reader_of_docs(role: &support::Role) { - let reader = ReadSession::open(&role.folder).expect("open the store for reading"); + let reader = support::open_reader(&role.folder, None); let changes = role.number("changes") as usize; let matched = assert_docs_are(&reader, changes, "a reader in another process"); support::say(format!("matched {matched}")); @@ -404,8 +360,12 @@ fn a_text_longer_than_one_mebibyte_and_a_vector_are_stored_as_they_are() { // It reads back under a limit that fits it once. `SELECT *` hands the row over as it // was read; a select list that names the column works its value out as a copy. - let reader = read_limited(&folder, Some(once)); - assert_eq!(used(&reader), 9 * MIB, "set aside by the open"); + let reader = support::open_reader(&folder, Some(once)); + assert_eq!( + support::memory_used(&reader), + 9 * MIB, + "set aside by the open" + ); match answered(&reader, "SELECT * FROM notes WHERE id = $id", 1) { Ok(rows) => match rows.as_slice() { [row] => { @@ -419,7 +379,7 @@ fn a_text_longer_than_one_mebibyte_and_a_vector_are_stored_as_they_are() { ), } assert_eq!( - used(&reader), + support::memory_used(&reader), 9 * MIB, "memory in use once the row is dropped" ); @@ -439,7 +399,12 @@ fn a_text_longer_than_one_mebibyte_and_a_vector_are_stored_as_they_are() { "the data file is {length} bytes long: a repeating text of {LONGEST_COMPRESSED} bytes \ was stored as it is" ); - assert_note_is(&read_limited(&folder, None), 1, &body, "exactly 1 MiB"); + assert_note_is( + &support::open_reader(&folder, None), + 1, + &body, + "exactly 1 MiB", + ); // A vector is never compressed, whatever it holds. A thousand vectors of 1,024 equal // numbers are 4,096,000 bytes that would shrink to a few kilobytes; each is kept beside @@ -470,7 +435,7 @@ fn a_text_longer_than_one_mebibyte_and_a_vector_are_stored_as_they_are() { "the data file is {length} bytes long: too short to hold {put_in} bytes of vectors as \ they are, so a vector was stored compressed" ); - let reader = read_limited(&folder, None); + let reader = support::open_reader(&folder, None); let last = support::rows(&reader, "SELECT v FROM shapes WHERE id = 1000"); assert!( last == [[Value::Vector(same)]], @@ -516,7 +481,7 @@ fn a_compressed_value_too_large_for_the_limit_is_refused() { // Through a reader with the limit, then through a writer with it. let refused = |on: &dyn Run, door: &str| { - let before = used(&on); + let before = support::memory_used(&on); assert_eq!(before, 9 * MIB, "{door}: set aside by the open"); // Asked twice: the first refusal left nothing counted, so the second is the same. let mut refusals = Vec::new(); @@ -536,7 +501,11 @@ fn a_compressed_value_too_large_for_the_limit_is_refused() { Err(other) => panic!("{door}: the select was refused as {other:?}"), Ok(rows) => panic!("{door}: the select was answered with {} rows", rows.len()), } - assert_eq!(used(&on), before, "{door}: memory in use after the refusal"); + assert_eq!( + support::memory_used(&on), + before, + "{door}: memory in use after the refusal" + ); } assert_eq!( refusals[0], refusals[1], @@ -559,16 +528,25 @@ fn a_compressed_value_too_large_for_the_limit_is_refused() { // The rest of the table answers in the same session. assert_note_is(&on, 2, "small", door); assert_eq!(support::int(&on, "SELECT COUNT(*) FROM notes"), 2, "{door}"); - assert_eq!(used(&on), before, "{door}: memory in use at the end"); + assert_eq!( + support::memory_used(&on), + before, + "{door}: memory in use at the end" + ); }; - refused(&read_limited(&folder, Some(LIMIT)), "a reader"); - let db = open_limited(&folder, LIMIT); + refused(&support::open_reader(&folder, Some(LIMIT)), "a reader"); + let db = support::open_limited(&folder, LIMIT); refused(&db, "the writer"); assert_eq!(db.memory_used(), 9 * MIB); support::close(db); // The store is unharmed: a reader with no limit returns the value byte for byte. - assert_note_is(&read_limited(&folder, None), 1, &body, "under no limit"); + assert_note_is( + &support::open_reader(&folder, None), + 1, + &body, + "under no limit", + ); } #[test] @@ -612,7 +590,7 @@ fn a_commit_with_no_room_to_compress_is_written_plain() { ); // Read by a reader, which has no limit: the store remembers the one set above for its // next writer. - let reader = read_limited(&folder, None); + let reader = support::open_reader(&folder, None); assert_note_is(&reader, 1, &body, "written with no room to compress"); // With room: the same row, committed the same way with no limit set, is compressed. @@ -629,88 +607,12 @@ fn a_commit_with_no_room_to_compress_is_written_plain() { "the data file is {length} bytes long: with room to compress, a repeating text of \ {LEN} bytes was stored as it is" ); - assert_note_is(&read_limited(&folder, None), 1, &body, "written with room"); -} - -// ---- damage ---- - -#[test] -fn a_damaged_length_of_a_compressed_value_is_reported_as_damage() { - const LEN: usize = LONGEST_COMPRESSED; - // A compressed text record begins with the byte 0x84 and then the length of the value in - // 8 bytes, low byte first. - const BEGINS: [u8; 9] = [0x84, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00]; - assert_eq!(BEGINS[1..], (LEN as u64).to_le_bytes()); - - let folder = support::folder("damaged-length"); - let body = support::large_text(Kind::Repeating, 1, LEN); - let db = support::open(&folder); - support::run(&db, NOTES); - insert_note(&db, 1, &body); - support::close(db); - - // A length no store holds, one byte more than the value has, one byte less, half of it, none. - for wrong in [ - u64::MAX, - 1_u64 << 40, - LEN as u64 + 1, - LEN as u64 - 1, - LEN as u64 / 2, - 0, - ] { - // A storage door that, in every read, puts the wrong length after that 0x84. - let changed = Arc::new(AtomicU64::new(0)); - let mut options = ReadSessionOptions::default(); - options.memory_limit = Some(64 * MIB); - options.storage = Some(support::storage({ - let changed = changed.clone(); - move |call| { - let Call::Read(_, bytes) = call else { - return; - }; - let mut from = 0; - while let Some(found) = bytes[from..] - .windows(BEGINS.len()) - .position(|window| window == BEGINS) - { - let at = from + found; - bytes[at + 1..at + 9].copy_from_slice(&wrong.to_le_bytes()); - changed.fetch_add(1, Ordering::SeqCst); - from = at + BEGINS.len(); - } - } - })); - let reader = ReadSession::open_with_options(&folder, options) - .unwrap_or_else(|error| panic!("the store did not open for reading: {error:?}")); - let before = used(&reader); - - // Damage, by name: never a panic, never the memory limit's refusal, never a value. - // Two checks stand between the changed bytes and an answer, the checksum of the - // page they are in and the record's own length against its stored bytes; whichever - // meets them first, the statement is told the store is damaged. - match answered(&reader, "SELECT body FROM notes WHERE id = $id", 1) { - Err(Error::StoreCorrupted { path, .. }) => assert_eq!(path, folder), - Err(other) => panic!("a recorded length of {wrong} was refused as {other:?}"), - Ok(rows) => panic!( - "a recorded length of {wrong} was answered with {} rows", - rows.len() - ), - } - assert_eq!( - used(&reader), - before, - "memory in use after a recorded length of {wrong}" - ); - // The door did change a length, or this test shows nothing. - assert!( - changed.load(Ordering::SeqCst) > 0, - "no read of the data file held the nine bytes a compressed record of this value \ - begins with, so no length was changed to {wrong}" - ); - } - - // Through an untouched door the value is as it was written. - assert_note_is(&read_limited(&folder, None), 1, &body, "undamaged"); + assert_note_is( + &support::open_reader(&folder, None), + 1, + &body, + "written with room", + ); } #[test] @@ -741,8 +643,12 @@ fn a_large_text_selected_by_name_is_held_once() { "the data file of a {kind:?} text of {LEN} bytes is {length} bytes long" ); - let reader = read_limited(&folder, Some(once)); - assert_eq!(used(&reader), 9 * MIB, "set aside by the open"); + let reader = support::open_reader(&folder, Some(once)); + assert_eq!( + support::memory_used(&reader), + 9 * MIB, + "set aside by the open" + ); // The select list names the column. The value is one text, whichever way the // statement asks for it, and a limit with room for it once is room enough. match answered(&reader, "SELECT body FROM notes WHERE id = $id", 1) { @@ -759,7 +665,7 @@ fn a_large_text_selected_by_name_is_held_once() { ), } assert_eq!( - used(&reader), + support::memory_used(&reader), 9 * MIB, "memory in use once the row is dropped" ); diff --git a/v2/contextdb/tests/memory.rs b/v2/contextdb/tests/memory.rs index 365611434..830efee2e 100644 --- a/v2/contextdb/tests/memory.rs +++ b/v2/contextdb/tests/memory.rs @@ -4,12 +4,8 @@ mod support; -use std::path::Path; - use contextdb::serde_json::{self, json}; -use contextdb::{ - Database, DatabaseOpenOptions, Error, ReadSession, ReadSessionOptions, Value, params, -}; +use contextdb::{Error, Value, params}; use support::Run; @@ -19,7 +15,7 @@ const MIB: usize = 1 << 20; fn a_statement_that_would_cross_the_limit_is_refused_by_name_and_committed_rows_stay() { let folder = support::folder("memory-limit-refuses"); let limit = 16 * MIB; - let db = open_limited(&folder, limit); + let db = support::open_limited(&folder, limit); assert_eq!(db.memory_limit(), Some(limit)); support::declare(&db); support::insert(&db, 1..=10); @@ -83,7 +79,7 @@ fn a_reader_has_its_own_limit() { let all = "SELECT id, body FROM big ORDER BY id"; // A reader with a limit of 16 MiB is refused, and the refusal names the reader's limit. - let narrow = read_limited(&folder, 16 * MIB); + let narrow = support::open_reader(&folder, Some(16 * MIB)); over_the_limit(support::refusal(&narrow, all), 16 * MIB); // The session is as good as before: it reads what fits. assert_eq!(support::int(&narrow, "SELECT COUNT(*) FROM big"), 40); @@ -93,14 +89,14 @@ fn a_reader_has_its_own_limit() { ); // A reader with no limit, and the writer that has none, answer the same statement. - let wide = ReadSession::open(&folder).expect("open the store for reading"); + let wide = support::open_reader(&folder, None); assert_eq!(support::rows(&wide, all).len(), 40); assert_eq!(support::rows(&db, all).len(), 40); // A writer with a limit of 32 MiB is refused by its own limit, while the two readers go on // by theirs. support::close(db); - let db = open_limited(&folder, 32 * MIB); + let db = support::open_limited(&folder, 32 * MIB); over_the_limit(support::refusal(&db, all), 32 * MIB); over_the_limit(support::refusal(&narrow, all), 16 * MIB); assert_eq!(support::rows(&wide, all).len(), 40); @@ -131,8 +127,11 @@ fn a_value_too_large_for_the_limit_is_refused_while_its_row_is_still_counted() { // Through a reader with the limit, then through a writer with it. Neither open is refused: // nothing of the large value is read until a statement selects it. - the_large_value_is_refused_and_its_row_counted(&read_limited(&folder, limit), limit); - the_large_value_is_refused_and_its_row_counted(&open_limited(&folder, limit), limit); + the_large_value_is_refused_and_its_row_counted( + &support::open_reader(&folder, Some(limit)), + limit, + ); + the_large_value_is_refused_and_its_row_counted(&support::open_limited(&folder, limit), limit); } fn the_large_value_is_refused_and_its_row_counted(on: &impl Run, limit: usize) { @@ -163,6 +162,13 @@ fn the_large_value_is_refused_and_its_row_counted(on: &impl Run, limit: usize) { [[Value::Json(json!({ "k": 1 }))]] ); assert_eq!(support::int(on, "SELECT COUNT(id) FROM docs"), 3); + let join = "SELECT a.id FROM docs a JOIN docs b ON a.id = b.id \ + WHERE a.id IN (SELECT id FROM docs WHERE id = 2) LIMIT 1"; + assert_eq!(support::rows(on, join), [[Value::Int64(2)]]); + // A window reads only the columns it names: the value no column of it names is never loaded. + let window = "WITH r AS (SELECT id, title, ROW_NUMBER() OVER (PARTITION BY title ORDER BY id) \ + AS n FROM docs) SELECT id FROM r WHERE title = 'doc-2' AND n <= 3"; + assert_eq!(support::rows(on, window), [[Value::Int64(2)]]); } #[test] @@ -170,9 +176,7 @@ fn memory_in_use_goes_back_when_a_result_is_dropped() { let folder = support::folder("memory-goes-back"); let db = support::open(&folder); support::declare(&db); - let tx = db.transaction().expect("begin"); - support::insert(&tx, 1..=1000); - tx.commit().expect("commit"); + support::insert_together(&db, 1..=1000); // Run the scan once before measuring, so that anything the first statement sets up for good // is already there. let _ = support::run(&db, support::SCAN); @@ -205,6 +209,15 @@ fn memory_in_use_goes_back_when_a_result_is_dropped() { "memory in use after the result was dropped" ); + // What a subquery's list took goes back when the part reading it is done. + let held = |filter: &str| { + let arm = format!("SELECT COUNT(*) FROM t WHERE {filter}"); + let _result = support::run(&db, &format!("{arm} UNION ALL {arm}")); + db.memory_used() + }; + let _ = held("id >= 1"); + let plain = held("id >= 1"); + assert_eq!(held("id IN (SELECT id FROM t)"), plain, "with a subquery"); // The same for the rows a transaction holds, when it is rolled back. let tx = db.transaction().expect("begin"); support::insert(&tx, 1001..=1100); @@ -238,33 +251,36 @@ fn a_declared_limit_survives_reopen_however_it_was_set() { db.set_memory_limit(Some(512 * MIB)) .expect("declare a limit"); assert_eq!(db.memory_limit(), Some(512 * MIB)); - assert_eq!(shown(&db, "limit"), Value::Int64(536_870_912)); - let db = reopen(db, &folder); + assert_eq!( + support::memory_shown(&db, "limit"), + Value::Int64(536_870_912) + ); + let db = support::reopen(db, &folder); assert_eq!(db.memory_limit(), Some(512 * MIB)); // Declared in SQL, in the sizes SQL takes. support::run(&db, "SET MEMORY_LIMIT 2G"); assert_eq!(db.memory_limit(), Some(2_147_483_648)); - let db = reopen(db, &folder); + let db = support::reopen(db, &folder); assert_eq!(db.memory_limit(), Some(2_147_483_648)); // An open that names a limit has that limit for as long as it is open. The store goes on // remembering the one that was declared. support::close(db); - let db = open_limited(&folder, 64 * MIB); + let db = support::open_limited(&folder, 64 * MIB); assert_eq!(db.memory_limit(), Some(64 * MIB)); - let db = reopen(db, &folder); + let db = support::reopen(db, &folder); assert_eq!(db.memory_limit(), Some(2_147_483_648)); // Declared as none, either way, it is none after reopening. support::run(&db, "SET MEMORY_LIMIT NONE"); assert_eq!(db.memory_limit(), None); - let db = reopen(db, &folder); + let db = support::reopen(db, &folder); assert_eq!(db.memory_limit(), None); support::run(&db, "SET MEMORY_LIMIT 512M"); assert_eq!(db.memory_limit(), Some(512 * MIB)); db.set_memory_limit(None).expect("declare no limit"); - let db = reopen(db, &folder); + let db = support::reopen(db, &folder); assert_eq!(db.memory_limit(), None); // A reader reports a limit too, and it is the reader's own, not the one the store keeps. @@ -276,13 +292,19 @@ fn a_declared_limit_survives_reopen_however_it_was_set() { "startup_ceiling", "ceiling_refresh_failures", ]; - let reader = read_limited(&folder, 64 * MIB); + let reader = support::open_reader(&folder, Some(64 * MIB)); assert_eq!( support::run(&reader, "SHOW MEMORY_LIMIT").columns(), columns ); - assert_eq!(shown(&reader, "limit"), Value::Int64(64 * MIB as i64)); - match (shown(&reader, "used"), shown(&reader, "available")) { + assert_eq!( + support::memory_shown(&reader, "limit"), + Value::Int64(64 * MIB as i64) + ); + match ( + support::memory_shown(&reader, "used"), + support::memory_shown(&reader, "available"), + ) { (Value::Int64(used), Value::Int64(available)) => { assert_eq!( used + available, @@ -293,13 +315,19 @@ fn a_declared_limit_survives_reopen_however_it_was_set() { other => panic!("a reader with a limit reports used and available as {other:?}"), } // A reader that was given no limit has none, whatever the store keeps for its writer. - let reader = ReadSession::open(&folder).expect("open the store for reading"); + let reader = support::open_reader(&folder, None); assert_eq!( support::run(&reader, "SHOW MEMORY_LIMIT").columns(), columns ); - assert_eq!(shown(&reader, "limit"), Value::Text("none".to_owned())); - assert_eq!(shown(&db, "limit"), Value::Int64(2_147_483_648)); + assert_eq!( + support::memory_shown(&reader, "limit"), + Value::Text("none".to_owned()) + ); + assert_eq!( + support::memory_shown(&db, "limit"), + Value::Int64(2_147_483_648) + ); } #[test] @@ -315,17 +343,17 @@ fn a_limit_set_inside_a_transaction_holds_at_once_and_a_rollback_does_not_undo_i support::insert(&tx, 1..=1); support::run(&tx, "SET MEMORY_LIMIT 512M"); let limit = Value::Int64(536_870_912); - assert_eq!(shown(&tx, "limit"), limit); - assert_eq!(shown(&db, "limit"), limit); + assert_eq!(support::memory_shown(&tx, "limit"), limit); + assert_eq!(support::memory_shown(&db, "limit"), limit); assert_eq!(db.memory_limit(), Some(512 * MIB)); // The rollback takes the row back and leaves the limit, in this open and in the store. tx.rollback(); assert_eq!(support::int(&db, "SELECT COUNT(*) FROM t"), 0); - assert_eq!(shown(&db, "limit"), limit); + assert_eq!(support::memory_shown(&db, "limit"), limit); assert_eq!(db.memory_limit(), Some(512 * MIB)); - let db = reopen(db, &folder); - assert_eq!(shown(&db, "limit"), limit); + let db = support::reopen(db, &folder); + assert_eq!(support::memory_shown(&db, "limit"), limit); assert_eq!(db.memory_limit(), Some(512 * MIB)); // The same when the transaction is dropped instead. @@ -335,31 +363,16 @@ fn a_limit_set_inside_a_transaction_holds_at_once_and_a_rollback_does_not_undo_i // The transaction is dropped here, uncommitted. } assert_eq!(db.memory_limit(), Some(2_147_483_648)); - let db = reopen(db, &folder); - assert_eq!(shown(&db, "limit"), Value::Int64(2_147_483_648)); + let db = support::reopen(db, &folder); + assert_eq!( + support::memory_shown(&db, "limit"), + Value::Int64(2_147_483_648) + ); assert_eq!(db.memory_limit(), Some(2_147_483_648)); } // ---- shared by the tests of this file ---- -fn open_limited(folder: &Path, limit: usize) -> Database { - let mut options = DatabaseOpenOptions::default(); - options.memory_limit = Some(limit); - support::open_with(folder, options).expect("open the store for writing under a limit") -} - -fn read_limited(folder: &Path, limit: usize) -> ReadSession { - let mut options = ReadSessionOptions::default(); - options.memory_limit = Some(limit); - ReadSession::open_with_options(folder, options) - .expect("open the store for reading under a limit") -} - -fn reopen(db: Database, folder: &Path) -> Database { - support::close(db); - support::open(folder) -} - /// Asserts that a refusal is the memory limit's and names this limit. Returns the bytes that /// were asked for and the bytes that were left. fn over_the_limit(refusal: Error, limit: usize) -> (u64, u64) { @@ -383,17 +396,3 @@ fn over_the_limit(refusal: Error, limit: usize) -> (u64, u64) { other => panic!("crossing the memory limit was refused as {other:?}"), } } - -/// One column of what `SHOW MEMORY_LIMIT` reports. -fn shown(on: &impl Run, column: &str) -> Value { - let report = support::run(on, "SHOW MEMORY_LIMIT"); - let at = report - .columns() - .iter() - .position(|name| name == column) - .unwrap_or_else(|| panic!("SHOW MEMORY_LIMIT has no column {column}")); - match report.rows() { - [row] => row[at].clone(), - rows => panic!("SHOW MEMORY_LIMIT returned {} rows", rows.len()), - } -} diff --git a/v2/contextdb/tests/memory_ceiling.rs b/v2/contextdb/tests/memory_ceiling.rs index c7389f55d..fe7270692 100644 --- a/v2/contextdb/tests/memory_ceiling.rs +++ b/v2/contextdb/tests/memory_ceiling.rs @@ -18,7 +18,7 @@ use std::fs; use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use contextdb::{ - Database, DatabaseOpenOptions, Error, ReadSession, ReadSessionOptions, Value, params, + Database, DatabaseOpenOptions, Error, ReadSession, ReadSessionOptions, Uuid, Value, params, }; const LIMIT: usize = 64 << 20; @@ -179,6 +179,16 @@ fn load_and_scan(role: support::Role) { assert_eq!(support::int(&db, "SELECT COUNT(name) FROM t"), ROWS); support::say("scanned names"); assert_eq!(support::int(&db, "SELECT SUM(tag) FROM t"), ROWS / 10 * 45); + // A filtered sum takes each row that passes once (CDB-330): tags 0 to 2 of every ten rows, + // and the tags of the half of the rows whose name sorts after row 500000. + assert_eq!( + support::int(&db, "SELECT SUM(tag) FROM t WHERE tag < 3"), + ROWS / 10 * 3 + ); + assert_eq!( + support::int(&db, "SELECT SUM(tag) FROM t WHERE name > 'row-0500000'"), + ROWS / 20 * 45 + ); support::say("scanned tags"); // And one page from the far end of the table, each row whole. let last_page = db @@ -587,7 +597,7 @@ fn an_indexed_search_and_a_build_stay_under_the_limit() { let folder = support::folder("build-under-the-limit"); let db = support::open(&folder); write_the_filler(&db); - support::declare_docs(&db, 64, "AUTO_INDEX_AT 1000"); + support::declare_docs(&db, 64, "INDEXING_THRESHOLD 1000"); support::load_docs(&db, 1..=1100, "a", |n| support::gathered(n, 64)); support::close(db); @@ -690,3 +700,80 @@ fn a_build_under_the_limit(role: &support::Role) { support::say(format!("before {before}")); support::say(format!("peak {}", ALLOCATED.peak.load(Ordering::Relaxed))); } + +// ---- one more edge from a node that has many ---- + +const EDGES_FROM_ONE_NODE: i64 = 20_000; + +/// The bytes a walk over this node's edges would hold at the least: a node id and its place in +/// the walk, 40 bytes each, for each edge. One edge written beside them must take far less. +const A_WALK_OVER_THEM: u64 = EDGES_FROM_ONE_NODE as u64 * 40; + +#[test] +fn one_more_edge_from_a_node_with_many_edges_reads_none_of_them() { + if let Some(role) = support::role() { + return one_more_edge(&role); + } + let folder = support::folder("edges-from-one-node"); + let db = support::open(&folder); + support::run( + &db, + "CREATE TABLE edges (id INTEGER PRIMARY KEY, source_id UUID NOT NULL, \ + target_id UUID NOT NULL, edge_type TEXT NOT NULL) DAG('E')", + ); + let tx = db.transaction().expect("begin"); + for id in 1..=EDGES_FROM_ONE_NODE { + let values = params! { "id" => id, "to" => Uuid::from_u128(id as u128 + 1) }; + tx.execute( + "INSERT INTO edges (id, source_id, target_id, edge_type) \ + VALUES ($id, '00000000-0000-0000-0000-000000000001', $to, 'E')", + &values, + ) + .expect("an edge from the one node"); + } + tx.commit().expect("commit the edges"); + support::close(db); + + let lines = support::Child::start( + "one_more_edge_from_a_node_with_many_edges_reads_none_of_them", + "edge", + &folder, + ) + .end(); + assert!( + lines.iter().any(|line| line == "accepted"), + "the edge was not accepted: {lines:?}" + ); + let taken = support::last_number(&lines, "taken").expect("the child announces it"); + assert!( + taken < A_WALK_OVER_THEM / 2, + "one edge from a node with {EDGES_FROM_ONE_NODE} edges took {taken} bytes, as much as a \ + walk over the node's edges ({A_WALK_OVER_THEM}): writing an edge reads the other edges \ + of its source, so what it costs grows with how many there are" + ); +} + +/// Opens the store, writes one more edge from the node, and announces `accepted` and +/// `taken `, the most the process held above what it held before the edge. +fn one_more_edge(role: &support::Role) { + let mut options = DatabaseOpenOptions::default(); + options.memory_limit = Some(BUILD_LIMIT); + let db = support::open_with(&role.folder, options).expect("open the store under the limit"); + let before = ALLOCATED.now.load(Ordering::Relaxed); + ALLOCATED.peak.store(before, Ordering::Relaxed); + let values = params! { + "id" => EDGES_FROM_ONE_NODE + 1, + "to" => Uuid::from_u128(EDGES_FROM_ONE_NODE as u128 + 10) + }; + match db.execute( + "INSERT INTO edges (id, source_id, target_id, edge_type) \ + VALUES ($id, '00000000-0000-0000-0000-000000000001', $to, 'E')", + &values, + ) { + Ok(_) => support::say("accepted"), + Err(error) => support::say(format!("refused {error:?}")), + } + let peak = ALLOCATED.peak.load(Ordering::Relaxed); + support::say(format!("taken {}", peak - before)); + support::close(db); +} diff --git a/v2/contextdb/tests/propagation.rs b/v2/contextdb/tests/propagation.rs index 498d20b62..f62a02305 100644 --- a/v2/contextdb/tests/propagation.rs +++ b/v2/contextdb/tests/propagation.rs @@ -172,16 +172,15 @@ fn an_aborting_propagation_names_its_table_and_undoes_its_statement_and_no_other assert_eq!(statuses(&db, "tasks"), wanted); } +const EDGES: &str = "CREATE TABLE edges (id INTEGER PRIMARY KEY, source_id UUID NOT NULL, \ + target_id UUID NOT NULL, edge_type TEXT NOT NULL)"; + /// Declares `claims`, whose rows follow each other into `invalidated` along incoming `CITES` /// edges, with this `clause` after the declaration, and the edge table beside it. Claim `n` /// has the id `Uuid::from_u128(n)`. fn store_of_claims(name: &str, claims: u128, clause: &str) -> Database { let db = support::open(&support::folder(name)); - support::run( - &db, - "CREATE TABLE edges (id INTEGER PRIMARY KEY, source_id UUID NOT NULL, \ - target_id UUID NOT NULL, edge_type TEXT NOT NULL)", - ); + support::run(&db, EDGES); support::run( &db, &format!( @@ -252,11 +251,7 @@ fn node(n: u128) -> Uuid { /// `rules` after its columns. fn store_of_nodes(name: &str, rules: &str, first: &str, count: u128) -> Database { let db = support::open(&support::folder(name)); - support::run( - &db, - "CREATE TABLE edges (id INTEGER PRIMARY KEY, source_id UUID NOT NULL, \ - target_id UUID NOT NULL, edge_type TEXT NOT NULL)", - ); + support::run(&db, EDGES); support::run( &db, &format!( diff --git a/v2/contextdb/tests/query_work.rs b/v2/contextdb/tests/query_work.rs new file mode 100644 index 000000000..98295c65f --- /dev/null +++ b/v2/contextdb/tests/query_work.rs @@ -0,0 +1,672 @@ +//! Counted work of the statements that read more than one table or more than one row for an +//! answer: each reads the stored rows its answer needs and holds only what it says it holds, +//! whatever the size of the tables. + +mod support; + +use std::collections::BTreeSet; + +use contextdb::{ + ContextId, Database, DatabaseOpenOptions, Error, Uuid, Value, params, serde_json::json, +}; + +const MIB: usize = 1 << 20; + +/// A store with the usual table `t` of a thousand rows and `owners`, one row for each row of +/// `t`, reached from it through the index on `t_id`: owner `n` is `(5000 + n, n, "note-")`. +fn owned(name: &str) -> Database { + let db = support::open(&support::folder(name)); + support::declare(&db); + support::run( + &db, + "CREATE TABLE owners (id INTEGER PRIMARY KEY, t_id INTEGER NOT NULL, note TEXT)", + ); + support::run(&db, "CREATE INDEX owners_t ON owners (t_id)"); + let tx = db.transaction().expect("begin"); + support::insert(&tx, 1..=1000); + for n in 1..=1000_i64 { + tx.execute( + "INSERT INTO owners (id, t_id, note) VALUES ($id, $t, $note)", + ¶ms! { "id" => 5000 + n, "t" => n, "note" => format!("note-{n}") }, + ) + .expect("insert an owner"); + } + tx.commit().expect("commit"); + db +} + +/// A store under a limit of 16 MiB with these tables, each of 48 rows whose `body` is half a +/// mebibyte of text that begins with the table's name and the row's number: 24 MiB a table, +/// which the limit cannot hold, and every body different from every other. +fn large(name: &str, tables: &[&str]) -> Database { + let mut options = DatabaseOpenOptions::default(); + options.memory_limit = Some(16 * MIB); + let db = support::open_with(&support::folder(name), options).expect("open under a limit"); + for table in tables { + support::run( + &db, + &format!("CREATE TABLE {table} (id INTEGER PRIMARY KEY, body TEXT)"), + ); + for n in 1..=48_i64 { + db.execute( + &format!("INSERT INTO {table} (id, body) VALUES ($id, $body)"), + ¶ms! { "id" => n, "body" => format!("{table}-{n:02}-{}", "x".repeat(MIB / 2)) }, + ) + .expect("insert a large row"); + } + } + db +} + +/// The first bytes of the one text a statement returns. +fn head(db: &Database, sql: &str) -> String { + match support::rows(db, sql).as_slice() { + [row] => match row.as_slice() { + [Value::Text(text)] => text[..6].to_owned(), + other => panic!("{sql}\nreturned {other:?}, not one text"), + }, + other => panic!("{sql}\nreturned {} rows, not one", other.len()), + } +} + +#[test] +fn a_join_reads_one_right_row_for_each_left_row_through_an_index() { + let db = owned("join-through-an-index"); + let joined = support::run( + &db, + "SELECT x.id, o.note FROM t x JOIN owners o ON o.t_id = x.id WHERE x.id <= 10", + ); + let wanted: Vec> = (1..=10_i64) + .map(|n| vec![Value::Int64(n), Value::Text(format!("note-{n}"))]) + .collect(); + support::assert_same_rows(joined.rows(), &wanted, "the joined rows"); + // Ten rows of `t` and the one owner of each. A scan of `owners` reads a thousand. + assert_eq!(joined.rows_examined(), 20); + let sql = "SELECT x.id, o.note FROM t x JOIN owners o ON o.t_id = x.id WHERE x.id <= 8 \ + AND o.id IN (SELECT id FROM owners WHERE id <= 5007)"; + let listed = support::run(&db, sql); + assert_eq!(listed.rows().len(), 7); + assert_eq!(listed.rows_examined(), 22, "the list is read once"); + // Another indexed column of `owners` named by a list leaves the join on its index: the three + // names, the one row of `t`, and the one owner of it. + support::run(&db, "CREATE INDEX owners_note ON owners (note)"); + let by_note = "SELECT x.id FROM t x JOIN owners o ON o.t_id = x.id WHERE x.id = 1 \ + AND o.note IN (SELECT note FROM owners WHERE id <= 5003)"; + assert_eq!(support::run(&db, by_note).rows_examined(), 5); + + // A left 7.0 is no key of an INTEGER column and a left TEXT of 300 bytes cuts an index: the + // join still reads the other index (`jr_b`, or `jr_btag` past tag 6), one left row and the + // rows of b = 3. Row 100 is under Context 2, which a handle of Context 1 does not see. + for sql in [ + "CREATE TABLE jl (id INTEGER PRIMARY KEY, a REAL, b INTEGER, txt TEXT)", + "CREATE TABLE jr (id INTEGER PRIMARY KEY, a INTEGER, b INTEGER, txt TEXT, tag INTEGER, \ + context_id UUID NOT NULL CONTEXT_ID)", + "CREATE INDEX jr_ab ON jr (a, b)", + "CREATE INDEX jr_b ON jr (b)", + "CREATE INDEX jr_txt ON jr (txt, tag)", + "CREATE INDEX jr_btag ON jr (b, tag)", + ] { + support::run(&db, sql); + } + let (long, ctx) = ("x".repeat(300), Uuid::from_u128); + support::run(&db, &format!("INSERT INTO jl VALUES (1, 7.0, 3, '{long}')")); + for (id, a, b, owner) in (1..=12_i64) + .map(|n| (n, n, n % 4, 1)) + .chain([(100, 7, 3, 2)]) + { + let row = format!("({id}, {a}, {b}, '{long}', {id}, '{}')", ctx(owner)); + support::run(&db, &format!("INSERT INTO jr VALUES {row}")); + } + let seven = |n: i64| [Value::Int64(n)]; + let narrowed = db.scoped_with_contexts(BTreeSet::from([ContextId::new(ctx(1))])); + let by_a = "SELECT jr.id FROM jl JOIN jr ON jr.a = jl.a AND jr.b = jl.b"; + let found = support::run(&db, by_a); + support::assert_same_rows(found.rows(), &[seven(7), seven(100)], "7.0 equals 7"); + assert_eq!(found.rows_examined(), 1 + 4, "the left row, the 4 of b = 3"); + assert_eq!( + support::rows(&narrowed, by_a), + [seven(7)], + "hidden is unmatched" + ); + let by_txt = "SELECT jr.id FROM jl JOIN jr ON jr.txt = jl.txt AND jr.b = jl.b WHERE jr.tag > 6"; + let found = support::run(&db, by_txt); + support::assert_same_rows( + found.rows(), + &[seven(7), seven(11), seven(100)], + "b = 3, tag > 6", + ); + assert_eq!(found.rows_examined(), 1 + 3, "only the entries above tag 6"); + // The reader's shape: 7.0 is no key of INTEGER, so the join walks `r_ab`, not `r_b`. + for sql in [ + "CREATE TABLE rr (id INTEGER PRIMARY KEY, a INTEGER, b INTEGER)", + "CREATE INDEX r_ab ON rr (a, b)", + "CREATE INDEX r_b ON rr (b)", + "CREATE TABLE ll (id REAL, a INTEGER, b INTEGER)", + "INSERT INTO ll VALUES (7.0, 3, 5)", + ] { + support::run(&db, sql); + } + for id in 1..=501_i64 { + let a = if id == 7 { 3 } else { 0 }; + support::run(&db, &format!("INSERT INTO rr VALUES ({id}, {a}, 5)")); + } + let shape = support::run( + &db, + "SELECT ll.a, rr.id FROM ll JOIN rr ON rr.id = ll.id AND rr.a = ll.a AND rr.b = ll.b \ + WHERE rr.b = 5", + ); + support::assert_same_rows(shape.rows(), &[[Value::Int64(3), Value::Int64(7)]], "row 7"); + assert_eq!( + shape.rows_examined(), + 1 + 1, + "the left row and the row of (3, 5)" + ); + // By the whole key of `jr`, the rows of `b = 1` that pass the filter are not read: the left + // row and the one right row it names. + let by_key = support::run( + &db, + "SELECT jr.id FROM jl JOIN jr ON jr.id = jl.id WHERE jr.b = 1", + ); + support::assert_same_rows(by_key.rows(), &[seven(1)], "the key names row 1"); + assert_eq!(by_key.rows_examined(), 1 + 1, "not the 3 rows of b = 1"); +} + +#[test] +fn a_cross_join_reads_its_right_side_once_as_an_inner_join_that_always_holds_does() { + let db = owned("cross-join-reads-once"); + for join in ["CROSS JOIN owners o", "INNER JOIN owners o ON 1 = 1"] { + let counted = support::run( + &db, + &format!("SELECT COUNT(*) AS n FROM t x {join} WHERE x.id <= 3"), + ); + assert_eq!(counted.rows(), [[Value::Int64(3000)]], "{join}"); + // Three rows of `t`, and `owners` once: not once for each of the three. + assert_eq!(counted.rows_examined(), 1003, "{join}"); + } +} + +#[test] +fn rows_that_pass_through_a_statement_are_not_held_by_it() { + // Two tables of 24 MiB under a limit of 16 MiB: each answer is right only if the bodies + // that pass through a WITH name, a UNION ALL, a sort or a grouping are not all held. + let db = large("rows-pass-through", &["big", "more"]); + for (sql, wanted) in [ + ( + "WITH named AS (SELECT id, body FROM big) SELECT MAX(body) AS last FROM named", + "big-48", + ), + ( + "WITH whole AS (SELECT body FROM big UNION ALL SELECT body FROM more) \ + SELECT MAX(body) AS last FROM whole", + "more-4", + ), + ( + "SELECT MAX(body) AS last FROM big GROUP BY id / 100", + "big-48", + ), + ] { + assert_eq!(head(&db, sql), wanted, "{sql}"); + } + let rows = support::int( + &db, + "WITH whole AS (SELECT body FROM big UNION ALL SELECT body FROM more) \ + SELECT COUNT(body) AS n FROM whole", + ); + assert_eq!(rows, 96, "both tables pass through"); + // A subquery's text is copied into every row it is shown in: 48 rows of half a mebibyte. + assert_refused_by_the_memory_limit( + &db, + "SELECT id, (SELECT body FROM big WHERE id = 1) AS b FROM more", + ); + // A name read twice is read once and its rows kept: 48 ids fit. + let twice = + "WITH n AS (SELECT id FROM big) SELECT COUNT(*) AS c FROM n a JOIN n b ON a.id = b.id"; + assert_eq!( + support::int(&db, twice), + 48, + "a name read twice under the limit" + ); + // A sort keeps the rows that can still leave: LIMIT plus OFFSET of the 48 bodies. + let page = support::rows( + &db, + "SELECT id FROM big ORDER BY body DESC LIMIT 2 OFFSET 3", + ); + assert_eq!(page, [[Value::Int64(45)], [Value::Int64(44)]]); + // Forty-five bodies are 22.5 MiB, which the limit cannot hold. + assert_refused_by_the_memory_limit( + &db, + "SELECT id FROM big ORDER BY body DESC LIMIT 40 OFFSET 5", + ); +} + +#[test] +fn the_values_of_rows_that_offset_skips_are_not_held() { + // (rows, bytes of a value, limit): the skipped rows are over what a statement is left. + for (rows, len, limit) in [ + (20_100_i64, 1_usize << 10, 16 * MIB), + (2005, 64 << 10, 13 * MIB), + ] { + let db = loaded("offset-skips-values", limit, "body", rows, |n| { + padded(n, len) + }); + let skip = rows - 5; + let page = support::rows( + &db, + &format!("SELECT id, body FROM t ORDER BY id LIMIT 5 OFFSET {skip}"), + ); + assert_eq!(page.len(), 5, "five rows after the {skip} skipped"); + for (row, id) in page.iter().zip(skip + 1..) { + match row.as_slice() { + [Value::Int64(found), Value::Text(body)] => { + assert_eq!(*found, id); + assert_eq!(body, &padded(id, len), "the body of row {id}"); + } + other => panic!("a row of {} values, not a number and a body", other.len()), + } + } + } +} + +#[test] +fn row_number_reads_each_partition_to_its_bound_and_one_more() { + let db = support::open(&support::folder("row-number-reads-to-the-bound")); + support::run( + &db, + "CREATE TABLE sessions (id INTEGER PRIMARY KEY, ctx TEXT NOT NULL, at INTEGER NOT NULL)", + ); + support::run( + &db, + "CREATE INDEX sessions_newest ON sessions (ctx ASC, at DESC, id ASC)", + ); + // Session `n` is in the context `c` at the time `n`: three hundred in each. + let tx = db.transaction().expect("begin"); + for n in 1..=900_i64 { + tx.execute( + "INSERT INTO sessions (id, ctx, at) VALUES ($id, $ctx, $at)", + ¶ms! { "id" => n, "ctx" => format!("c{}", n % 3), "at" => n }, + ) + .expect("insert a session"); + } + tx.commit().expect("commit"); + let newest = support::run( + &db, + "WITH ranked AS ( \ + SELECT ctx, id, ROW_NUMBER() OVER (PARTITION BY ctx ORDER BY at DESC, id ASC) AS r \ + FROM sessions WHERE ctx IN ('c0', 'c1')) \ + SELECT ctx, id, r FROM ranked \ + WHERE (ctx = 'c0' AND r <= 2) OR (ctx = 'c1' AND r <= 1) ORDER BY ctx ASC, r ASC", + ); + let row = + |ctx: &str, id: i64, r: i64| vec![support::text(ctx), Value::Int64(id), Value::Int64(r)]; + assert_eq!( + newest.rows(), + [row("c0", 900, 1), row("c0", 897, 2), row("c1", 898, 1)] + ); + // The three rows returned, and at most one more in each of the two partitions. Sorting the + // input reads the six hundred rows of the two contexts. + assert!( + (3..=5).contains(&newest.rows_examined()), + "{} rows were read", + newest.rows_examined() + ); +} + +#[test] +fn limit_with_offset_over_an_ordered_index_reads_the_rows_it_skips_and_returns() { + let db = support::open(&support::folder("limit-offset-over-an-index")); + support::run( + &db, + "CREATE TABLE events (id INTEGER PRIMARY KEY, kind TEXT NOT NULL, seq INTEGER NOT NULL)", + ); + support::run(&db, support::EVENTS_INDEX); + // Event `n` is `(n, "k", n)`. + let tx = db.transaction().expect("begin"); + for n in 1..=1000_i64 { + tx.execute( + "INSERT INTO events (id, kind, seq) VALUES ($id, $kind, $seq)", + ¶ms! { "id" => n, "kind" => format!("k{}", n % 5), "seq" => n }, + ) + .expect("insert an event"); + } + tx.commit().expect("commit"); + let page = support::run( + &db, + "SELECT id FROM events WHERE kind = 'k1' ORDER BY seq DESC LIMIT 5 OFFSET 10", + ); + // The newest of the kind is 996; ten are skipped. + let wanted = [946_i64, 941, 936, 931, 926].map(|n| [Value::Int64(n)]); + assert_eq!(page.rows(), wanted); + assert_eq!(page.rows_examined(), 15); +} + +#[test] +fn a_lookup_by_an_indexed_json_path_reads_the_rows_it_returns() { + let db = support::open(&support::folder("json-path-lookup")); + support::run(&db, "CREATE TABLE docs (id INTEGER PRIMARY KEY, doc JSON)"); + support::run(&db, "CREATE INDEX docs_kind ON docs ((doc -> 'kind'))"); + // Document `n` is `{"kind": "k", "n": n}`. + let tx = db.transaction().expect("begin"); + for n in 1..=1000_i64 { + tx.execute( + "INSERT INTO docs (id, doc) VALUES ($id, $doc)", + ¶ms! { "id" => n, "doc" => json!({ "kind": format!("k{}", n % 100), "n": n }) }, + ) + .expect("insert a document"); + } + tx.commit().expect("commit"); + let found = support::run(&db, "SELECT id FROM docs WHERE doc -> 'kind' = '\"k7\"'"); + let wanted: Vec> = (0..10_i64) + .map(|n| vec![Value::Int64(n * 100 + 7)]) + .collect(); + support::assert_same_rows(found.rows(), &wanted, "the documents of the kind"); + assert_eq!(found.rows_examined(), 10); +} + +#[test] +fn a_grouped_count_over_a_kept_count_reads_no_rows_and_gives_the_groups_the_rows_give() { + let db = support::open(&support::folder("grouped-count-over-a-kept-count")); + support::run( + &db, + "CREATE TABLE plain (id INTEGER PRIMARY KEY, ctx TEXT NOT NULL, conn TEXT NOT NULL)", + ); + support::run( + &db, + "CREATE TABLE kept (id INTEGER PRIMARY KEY, ctx TEXT NOT NULL, conn TEXT NOT NULL, \ + UNIQUE (ctx, conn, id)) MAINTAIN COUNT (ctx), (ctx, conn)", + ); + // Row `n` of each is `(n, "c", "k")`: fifty rows for each pair. + let tx = db.transaction().expect("begin"); + for n in 1..=600_i64 { + for table in ["plain", "kept"] { + tx.execute( + &format!("INSERT INTO {table} (id, ctx, conn) VALUES ($id, $ctx, $conn)"), + ¶ms! { "id" => n, "ctx" => format!("c{}", n % 3), "conn" => format!("k{}", n % 4) }, + ) + .expect("insert a row"); + } + } + tx.commit().expect("commit"); + let group = |name: String, rows: i64| vec![Value::Text(name), Value::Int64(rows)]; + for (grouped, wanted) in [ + ( + "SELECT ctx, COUNT(*) FROM {} GROUP BY ctx", + (0..3) + .map(|n| group(format!("c{n}"), 200)) + .collect::>(), + ), + ( + "SELECT conn, COUNT(*) FROM {} WHERE ctx = 'c1' GROUP BY conn", + (0..4) + .map(|n| group(format!("k{n}"), 50)) + .collect::>(), + ), + ] { + let from_counts = support::run(&db, &grouped.replace("{}", "kept")); + let from_rows = support::run(&db, &grouped.replace("{}", "plain")); + // The same groups in the same order, the order of the grouping values. + assert_eq!(from_counts.rows(), wanted, "{grouped}"); + assert_eq!(from_rows.rows(), wanted, "{grouped}"); + // One kept record for each group and no row; without one, every row of the table. + assert_eq!(from_counts.rows_examined(), 0, "{grouped}"); + assert_eq!(from_rows.rows_examined(), 600, "{grouped}"); + } +} + +/// A store whose table `t` is `(id INTEGER PRIMARY KEY, TEXT)` with a row for each +/// number from 1 to `rows`, its text given by `text`. The rows are loaded with no limit, about +/// a mebibyte to a commit, and the store is then opened again under `limit`: of a limit, 9 MiB +/// are set aside by the open and the rest is the room a statement has. +fn loaded( + name: &str, + limit: usize, + column: &str, + rows: i64, + text: impl Fn(i64) -> String, +) -> Database { + let folder = support::folder(name); + let db = support::open(&folder); + support::run( + &db, + &format!("CREATE TABLE t (id INTEGER PRIMARY KEY, {column} TEXT)"), + ); + let insert = format!("INSERT INTO t (id, {column}) VALUES ($id, $text)"); + let mut n = 1; + while n <= rows { + let tx = db.transaction().expect("begin"); + let mut bytes = 0; + while n <= rows && bytes < MIB { + let text = text(n); + bytes += text.len(); + tx.execute(&insert, ¶ms! { "id" => n, "text" => text }) + .expect("insert a row"); + n += 1; + } + tx.commit().expect("commit"); + } + support::close(db); + let mut options = DatabaseOpenOptions::default(); + options.memory_limit = Some(limit); + support::open_with(&folder, options).expect("open under a limit") +} + +/// Exactly `len` bytes of text that begin with this number, in six digits. +fn padded(number: i64, len: usize) -> String { + format!("{number:06}-{}", "x".repeat(len - 7)) +} + +/// Asserts that the statement is refused, and by the memory limit. +fn assert_refused_by_the_memory_limit(db: &Database, sql: &str) { + let refusal = support::refusal(db, sql); + assert!( + matches!(refusal, Error::MemoryBudgetExceeded { .. }), + "{sql}\nwas refused by {refusal:?}, not by the memory limit" + ); +} + +#[test] +fn distinct_holds_one_entry_for_each_different_value() { + // 384 rows of 64 KiB are 24 MiB in each store, under a limit of 16 MiB. + const ROWS: i64 = 384; + const LEN: usize = 64 << 10; + let few = loaded("distinct-of-ten-values", 16 * MIB, "c", ROWS, |n| { + padded(n % 10, LEN) + }); + let found = support::rows(&few, "SELECT DISTINCT c FROM t"); + let mut heads: Vec = found + .iter() + .map(|row| match row.as_slice() { + [Value::Text(text)] if text.len() == LEN => text[..6].to_owned(), + other => panic!( + "a row of {} values, not one text of {LEN} bytes", + other.len() + ), + }) + .collect(); + heads.sort(); + let wanted: Vec = (0..10).map(|n| format!("{n:06}")).collect(); + assert_eq!(heads, wanted, "each of the ten values once"); + + // Every value different: one entry for each is the whole 24 MiB. + let all = loaded("distinct-of-every-value", 16 * MIB, "c", ROWS, |n| { + padded(n, LEN) + }); + assert_refused_by_the_memory_limit(&all, "SELECT DISTINCT c FROM t"); +} + +#[test] +fn bound_limit_and_offset_answer_as_the_literals_and_refuse_what_is_not_a_count() { + let db = support::open(&support::folder("bound-limit-and-offset")); + support::declare(&db); + support::insert_together(&db, 1..=100); + + let bound = "SELECT id FROM t ORDER BY id LIMIT $n OFFSET $m"; + let found = db + .execute(bound, ¶ms! { "n" => 5_i64, "m" => 10_i64 }) + .expect("LIMIT and OFFSET take bound whole numbers"); + let written = support::rows(&db, "SELECT id FROM t ORDER BY id LIMIT 5 OFFSET 10"); + assert_eq!(found.rows(), written); + assert_eq!(written, [11_i64, 12, 13, 14, 15].map(|n| [Value::Int64(n)])); + + let not_counts = [ + Value::Int64(-1), + Value::Float64(1.5), + Value::Text("5".to_owned()), + Value::Null, + ]; + for bad in not_counts { + for (n, m) in [ + (bad.clone(), Value::Int64(0)), + (Value::Int64(5), bad.clone()), + ] { + match db.execute(bound, ¶ms! { "n" => n, "m" => m }) { + Err(Error::PlanError(_)) => {} + other => panic!("with {bad:?} bound, not refused as a plan error: {other:?}"), + } + } + } +} + +/// Runs `check` on a thread of 2 MiB, less than the main thread of a program has, over a store +/// with the usual table `t`: a statement that nests must be refused by its depth and never +/// overflow the stack (CDB-250). `check` returns what went wrong. +fn on_a_small_stack(name: &'static str, check: fn(&Database) -> Vec) { + let outcome = std::thread::scope(|scope| { + std::thread::Builder::new() + .stack_size(2 * MIB) + .spawn_scoped(scope, move || { + let db = support::open(&support::folder(name)); + support::declare(&db); + support::insert(&db, 1..=3); + check(&db) + }) + .expect("start the thread") + .join() + }); + match outcome { + Ok(told) => assert!(told.is_empty(), "{told:#?}"), + Err(_) => panic!("a long statement panicked on a stack of 2 MiB"), + } +} + +fn is_refused_by_depth(result: contextdb::Result) -> bool { + match result { + Err(error) => error.to_string().contains("deeper than the limit of 64"), + Ok(_) => false, + } +} + +/// What went wrong, if anything, with 64 levels of an expression that nests by `open` and +/// `close` (read) and with 65 (refused by depth). +fn nested_to_the_limit(db: &Database, open: &str, close: &str) -> Vec { + let ran = |levels: usize| { + let sql = format!( + "SELECT id FROM t WHERE {}id{}", + open.repeat(levels), + close.repeat(levels) + ); + db.execute(&sql, ¶ms! {}) + }; + let mut told = Vec::new(); + if let Err(error) = ran(64) { + told.push(format!("64 levels of `{open}` were refused: {error:?}")); + } + if !is_refused_by_depth(ran(65)) { + told.push(format!("65 levels of `{open}` were not refused by depth")); + } + told +} + +#[test] +fn parentheses_and_not_nested_to_the_limit_are_read_and_one_past_it_is_refused_on_a_small_stack() { + on_a_small_stack("long-parentheses", |db| { + let mut told = nested_to_the_limit(db, "(", ")"); + told.extend(nested_to_the_limit(db, "NOT ", "")); + told + }); +} + +#[test] +fn a_function_call_nested_to_the_limit_is_read_and_one_past_it_is_refused_on_a_small_stack() { + on_a_small_stack("long-calls", |db| { + nested_to_the_limit(db, "COALESCE(", ", 1)") + }); +} + +#[test] +fn a_chain_of_operators_is_refused_by_depth_and_quoted_parentheses_and_ands_are_not_levels() { + on_a_small_stack("long-chains", |db| { + let ran = |sql: &str| db.execute(sql, ¶ms! {}); + let mut told = Vec::new(); + // A chain of operators nests in the tree it builds, not in the text. + let chain = format!("SELECT id FROM t WHERE id = 1{}", " + 1".repeat(200)); + if !is_refused_by_depth(ran(&chain)) { + told.push("a chain of 200 operators was not refused by depth".to_owned()); + } + // Parentheses in quoted text or a comment are not levels; a long run of ANDs is not + // a chain. + let quoted = format!( + "SELECT '{}' /* {} */ FROM t", + "(".repeat(200), + "(".repeat(200) + ); + let run = format!( + "SELECT id FROM t WHERE id = 1{}", + " AND id = 1".repeat(2000) + ); + for sql in [quoted, run] { + if let Err(error) = ran(&sql) { + told.push(format!("{}... was refused: {error:?}", &sql[..30])); + } + } + let ors = format!("SELECT id FROM t WHERE {}id = 3", "id = 9 OR ".repeat(1023)); + if !ran(&ors).is_ok_and(|result| result.rows() == [[Value::Int64(3)]]) { + told.push("a run of 1024 ORs did not give its row".to_owned()); + } + // SELECTs nested in one another count the same way, the outermost one as the first level. + let selects = |levels: usize| { + (1..levels).fold("SELECT id FROM t".to_owned(), |inner, _| { + format!("SELECT id FROM t WHERE id IN ({inner})") + }) + }; + if let Err(error) = ran(&selects(64)) { + told.push(format!("64 nested SELECTs were refused: {error:?}")); + } + if !is_refused_by_depth(ran(&selects(65))) { + told.push("65 nested SELECTs were not refused by depth".to_owned()); + } + told + }); +} + +#[test] +fn union_arms_and_with_names_in_a_long_statement_are_read_or_refused_on_a_small_stack() { + on_a_small_stack("long-unions-and-names", |db| { + let ran = |sql: &str| db.execute(sql, ¶ms! {}); + let mut told = Vec::new(); + // Arms of a UNION are one list read in turn, whatever their number. + let arms = vec!["SELECT id FROM t"; 3000].join(" UNION ALL "); + match ran(&arms) { + Ok(result) if result.rows().len() == 9000 => {} + other => told.push(format!( + "3000 UNION ALL arms of 3 rows gave {:?}", + other.map(|result| result.rows().len()) + )), + } + // Names of a WITH that read the name before them nest: a few are read, and a chain + // far past the limit is refused by depth. + let with = |names: usize| { + let mut text = String::from("WITH n0 AS (SELECT id FROM t)"); + for n in 1..names { + text.push_str(&format!(", n{n} AS (SELECT id FROM n{})", n - 1)); + } + format!("{text} SELECT id FROM n{}", names - 1) + }; + if let Err(error) = ran(&with(16)) { + told.push(format!("a chain of 16 WITH names was refused: {error:?}")); + } + if !is_refused_by_depth(ran(&with(300))) { + told.push("a chain of 300 WITH names was not refused by depth".to_owned()); + } + told + }); +} diff --git a/v2/contextdb/tests/readers.rs b/v2/contextdb/tests/readers.rs index 36bd862d6..36af72053 100644 --- a/v2/contextdb/tests/readers.rs +++ b/v2/contextdb/tests/readers.rs @@ -63,9 +63,7 @@ fn a_statement_reads_one_moment_while_commits_land_under_it() { let folder = support::folder("statement-one-moment"); let db = support::open(&folder); support::declare(&db); - let tx = db.transaction().expect("begin"); - support::insert(&tx, 1..=ROWS); - tx.commit().expect("commit"); + support::insert_together(&db, 1..=ROWS); let mut reader = scanner_stopped_inside_its_scan(test, &folder, ROWS); @@ -93,9 +91,7 @@ fn a_reader_keeps_answering_when_the_writer_is_killed_and_follows_the_restarted_ let folder = support::folder("reader-outlives-writer"); let db = support::open(&folder); support::declare(&db); - let tx = db.transaction().expect("begin"); - support::insert(&tx, 1..=ROWS); - tx.commit().expect("commit"); + support::insert_together(&db, 1..=ROWS); support::close(db); // A writer in another process, and this process as a reader of its store. @@ -180,9 +176,7 @@ fn a_killed_reader_leaves_one_file_that_the_next_open_clears() { let readers = folder.join("readers"); let db = support::open(&folder); support::declare(&db); - let tx = db.transaction().expect("begin"); - support::insert(&tx, 1..=ROWS); - tx.commit().expect("commit"); + support::insert_together(&db, 1..=ROWS); support::close(db); // Two readers, each stopped inside a statement: each holds one file. @@ -402,7 +396,12 @@ fn a_reader_sees_one_grouping_whole_while_the_writer_builds_and_switches() { return searcher(&role); } let test = "a_reader_sees_one_grouping_whole_while_the_writer_builds_and_switches"; - let (folder, db) = support::built("reader-beside-build", GROUPED, "AUTO_INDEX_AT 1000", 2000); + let (folder, db) = support::built( + "reader-beside-build", + GROUPED, + "INDEXING_THRESHOLD 1000", + 2000, + ); let line = |db: &contextdb::Database| told(&support::answer(db, &indexed_ten(), &asked())); let first = line(&db); @@ -457,11 +456,7 @@ fn a_reader_sees_one_grouping_whole_while_the_writer_builds_and_switches() { /// search it announces `reading` and waits for a line; `pause_at` 0 never stops. Then it /// announces the answer's line and `reads `, searches once more and announces that line. fn searcher(role: &support::Role) { - let (door, searching, reads) = support::pausing_at_read(role.number("pause_at")); - let mut options = ReadSessionOptions::default(); - options.storage = Some(door); - let reader = - ReadSession::open_with_options(&role.folder, options).expect("open the store for reading"); + let (reader, searching, reads) = support::reader_pausing(role); searching.store(true, Ordering::SeqCst); let result = support::search(&reader, &indexed_ten(), &asked()) .expect("a reader is not refused because a build ran"); @@ -486,7 +481,7 @@ fn a_new_process_searches_a_built_grouping_at_once() { return; } let test = "a_new_process_searches_a_built_grouping_at_once"; - let (folder, db) = support::built("first-search", GROUPED, "AUTO_INDEX_AT 1000", 2000); + let (folder, db) = support::built("first-search", GROUPED, "INDEXING_THRESHOLD 1000", 2000); let wanted = told(&support::answer(&db, &indexed_ten(), &asked())); support::close(db); // The first search of a fresh process does the work of its second and of the process diff --git a/v2/contextdb/tests/row_guards.rs b/v2/contextdb/tests/row_guards.rs index af65df391..ce15bf188 100644 --- a/v2/contextdb/tests/row_guards.rs +++ b/v2/contextdb/tests/row_guards.rs @@ -10,6 +10,14 @@ use contextdb::{ContextId, Database, Error, Transaction, Uuid, Value, params}; const LEASES: &str = "CREATE TABLE leases (id INTEGER PRIMARY KEY, generation UUID UNIQUE, \ owner TEXT, epoch INTEGER NOT NULL)"; +/// Leases 1 (owner `a`, epoch 2) and 2 (no owner, epoch 5), as two tests expect them. +fn leases_as_left() -> [Vec; 2] { + [ + vec![Value::Int64(1), support::text("a"), Value::Int64(2)], + vec![Value::Int64(2), Value::Null, Value::Int64(5)], + ] +} + const ALL_LEASES: &str = "SELECT id, owner, epoch FROM leases ORDER BY id"; /// A store with `leases` 1 (owner `a`, epoch 1) and 2 (no owner, epoch 5), each with a @@ -240,13 +248,7 @@ fn a_guard_taken_after_a_declaration_refuses_the_commit_when_its_value_was_chang support::refusal(&db, "SELECT COUNT(*) FROM audits"), Error::TableNotFound(table) if table == "audits" )); - assert_eq!( - support::rows(&db, ALL_LEASES), - [ - vec![Value::Int64(1), support::text("a"), Value::Int64(2)], - vec![Value::Int64(2), Value::Null, Value::Int64(5)], - ] - ); + assert_eq!(support::rows(&db, ALL_LEASES), leases_as_left()); // A guard names places in the row as the transaction shows it, and holds the same values // whatever column the transaction dropped before or after it. Each case has a table of @@ -417,11 +419,5 @@ fn a_guard_is_checked_again_at_commit_though_the_transaction_wrote_nothing() { .expect("commit over a guarded value that is held again"); // Only the other commits wrote. - assert_eq!( - support::rows(&db, ALL_LEASES), - [ - vec![Value::Int64(1), support::text("a"), Value::Int64(2)], - vec![Value::Int64(2), Value::Null, Value::Int64(5)], - ] - ); + assert_eq!(support::rows(&db, ALL_LEASES), leases_as_left()); } diff --git a/v2/contextdb/tests/sql/aggregates.sql b/v2/contextdb/tests/sql/aggregates.sql index f7a9cdc64..cd8b9322d 100644 --- a/v2/contextdb/tests/sql/aggregates.sql +++ b/v2/contextdb/tests/sql/aggregates.sql @@ -8,34 +8,34 @@ VALUES (1, 7, 0.5, 'north'), (2, 6, 1.5, 'south'), (3, NULL, NULL, NULL), (4, 9, # COUNT(*) counts rows and COUNT of a column counts its values that are not NULL. SELECT COUNT(*) FROM sales; ---- -COUNT +count 4 SELECT COUNT(qty) FROM sales; ---- -COUNT +count 3 SELECT COUNT(*) FROM sales WHERE qty > 6; ---- -COUNT +count 2 SELECT COUNT(*) FROM sales WHERE id > 100; ---- -COUNT +count 0 # SUM skips NULL, adds whole numbers as whole numbers and REAL as REAL, and is named after the # function unless the statement gives it a name. SELECT SUM(qty) FROM sales; ---- -SUM +sum 22 SELECT SUM(price) FROM sales; ---- -SUM +sum 4.0 SELECT SUM(qty) AS total FROM sales; @@ -46,7 +46,7 @@ total # Over no rows SUM is NULL, not zero. SELECT SUM(qty) FROM sales WHERE id > 100; ---- -SUM +sum NULL # A column that is not a number cannot be added. @@ -64,25 +64,36 @@ error: PlanError # MIN and MAX skip NULL, and over no rows each is NULL. SELECT MIN(qty) FROM sales; ---- -MIN +min 6 SELECT MAX(qty) FROM sales; ---- -MAX +max 9 SELECT MIN(price), MAX(price) FROM sales; ---- -MIN | MAX +min | max 0.5 | 2.0 SELECT MIN(region), MAX(region) FROM sales; ---- -MIN | MAX +min | max east | south SELECT MIN(qty), MAX(qty) FROM sales WHERE id > 100; ---- -MIN | MAX +min | max NULL | NULL + +# MIN and MAX of a VECTOR are refused, as pgvector has neither. +CREATE TABLE vecs (id INTEGER PRIMARY KEY, v VECTOR(2)); +INSERT INTO vecs (id, v) VALUES (1, [1.0, 0.0]), (2, [0.0, 1.0]); +SELECT MIN(v) FROM vecs; +---- +error: PlanError + +SELECT MAX(v) FROM vecs; +---- +error: PlanError diff --git a/v2/contextdb/tests/sql/alter_table.sql b/v2/contextdb/tests/sql/alter_table.sql index 3543d13ef..91de6ab93 100644 --- a/v2/contextdb/tests/sql/alter_table.sql +++ b/v2/contextdb/tests/sql/alter_table.sql @@ -261,35 +261,35 @@ error: ColumnNotFound # The thresholds of the search index are changed online, and the next search and upkeep cycle # read them: the declaration says what was written and what is in force, and DEFAULT takes the # declaration away. -ALTER TABLE docs ALTER COLUMN v SET AUTO_INDEX_AT 5000; -ALTER TABLE docs ALTER COLUMN v SET CONSOLIDATION (CHANGE_PERCENT = 30, TOMBSTONE_PERCENT = 5); +ALTER TABLE docs ALTER COLUMN v SET INDEXING_THRESHOLD 5000; +ALTER TABLE docs ALTER COLUMN v SET COMPACTION (CHANGE_PERCENT = 30, TOMBSTONE_PERCENT = 5); SHOW VECTOR_INDEXES; ---- -table | column | dimension | quantization | vector_count | bytes | partition_key_columns | max_partitions | live_partitions | search_mode | declared_auto_index_at | effective_auto_index_at | declared_consolidation_mode | declared_consolidation_change_percent | declared_consolidation_tombstone_percent | effective_consolidation_mode | effective_consolidation_change_percent | effective_consolidation_tombstone_percent | pending_inserts | tombstones | durable_vector_bytes | durable_index_bytes | indexed_available | maintenance_state | maintenance_vectors_total | maintenance_vectors_done | maintenance_vectors_remaining | unavailable_partitions | stalled_partitions | broad_route | recovery_action +table | column | dimension | quantization | vector_count | bytes | partition_key_columns | max_partitions | live_partitions | search_mode | declared_indexing_threshold | effective_indexing_threshold | declared_compaction_mode | declared_compaction_change_percent | declared_compaction_tombstone_percent | effective_compaction_mode | effective_compaction_change_percent | effective_compaction_tombstone_percent | pending_tuples | tombstones | durable_vector_bytes | durable_index_bytes | indexed_available | maintenance_state | maintenance_vectors_total | maintenance_vectors_done | maintenance_vectors_remaining | unavailable_partitions | stalled_partitions | broad_route | recovery_action docs | loose | * | * | * | * | * | * | * | * | NULL | 100000 | NULL | NULL | NULL | PERCENT | 20 | 10 | * | * | * | * | * | * | * | * | * | * | * | * | * docs | v | * | * | * | * | * | * | * | * | 5000 | 5000 | PERCENT | 30 | 5 | PERCENT | 30 | 5 | * | * | * | * | * | * | * | * | * | * | * | * | * -ALTER TABLE docs ALTER COLUMN v SET AUTO_INDEX_AT DEFAULT; -ALTER TABLE docs ALTER COLUMN v SET CONSOLIDATION NONE; +ALTER TABLE docs ALTER COLUMN v SET INDEXING_THRESHOLD DEFAULT; +ALTER TABLE docs ALTER COLUMN v SET COMPACTION NONE; SHOW VECTOR_INDEXES; ---- -table | column | dimension | quantization | vector_count | bytes | partition_key_columns | max_partitions | live_partitions | search_mode | declared_auto_index_at | effective_auto_index_at | declared_consolidation_mode | declared_consolidation_change_percent | declared_consolidation_tombstone_percent | effective_consolidation_mode | effective_consolidation_change_percent | effective_consolidation_tombstone_percent | pending_inserts | tombstones | durable_vector_bytes | durable_index_bytes | indexed_available | maintenance_state | maintenance_vectors_total | maintenance_vectors_done | maintenance_vectors_remaining | unavailable_partitions | stalled_partitions | broad_route | recovery_action +table | column | dimension | quantization | vector_count | bytes | partition_key_columns | max_partitions | live_partitions | search_mode | declared_indexing_threshold | effective_indexing_threshold | declared_compaction_mode | declared_compaction_change_percent | declared_compaction_tombstone_percent | effective_compaction_mode | effective_compaction_change_percent | effective_compaction_tombstone_percent | pending_tuples | tombstones | durable_vector_bytes | durable_index_bytes | indexed_available | maintenance_state | maintenance_vectors_total | maintenance_vectors_done | maintenance_vectors_remaining | unavailable_partitions | stalled_partitions | broad_route | recovery_action docs | loose | * | * | * | * | * | * | * | * | NULL | 100000 | NULL | NULL | NULL | PERCENT | 20 | 10 | * | * | * | * | * | * | * | * | * | * | * | * | * docs | v | * | * | * | * | * | * | * | * | NULL | 100000 | NONE | NULL | NULL | NONE | NULL | NULL | * | * | * | * | * | * | * | * | * | * | * | * | * -ALTER TABLE docs ALTER COLUMN v SET CONSOLIDATION DEFAULT; +ALTER TABLE docs ALTER COLUMN v SET COMPACTION DEFAULT; SHOW VECTOR_INDEXES; ---- -table | column | dimension | quantization | vector_count | bytes | partition_key_columns | max_partitions | live_partitions | search_mode | declared_auto_index_at | effective_auto_index_at | declared_consolidation_mode | declared_consolidation_change_percent | declared_consolidation_tombstone_percent | effective_consolidation_mode | effective_consolidation_change_percent | effective_consolidation_tombstone_percent | pending_inserts | tombstones | durable_vector_bytes | durable_index_bytes | indexed_available | maintenance_state | maintenance_vectors_total | maintenance_vectors_done | maintenance_vectors_remaining | unavailable_partitions | stalled_partitions | broad_route | recovery_action +table | column | dimension | quantization | vector_count | bytes | partition_key_columns | max_partitions | live_partitions | search_mode | declared_indexing_threshold | effective_indexing_threshold | declared_compaction_mode | declared_compaction_change_percent | declared_compaction_tombstone_percent | effective_compaction_mode | effective_compaction_change_percent | effective_compaction_tombstone_percent | pending_tuples | tombstones | durable_vector_bytes | durable_index_bytes | indexed_available | maintenance_state | maintenance_vectors_total | maintenance_vectors_done | maintenance_vectors_remaining | unavailable_partitions | stalled_partitions | broad_route | recovery_action docs | loose | * | * | * | * | * | * | * | * | NULL | 100000 | NULL | NULL | NULL | PERCENT | 20 | 10 | * | * | * | * | * | * | * | * | * | * | * | * | * docs | v | * | * | * | * | * | * | * | * | NULL | 100000 | NULL | NULL | NULL | PERCENT | 20 | 10 | * | * | * | * | * | * | * | * | * | * | * | * | * # A value CREATE TABLE refuses is refused here, and the declaration stays as it was. -ALTER TABLE docs ALTER COLUMN v SET AUTO_INDEX_AT 0; +ALTER TABLE docs ALTER COLUMN v SET INDEXING_THRESHOLD 0; ---- error: InvalidVectorPolicyDeclaration -ALTER TABLE docs ALTER COLUMN v SET CONSOLIDATION (CHANGE_PERCENT = 101); +ALTER TABLE docs ALTER COLUMN v SET COMPACTION (CHANGE_PERCENT = 101); ---- error: InvalidVectorPolicyDeclaration diff --git a/v2/contextdb/tests/sql/compare_types.sql b/v2/contextdb/tests/sql/compare_types.sql index 149437660..a58817561 100644 --- a/v2/contextdb/tests/sql/compare_types.sql +++ b/v2/contextdb/tests/sql/compare_types.sql @@ -156,3 +156,38 @@ SELECT id, n, label FROM things ORDER BY id; id | n | label 1 | 9 | seven 3 | NULL | NULL + +# The value a SELECT gives has its column's type: a number is not compared with text there. +SELECT id FROM things WHERE n IN (SELECT label FROM things); +---- +error: PlanError + +# A whole number and a REAL are equal only when they are the same number, through an index too. +CREATE TABLE wide (id INTEGER PRIMARY KEY, x REAL); +CREATE INDEX wide_x ON wide (x); +INSERT INTO wide (id, x) VALUES (1, 9007199254740992.0); +---- +rows affected: 1 + +SELECT id FROM wide WHERE x = 9007199254740993; +---- +id + +SELECT id FROM wide WHERE x >= 9007199254740993; +---- +id + +SELECT id FROM wide WHERE x = 9007199254740992; +---- +id +1 + +# A whole number a REAL cannot hold is above the REAL that is nearest it. +INSERT INTO wide (id, x) VALUES (2, 9223372036854775808.0); +---- +rows affected: 1 + +SELECT id FROM wide WHERE x > 9223372036854775807; +---- +id +2 diff --git a/v2/contextdb/tests/sql/create_table.sql b/v2/contextdb/tests/sql/create_table.sql deleted file mode 100644 index c0a620922..000000000 --- a/v2/contextdb/tests/sql/create_table.sql +++ /dev/null @@ -1,60 +0,0 @@ -# CREATE TABLE never redeclares a table, IF NOT EXISTS makes a second declaration do nothing, and -# the indexes behind a key and a unique rule have names the engine keeps for itself. - -CREATE TABLE notes (id INTEGER PRIMARY KEY, title TEXT UNIQUE, body TEXT); -INSERT INTO notes (id, title, body) VALUES (1, 'kept', 'first'); - -# A taken name is refused, and the table and its rows stay as they were. -CREATE TABLE notes (id UUID PRIMARY KEY, other REAL); ----- -error: SchemaInvalid - -SELECT id, title, body FROM notes ORDER BY id; ----- -id | title | body -1 | kept | first - -# With IF NOT EXISTS a taken name is left alone, whatever shape the second declaration has. -CREATE TABLE IF NOT EXISTS notes (id UUID PRIMARY KEY, other REAL); ----- -rows affected: 0 - -SELECT other FROM notes; ----- -error: ColumnNotFound - -INSERT INTO notes (id, title, body) VALUES (2, 'second', 'more'); -SELECT id, title, body FROM notes ORDER BY id; ----- -id | title | body -1 | kept | first -2 | second | more - -# With IF NOT EXISTS a free name is declared. -CREATE TABLE IF NOT EXISTS tags (id INTEGER PRIMARY KEY, word TEXT); -INSERT INTO tags (id, word) VALUES (1, 'a'); -SELECT id, word FROM tags ORDER BY id; ----- -id | word -1 | a - -# The key's index is __pk_ and a unique column's is __unique_. A user's index -# may not take either prefix, and may sit beside them. -CREATE INDEX __pk_id ON notes (id); ----- -error: ReservedIndexName - -CREATE INDEX __unique_title ON notes (title); ----- -error: ReservedIndexName - -CREATE INDEX notes_by_body ON notes (body); -SELECT id FROM notes WHERE id = 2; ----- -id -2 - -SELECT id FROM notes WHERE title = 'kept'; ----- -id -1 diff --git a/v2/contextdb/tests/sql/cte.sql b/v2/contextdb/tests/sql/cte.sql new file mode 100644 index 000000000..e5695ac4f --- /dev/null +++ b/v2/contextdb/tests/sql/cte.sql @@ -0,0 +1,44 @@ +# WITH: a named SELECT that the statement after it reads as a table. + +CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT, status TEXT); +INSERT INTO items (id, name, status) +VALUES (1, 'sensor-a', 'active'), (2, 'sensor-b', 'retired'), (3, 'meter', 'active'); + +WITH active AS (SELECT id, name FROM items WHERE status = 'active') +SELECT * FROM active WHERE name LIKE 'sensor%'; +---- +id | name +1 | sensor-a + +# Several are separated by commas, a later one may read an earlier one, and one may be read +# more than once. +WITH active AS (SELECT id, name FROM items WHERE status = 'active'), + meters AS (SELECT id FROM active WHERE name = 'meter') +SELECT a.name FROM active a JOIN meters m ON a.id = m.id; +---- +name +meter + +# Its columns are the names its SELECT gives them. +WITH n AS (SELECT COUNT(*) AS total FROM items) +SELECT total FROM n; +---- +total +3 + +# A name that is neither a table nor a WITH name of the statement is a missing table. +WITH active AS (SELECT id FROM items) +SELECT id FROM retired; +---- +error: TableNotFound + +# A WITH that reads itself is refused by name. +WITH RECURSIVE up AS (SELECT id FROM items) +SELECT id FROM up; +---- +error: RecursiveCteNotSupported + +# A name that two columns of a WITH answer to is refused where it is read. +WITH w AS (SELECT id AS x, name AS x FROM items) SELECT x FROM w; +---- +error: PlanError diff --git a/v2/contextdb/tests/sql/dag.sql b/v2/contextdb/tests/sql/dag.sql index 87a354c22..2822c0a7b 100644 --- a/v2/contextdb/tests/sql/dag.sql +++ b/v2/contextdb/tests/sql/dag.sql @@ -160,3 +160,20 @@ SELECT id, source_id, target_id FROM one_edge; ---- id | source_id | target_id 1 | 00000000-0000-0000-0000-000000000002 | 00000000-0000-0000-0000-000000000001 + +# A table of edges that is also IMMUTABLE takes an edge, and refuses the edge that would close a cycle. +CREATE TABLE fixed_edges ( + id INTEGER PRIMARY KEY, + source_id UUID NOT NULL, + target_id UUID NOT NULL, + edge_type TEXT NOT NULL +) DAG('X') IMMUTABLE; +INSERT INTO fixed_edges (id, source_id, target_id, edge_type) +VALUES (1, '00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000002', 'X'); +---- +rows affected: 1 + +INSERT INTO fixed_edges (id, source_id, target_id, edge_type) +VALUES (2, '00000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000001', 'X'); +---- +error: CycleDetected diff --git a/v2/contextdb/tests/sql/declarations.sql b/v2/contextdb/tests/sql/declarations.sql index d67f2b702..48243ec77 100644 --- a/v2/contextdb/tests/sql/declarations.sql +++ b/v2/contextdb/tests/sql/declarations.sql @@ -51,6 +51,22 @@ id | title 2 | b 3 | a +# The indexes behind a key and a UNIQUE rule are __pk_ and __unique_; a user's +# index may not take either prefix, and may sit beside them. +CREATE INDEX __pk_id ON notes (id); +---- +error: ReservedIndexName + +CREATE INDEX __unique_title ON notes (title); +---- +error: ReservedIndexName + +CREATE INDEX notes_by_body ON notes (body); +SELECT id FROM notes WHERE body = 'x'; +---- +id +2 + # A name written without quotes is its lower-case letters, and a name in quotes is the letters # as written: `Items`, `ITEMS` and `items` are one table, and "Items" is another. CREATE TABLE Items (Id INTEGER PRIMARY KEY, Name TEXT); @@ -209,76 +225,15 @@ CREATE TABLE p_push (id INTEGER PRIMARY KEY, t TEXT NOT NULL, v VECTOR(2) PARTIT CREATE TABLE p_pull (id INTEGER PRIMARY KEY, t TEXT NOT NULL, v VECTOR(2) PARTITION_KEY (t)) SYNC PULL ONLY; CREATE TABLE p_two_way (id INTEGER PRIMARY KEY, t TEXT NOT NULL, v VECTOR(2) PARTITION_KEY (t)) SYNC TWO WAY; -# A table that keeps only current versions, sends its rows out and keeps the first write would -# hand another machine a newest value as the first: refused. KEEP LATEST or SYNC OFF is the way -# out, as above. -CREATE TABLE refused (id TEXT PRIMARY KEY, state TEXT NOT NULL) HISTORY CURRENT ONLY; ----- -error: SchemaInvalid - -CREATE TABLE refused (id TEXT PRIMARY KEY, state TEXT NOT NULL) HISTORY CURRENT ONLY SYNC PUSH ONLY SYNC CONFLICT KEEP FIRST; ----- -error: SchemaInvalid - -# An IMMUTABLE table has no row to expire and no older version to drop. -CREATE TABLE refused (id INTEGER PRIMARY KEY) IMMUTABLE RETAIN 7 DAYS; ----- -error: SchemaInvalid - -CREATE TABLE refused (id INTEGER PRIMARY KEY) IMMUTABLE HISTORY CURRENT ONLY SYNC OFF; ----- -error: SchemaInvalid - -# SYNC SAFE waits for delivery, so it needs a direction that delivers. Plain RETAIN takes any. -CREATE TABLE refused (id INTEGER PRIMARY KEY) RETAIN 7 DAYS SYNC SAFE SYNC OFF; ----- -error: SchemaInvalid - -CREATE TABLE refused (id INTEGER PRIMARY KEY) RETAIN 7 DAYS SYNC SAFE SYNC PULL ONLY; +# A STATE MACHINE over a table that is IMMUTABLE could never move. +CREATE TABLE refused (id INTEGER PRIMARY KEY, status TEXT NOT NULL) STATE MACHINE (status: a -> [b]) IMMUTABLE; ---- error: SchemaInvalid +# Plain RETAIN takes any direction. CREATE TABLE retain_local (id INTEGER PRIMARY KEY) RETAIN 7 DAYS SYNC OFF; CREATE TABLE retain_pull (id INTEGER PRIMARY KEY) RETAIN 7 DAYS SYNC PULL ONLY; -# RETAIN names no direction: one written inside it is a syntax error. -CREATE TABLE refused (id INTEGER PRIMARY KEY) RETAIN 24 HOURS SYNC SAFE PUSH ONLY; ----- -error: ParseError - -# A reference names columns that a key or a UNIQUE rule of the parent covers. -CREATE TABLE refused (id INTEGER PRIMARY KEY, plan_name TEXT REFERENCES plans(name)); ----- -error: SchemaInvalid - -CREATE TABLE refused ( - id INTEGER PRIMARY KEY, - context_id UUID, - name TEXT, - FOREIGN KEY (context_id, name) REFERENCES projects(context_id, name) -); ----- -error: SchemaInvalid - -# A kept count needs an index that leads with its list, and is not kept where a key already -# says the count is at most one. -CREATE TABLE refused (id INTEGER PRIMARY KEY, kind TEXT) MAINTAIN COUNT (kind); ----- -error: SchemaInvalid - -CREATE TABLE refused (id INTEGER PRIMARY KEY, kind TEXT) MAINTAIN COUNT (id); ----- -error: SchemaInvalid - -# DAG is for a table of edges: source_id, target_id and edge_type. -CREATE TABLE refused (id INTEGER PRIMARY KEY, source_id UUID NOT NULL, target_id UUID NOT NULL) DAG('DEPENDS_ON'); ----- -error: SchemaInvalid - -SELECT id FROM refused; ----- -error: TableNotFound - # A key, a UNIQUE rule and an index name at most 32 columns. CREATE TABLE refused (c01 INTEGER, c02 INTEGER, c03 INTEGER, c04 INTEGER, c05 INTEGER, c06 INTEGER, c07 INTEGER, c08 INTEGER, c09 INTEGER, c10 INTEGER, c11 INTEGER, c12 INTEGER, c13 INTEGER, c14 INTEGER, c15 INTEGER, c16 INTEGER, c17 INTEGER, c18 INTEGER, c19 INTEGER, c20 INTEGER, c21 INTEGER, c22 INTEGER, c23 INTEGER, c24 INTEGER, c25 INTEGER, c26 INTEGER, c27 INTEGER, c28 INTEGER, c29 INTEGER, c30 INTEGER, c31 INTEGER, c32 INTEGER, c33 INTEGER, PRIMARY KEY (c01, c02, c03, c04, c05, c06, c07, c08, c09, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20, c21, c22, c23, c24, c25, c26, c27, c28, c29, c30, c31, c32, c33)); ---- @@ -300,24 +255,6 @@ error: SchemaInvalid CREATE INDEX wide_32 ON wide (c01, c02, c03, c04, c05, c06, c07, c08, c09, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20, c21, c22, c23, c24, c25, c26, c27, c28, c29, c30, c31, c32); CREATE TABLE wide_key (c01 INTEGER, c02 INTEGER, c03 INTEGER, c04 INTEGER, c05 INTEGER, c06 INTEGER, c07 INTEGER, c08 INTEGER, c09 INTEGER, c10 INTEGER, c11 INTEGER, c12 INTEGER, c13 INTEGER, c14 INTEGER, c15 INTEGER, c16 INTEGER, c17 INTEGER, c18 INTEGER, c19 INTEGER, c20 INTEGER, c21 INTEGER, c22 INTEGER, c23 INTEGER, c24 INTEGER, c25 INTEGER, c26 INTEGER, c27 INTEGER, c28 INTEGER, c29 INTEGER, c30 INTEGER, c31 INTEGER, c32 INTEGER, c33 INTEGER, PRIMARY KEY (c01, c02, c03, c04, c05, c06, c07, c08, c09, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20, c21, c22, c23, c24, c25, c26, c27, c28, c29, c30, c31, c32)); -# Clauses of a later version are still refused by their names, and stored procedures and -# functions by their own kind. -CREATE TABLE refused (id INTEGER PRIMARY KEY, until TIMESTAMP EXPIRES); ----- -error: PlanError - -CREATE PROCEDURE tidy () AS 'DELETE FROM notes'; ----- -error: StoredProcNotSupported - -CREATE FUNCTION one () RETURNS INTEGER AS 'SELECT 1'; ----- -error: StoredProcNotSupported - -SELECT id FROM refused; ----- -error: TableNotFound - # An index names columns the table has and can index: a JSON column is not indexable, and a REAL # may be indexed but is no key and under no UNIQUE rule. CREATE TABLE people (id INTEGER PRIMARY KEY, score REAL, born INTEGER, doc JSON); @@ -357,3 +294,12 @@ SELECT id FROM filled; ---- id 1 + +# A JSON-path index may name a path of two keys. +CREATE TABLE chained (id INTEGER PRIMARY KEY, doc JSON); +CREATE INDEX chained_by_path ON chained ((doc -> 'k' -> 'j')); +INSERT INTO chained (id, doc) VALUES (1, '{"k": {"j": 1}}'); +SELECT id FROM chained; +---- +id +1 diff --git a/v2/contextdb/tests/sql/distinct.sql b/v2/contextdb/tests/sql/distinct.sql new file mode 100644 index 000000000..8fc8b5da5 --- /dev/null +++ b/v2/contextdb/tests/sql/distinct.sql @@ -0,0 +1,101 @@ +# DISTINCT gives each row of the answer once. + +CREATE TABLE hits (id INTEGER PRIMARY KEY, ctx TEXT, conn TEXT); +INSERT INTO hits (id, ctx, conn) +VALUES (1, 'a', 'x'), (2, 'a', 'x'), (3, 'a', 'y'), (4, 'b', 'x'), (5, NULL, NULL), (6, NULL, NULL); + +SELECT DISTINCT ctx FROM hits ORDER BY ctx; +---- +ctx +a +b +NULL + +# Rows are the same when every column is, and two NULLs are the same here. +SELECT DISTINCT ctx, conn FROM hits ORDER BY ctx, conn; +---- +ctx | conn +a | x +a | y +b | x +NULL | NULL + +# LIMIT counts the rows that are left. +SELECT DISTINCT conn FROM hits ORDER BY conn LIMIT 2; +---- +conn +x +y + +# A vector column, and a number column with a NULL: each different value once, NULL one value. +CREATE TABLE marks (id INTEGER PRIMARY KEY, v VECTOR(3), x INTEGER); +INSERT INTO marks (id, v, x) +VALUES (0, [1.0, 0.0, 0.0], 1), (1, [0.0, 1.0, 0.0], 2), (2, NULL, NULL), + (3, [1.0, 0.0, 0.0], 1), (4, [0.0, 1.0, 0.0], 2), (5, NULL, NULL); + +SELECT DISTINCT v FROM marks; +---- +v +* +* +* + +SELECT DISTINCT x FROM marks ORDER BY x; +---- +x +1 +2 +NULL + +# Vectors are values: equal ones group and partition together, and sort by their numbers. +SELECT COUNT(*) AS n FROM marks GROUP BY v ORDER BY n; +---- +n +2 +2 +2 + +SELECT id, ROW_NUMBER() OVER (PARTITION BY v ORDER BY id) AS rn FROM marks ORDER BY id; +---- +id | rn +0 | 1 +1 | 1 +2 | 1 +3 | 2 +4 | 2 +5 | 2 + +SELECT id FROM marks WHERE v IS NOT NULL ORDER BY v, id; +---- +id +1 +4 +0 +3 + +# DISTINCT keeps one row for each value shown, so a row it drops cannot be put in order. +SELECT DISTINCT x FROM marks ORDER BY id DESC; +---- +error: PlanError + +# Equal vectors are equal: = matches every row that holds them. +SELECT id FROM marks WHERE v = [1.0, 0.0, 0.0] ORDER BY id; +---- +id +0 +3 + +# A name the select list gives under a qualifier is that item: it may be sorted by. +SELECT DISTINCT marks.x FROM marks ORDER BY x; +---- +x +1 +2 +NULL + +# The same SELECT written twice is one expression: it is in the select list, so it may be sorted by. +# (Postgres matches the two by structure; not shown in its pages, believed from its source.) +SELECT DISTINCT (SELECT 1) AS k FROM marks ORDER BY (SELECT 1); +---- +k +1 diff --git a/v2/contextdb/tests/sql/explain.sql b/v2/contextdb/tests/sql/explain.sql new file mode 100644 index 000000000..a3be15e18 --- /dev/null +++ b/v2/contextdb/tests/sql/explain.sql @@ -0,0 +1,156 @@ +# EXPLAIN : the route it would take, a line of the TEXT column QUERY PLAN for each +# line of the explanation. The statement is planned and not run. + +CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT NOT NULL, tag INTEGER NOT NULL); +CREATE INDEX t_tag ON t (tag); +INSERT INTO t (id, name, tag) VALUES (1, 'one', 1), (2, 'two', 2), (7, 'seven', 3); + +# A lookup by the key goes through the index behind the key. +EXPLAIN SELECT name FROM t WHERE id = 7; +---- +QUERY PLAN +IndexScan { index: __pk_id } + predicates_pushed: [id] + indexes_considered: [t_tag: first column not in WHERE] + +# A range of an index is read through it, and the key's index says why it lost. +EXPLAIN SELECT id FROM t WHERE tag = 3; +---- +QUERY PLAN +IndexScan { index: t_tag } + predicates_pushed: [tag] + indexes_considered: [__pk_id: first column not in WHERE] + +# Each reason an index is passed over is said, in the documented words. +CREATE TABLE e (id INTEGER PRIMARY KEY, a INTEGER, b INTEGER, s TEXT); +CREATE INDEX e_ab ON e (a, b); +CREATE INDEX e_a ON e (a); +CREATE INDEX e_s ON e (s); +EXPLAIN SELECT id FROM e WHERE COALESCE(s, 'x') = 'a'; +---- +QUERY PLAN +Scan + indexes_considered: [__pk_id: first column not in WHERE, e_ab: first column not in WHERE, e_a: first column not in WHERE, e_s: function call in predicate] + +EXPLAIN SELECT id FROM e WHERE a + 1 = 2; +---- +QUERY PLAN +Scan + indexes_considered: [__pk_id: first column not in WHERE, e_ab: arithmetic in predicate, e_a: arithmetic in predicate, e_s: first column not in WHERE] + +EXPLAIN SELECT id FROM e WHERE a = b; +---- +QUERY PLAN +Scan + indexes_considered: [__pk_id: first column not in WHERE, e_ab: non-literal rhs, e_a: non-literal rhs, e_s: first column not in WHERE] + +EXPLAIN SELECT id FROM e WHERE s LIKE 'a%'; +---- +QUERY PLAN +Scan + indexes_considered: [__pk_id: first column not in WHERE, e_ab: first column not in WHERE, e_a: first column not in WHERE, e_s: LIKE is residual-only] + +EXPLAIN SELECT id FROM e WHERE a = 1 AND b = 2; +---- +QUERY PLAN +IndexScan { index: e_ab } + predicates_pushed: [a, b] + indexes_considered: [__pk_id: first column not in WHERE, e_a: fewer predicate columns matched than chosen index, e_s: first column not in WHERE] + +EXPLAIN SELECT id FROM e WHERE a = 1; +---- +QUERY PLAN +IndexScan { index: e_ab } + predicates_pushed: [a] + indexes_considered: [__pk_id: first column not in WHERE, e_a: tied with chosen index; lost by creation order, e_s: first column not in WHERE] + +# A statement that writes is explained as it would run, and writes nothing. +EXPLAIN DELETE FROM t WHERE id = 7; +SELECT id, name, tag FROM t ORDER BY id; +---- +id | name | tag +1 | one | 1 +2 | two | 2 +7 | seven | 3 + +# A join goes through the index of its right table; a grouped count says whether a kept count +# serves it, and the statement that would keep one when none is declared. +CREATE TABLE owners (id INTEGER PRIMARY KEY, t_id INTEGER NOT NULL, note TEXT); +CREATE INDEX owners_t ON owners (t_id); +CREATE TABLE kept (id INTEGER PRIMARY KEY, ctx TEXT NOT NULL, conn TEXT NOT NULL, UNIQUE (ctx, conn, id)) MAINTAIN COUNT (ctx), (ctx, conn); +CREATE TABLE links (id INTEGER PRIMARY KEY, source_id UUID NOT NULL, target_id UUID NOT NULL, edge_type TEXT NOT NULL); + +EXPLAIN SELECT x.name, o.note FROM t x JOIN owners o ON o.t_id = x.id WHERE x.id = 7; +---- +QUERY PLAN +IndexScan { index: __pk_id } + predicates_pushed: [id] + indexes_considered: [t_tag: first column not in WHERE] +IndexScan { index: owners_t } + predicates_pushed: [t_id] + indexes_considered: [__pk_id: first column not in WHERE] + +EXPLAIN SELECT conn, COUNT(*) FROM kept WHERE ctx = 'a' GROUP BY conn; +---- +QUERY PLAN +maintained count: used (ctx, conn) + +EXPLAIN SELECT t_id, COUNT(*) FROM owners GROUP BY t_id; +---- +QUERY PLAN +maintained count: not declared — ALTER TABLE owners SET MAINTAIN COUNT (t_id) makes this O(1) +Scan + indexes_considered: [__pk_id: first column not in WHERE, owners_t: first column not in WHERE] + +# A pattern with no start node named says why no adjacency was chosen. +EXPLAIN SELECT name FROM t WHERE id IN (SELECT depth FROM GRAPH_TABLE(links MATCH (a)-[:LINKS]->(b) COLUMNS (depth AS depth))); +---- +QUERY PLAN +Scan + indexes_considered: [__pk_id: first column not in WHERE, __graph_edge_source_target_type: first column not in WHERE, __graph_edge_target_source_type: first column not in WHERE] + links: no pinned vertex +Scan + indexes_considered: [__pk_id: first column not in WHERE, t_tag: first column not in WHERE] + +# An index that loses to the table's whole key says why. +CREATE INDEX e_id ON e (id); +EXPLAIN SELECT id FROM e WHERE id = 1; +---- +QUERY PLAN +IndexScan { index: __pk_id } + predicates_pushed: [id] + indexes_considered: [e_ab: first column not in WHERE, e_a: first column not in WHERE, e_s: first column not in WHERE, e_id: lower selectivity than chosen index] + +# Explaining a write refuses what reading the statement refuses, never what only its rows would: +# a SELECT that stands for one value is explained, though running it over these rows is refused. +EXPLAIN UPDATE t SET tag = (SELECT tag FROM t) WHERE id = 1; +SELECT id, name, tag FROM t ORDER BY id; +---- +id | name | tag +1 | one | 1 +2 | two | 2 +7 | seven | 3 + +EXPLAIN DELETE FROM t WHERE id IN (SELECT name FROM t); +---- +error: PlanError + +EXPLAIN INSERT INTO t (id, name) VALUES (9, name); +---- +error: ColumnNotFound + +EXPLAIN UPDATE t SET name = nope WHERE id = 1; +---- +error: ColumnNotFound + +EXPLAIN UPDATE t SET nope = 1 WHERE id = 1; +---- +error: ColumnNotFound + +EXPLAIN INSERT INTO t (id, name) VALUES (1); +---- +error: PlanError + +EXPLAIN INSERT INTO t (id, name, tag) VALUES (9, 'n', 1) ON CONFLICT (tag) DO UPDATE SET name = 'x'; +---- +error: PlanError diff --git a/v2/contextdb/tests/sql/expressions.sql b/v2/contextdb/tests/sql/expressions.sql new file mode 100644 index 000000000..8d2a52117 --- /dev/null +++ b/v2/contextdb/tests/sql/expressions.sql @@ -0,0 +1,123 @@ +# What a select list may work out, and what its columns are called. + +CREATE TABLE sales (id INTEGER PRIMARY KEY, qty INTEGER, price REAL, region TEXT); +INSERT INTO sales (id, qty, price, region) +VALUES (1, 7, 0.5, 'north'), (2, 6, 1.5, NULL), (3, NULL, NULL, 'east'); + +# A SELECT needs no table. An expression with no name is called ?column?. +SELECT 1 + 1; +---- +?column? +2 + +SELECT id, qty * 2 FROM sales WHERE id = 1; +---- +id | ?column? +1 | 14 + +# An aggregate or a function with no name is called by its own, in lower case. +SELECT COUNT(*), SUM(qty), MIN(qty), MAX(qty), AVG(qty) FROM sales; +---- +count | sum | min | max | avg +3 | 13 | 6 | 7 | 6.5 + +SELECT COALESCE(region, 'none') FROM sales ORDER BY id; +---- +coalesce +north +none +east + +# SUM of an INTEGER column is an INTEGER, and of a REAL column a REAL. +SELECT SUM(qty) AS whole, SUM(price) AS part FROM sales; +---- +whole | part +13 | 2.0 + +# A name after an expression or a table is its alias, with or without AS. +SELECT x.qty total FROM sales x WHERE x.id = 1; +---- +total +7 + +SELECT qty AS total FROM sales AS x WHERE x.id = 1; +---- +total +7 + +# Rows of values compare with = and <>, column by column: two rows differ when any column +# does, whatever the others hold. +SELECT id FROM sales WHERE (qty, region) = (7, 'north'); +---- +id +1 + +SELECT id FROM sales WHERE (id, qty) <> (1, 7) ORDER BY id; +---- +id +2 +3 + +# A qualifier that names no table or alias of the statement is refused, and so is a function +# this version does not have, before any row is read. +SELECT y.qty FROM sales x; +---- +error: ColumnNotFound + +SELECT UPPER(region) FROM sales WHERE id > 100; +---- +error: PlanError + +# The engine gives a row no number: row_id is a name like any other, and an unknown one is +# refused (CDB-228), and a column of that name keeps what it is given. +SELECT row_id FROM sales; +---- +error: ColumnNotFound + +CREATE TABLE own_ids (row_id TEXT NOT NULL); +INSERT INTO own_ids VALUES ('k-99'); +SELECT * FROM own_ids; +---- +row_id +k-99 + +# Whole numbers stay whole, and a NULL operand gives NULL. +SELECT 7 / 2 AS whole, 7 * 0.5 AS mixed, 1.5 - 1 AS real, NULL + 1 AS unknown; +---- +whole | mixed | real | unknown +3 | 3.5 | 0.5 | NULL + +# What does not fit a column, divides by zero or adds a number to text is refused, never wrapped. +SELECT 9223372036854775807 + 1; +---- +error: PlanError + +SELECT (-9223372036854775807 - 1) * -1; +---- +error: PlanError + +SELECT 7 / 0; +---- +error: PlanError + +SELECT 7.0 / 0.0; +---- +error: PlanError + +SELECT 7 + 'x'; +---- +error: PlanError + +# The high bound of a BETWEEN and the items of an IN list may be scalar subqueries. +SELECT id FROM sales WHERE id BETWEEN 1 AND (SELECT MAX(qty) FROM sales) ORDER BY id; +---- +id +1 +2 +3 + +SELECT id FROM sales WHERE id IN (1, (SELECT MAX(id) FROM sales)) ORDER BY id; +---- +id +1 +3 diff --git a/v2/contextdb/tests/sql/graph_compose.sql b/v2/contextdb/tests/sql/graph_compose.sql new file mode 100644 index 000000000..4012dc0a0 --- /dev/null +++ b/v2/contextdb/tests/sql/graph_compose.sql @@ -0,0 +1,101 @@ +# What a graph pattern returns is rows like any other: a CTE holds them, and they are joined, +# filtered and searched from there. + +CREATE TABLE edges ( + id INTEGER PRIMARY KEY, + source_id UUID NOT NULL, + target_id UUID NOT NULL, + edge_type TEXT NOT NULL +); + +CREATE TABLE tasks (id UUID PRIMARY KEY, status TEXT NOT NULL); + +CREATE TABLE items (id UUID PRIMARY KEY, name TEXT NOT NULL, is_deprecated BOOLEAN NOT NULL, embedding VECTOR(2)); + +INSERT INTO edges (id, source_id, target_id, edge_type) +VALUES (1, '00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000002', 'DEPENDS_ON'), + (2, '00000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'DEPENDS_ON'), + (3, '00000000-0000-0000-0000-000000000004', '00000000-0000-0000-0000-000000000005', 'DEPENDS_ON'), + (4, '00000000-0000-0000-0000-000000000011', '00000000-0000-0000-0000-000000000012', 'RELATES_TO'), + (5, '00000000-0000-0000-0000-000000000012', '00000000-0000-0000-0000-000000000013', 'RELATES_TO'), + (6, '00000000-0000-0000-0000-000000000011', '00000000-0000-0000-0000-000000000014', 'RELATES_TO'), + (7, '00000000-0000-0000-0000-000000000012', '00000000-0000-0000-0000-000000000001', 'EXTRACTED_FROM'), + (8, '00000000-0000-0000-0000-000000000015', '00000000-0000-0000-0000-000000000002', 'EXTRACTED_FROM'); +---- +rows affected: 8 + +INSERT INTO tasks (id, status) +VALUES ('00000000-0000-0000-0000-000000000001', 'active'), + ('00000000-0000-0000-0000-000000000002', 'active'), + ('00000000-0000-0000-0000-000000000003', 'done'), + ('00000000-0000-0000-0000-000000000005', 'active'); +---- +rows affected: 4 + +# Items 12, 14 and 15 hold the vector that is searched for; 13 holds another. Item 15 is on no +# RELATES_TO edge, and item 14 is deprecated. +INSERT INTO items (id, name, is_deprecated, embedding) +VALUES ('00000000-0000-0000-0000-000000000012', 'near', FALSE, [1.0, 0.0]), + ('00000000-0000-0000-0000-000000000013', 'far', FALSE, [0.0, 1.0]), + ('00000000-0000-0000-0000-000000000014', 'retired', TRUE, [1.0, 0.0]), + ('00000000-0000-0000-0000-000000000015', 'outside', FALSE, [1.0, 0.0]); +---- +rows affected: 4 + +# The tasks that task 1 depends on, joined to their rows: task 3 is not active, and task 5 is +# active but no dependency of task 1. +WITH deps AS ( + SELECT b_id FROM GRAPH_TABLE( + edges MATCH (a)-[:DEPENDS_ON]->{1,3}(b) + WHERE a.id = '00000000-0000-0000-0000-000000000001' + COLUMNS (b.id AS b_id) + ) +) +SELECT t.id, t.status FROM tasks t +INNER JOIN deps ON t.id = deps.b_id +WHERE t.status = 'active'; +---- +id | status +00000000-0000-0000-0000-000000000002 | active + +# The graph first, the search after: the nearest items among those a RELATES_TO walk reaches. +# Item 15 is as near as item 12 and is in no answer, because no walk reaches it. +WITH neighborhood AS ( + SELECT b_id FROM GRAPH_TABLE( + edges MATCH (a)-[:RELATES_TO]->{1,2}(b) + COLUMNS (b.id AS b_id) + ) +), +candidates AS ( + SELECT id, name, embedding FROM items i + INNER JOIN neighborhood n ON i.id = n.b_id + WHERE i.is_deprecated = FALSE +) +SELECT id, name FROM candidates +ORDER BY embedding <=> [1.0, 0.0] +LIMIT 5; +---- +id | name +00000000-0000-0000-0000-000000000012 | near +00000000-0000-0000-0000-000000000013 | far + +# The search first, the graph after: the three nearest items, and what each was extracted from. +WITH nearest AS ( + SELECT id FROM items ORDER BY embedding <=> [1.0, 0.0] LIMIT 3 +) +SELECT a_id, b_id FROM GRAPH_TABLE( + edges MATCH (a)-[:EXTRACTED_FROM]->(b) + WHERE a.id IN (SELECT id FROM nearest) + COLUMNS (a.id AS a_id, b.id AS b_id) +) ORDER BY a_id; +---- +a_id | b_id +00000000-0000-0000-0000-000000000012 | 00000000-0000-0000-0000-000000000001 +00000000-0000-0000-0000-000000000015 | 00000000-0000-0000-0000-000000000002 + +# A graph pattern is joined through a CTE. Written straight into a join it is not read. +SELECT r.b_id, t.status FROM GRAPH_TABLE( + edges MATCH (a)-[:DEPENDS_ON]->(b) COLUMNS (b.id AS b_id) +) AS r JOIN tasks t ON t.id = r.b_id; +---- +error: ParseError diff --git a/v2/contextdb/tests/sql/graph_paths.sql b/v2/contextdb/tests/sql/graph_paths.sql new file mode 100644 index 000000000..f3f94239a --- /dev/null +++ b/v2/contextdb/tests/sql/graph_paths.sql @@ -0,0 +1,208 @@ +# GRAPH_TABLE with a variable-length step or several steps: a walk along every matching edge out +# from each start, to the upper bound. A node is reported once, at the shallowest depth it is +# reached. An edge back to a node already reached still counts. + +CREATE TABLE edges ( + id INTEGER PRIMARY KEY, + source_id UUID NOT NULL, + target_id UUID NOT NULL, + edge_type TEXT NOT NULL +); + +# A cycle 1 -> 2 -> 3 -> 1; node 5 with an edge to itself; 6 -> 7 -> 8 with 6 -> 8 beside it; +# and two starts, a and b, that both reach e in one step, while b reaches d in one and a in two. +INSERT INTO edges (id, source_id, target_id, edge_type) +VALUES (1, '00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000002', 'E'), + (2, '00000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'E'), + (3, '00000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000001', 'E'), + (4, '00000000-0000-0000-0000-000000000005', '00000000-0000-0000-0000-000000000005', 'E'), + (5, '00000000-0000-0000-0000-000000000006', '00000000-0000-0000-0000-000000000007', 'E'), + (6, '00000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000008', 'E'), + (7, '00000000-0000-0000-0000-000000000006', '00000000-0000-0000-0000-000000000008', 'E'), + (8, '00000000-0000-0000-0000-00000000000b', '00000000-0000-0000-0000-00000000000d', 'E'), + (9, '00000000-0000-0000-0000-00000000000a', '00000000-0000-0000-0000-00000000000c', 'E'), + (10, '00000000-0000-0000-0000-00000000000c', '00000000-0000-0000-0000-00000000000d', 'E'), + (11, '00000000-0000-0000-0000-00000000000b', '00000000-0000-0000-0000-00000000000e', 'E'), + (12, '00000000-0000-0000-0000-00000000000a', '00000000-0000-0000-0000-00000000000e', 'E'); +---- +rows affected: 12 + +# A cycle: the walk goes round it, and the start is reported when the cycle comes back to it +# within the range. +SELECT b_id, depth FROM GRAPH_TABLE( + edges MATCH (a)-[:E]->{1,3}(b) + WHERE a.id = '00000000-0000-0000-0000-000000000001' OR a.id = '00000000-0000-0000-0000-000000000007' + COLUMNS (b.id AS b_id, depth AS depth) +) ORDER BY depth, b_id; +---- +b_id | depth +00000000-0000-0000-0000-000000000002 | 1 +00000000-0000-0000-0000-000000000008 | 1 +00000000-0000-0000-0000-000000000003 | 2 +00000000-0000-0000-0000-000000000001 | 3 + +# The same cycle, one step short of coming back: the start is not reported. +SELECT b_id, depth FROM GRAPH_TABLE( + edges MATCH (a)-[:E]->{1,2}(b) + WHERE a.id = '00000000-0000-0000-0000-000000000001' + COLUMNS (b.id AS b_id, depth AS depth) +) ORDER BY depth; +---- +b_id | depth +00000000-0000-0000-0000-000000000002 | 1 +00000000-0000-0000-0000-000000000003 | 2 + +# The lower bound leaves out what is nearer. +SELECT b_id, depth FROM GRAPH_TABLE( + edges MATCH (a)-[:E]->{2,3}(b) + WHERE a.id = '00000000-0000-0000-0000-000000000001' + COLUMNS (b.id AS b_id, depth AS depth) +) ORDER BY depth; +---- +b_id | depth +00000000-0000-0000-0000-000000000003 | 2 +00000000-0000-0000-0000-000000000001 | 3 + +# With no start named, every node is a start. +SELECT COUNT(*) AS n FROM GRAPH_TABLE( + edges MATCH (a)-[:E]->{2,3}(b) + COLUMNS (b.id AS b_id) +); +---- +n +4 + +# A start named twice is one start: one edge leaves it, so one row. +SELECT COUNT(*) AS n FROM GRAPH_TABLE(edges MATCH (a)-[:E]->(b) WHERE a.id IN ('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000001') COLUMNS (b.id AS b_id)); +---- +n +1 + +# An edge from a node to itself reaches that node, once. +SELECT b_id, depth FROM GRAPH_TABLE( + edges MATCH (a)-[:E]->{1,2}(b) + WHERE a.id = '00000000-0000-0000-0000-000000000005' + COLUMNS (b.id AS b_id, depth AS depth) +); +---- +b_id | depth +00000000-0000-0000-0000-000000000005 | 1 + +# Node 8 is one step and two steps from node 6: it is reported once, at one. +SELECT b_id, depth FROM GRAPH_TABLE( + edges MATCH (a)-[:E]->{1,3}(b) + WHERE a.id = '00000000-0000-0000-0000-000000000006' + COLUMNS (b.id AS b_id, depth AS depth) +) ORDER BY b_id; +---- +b_id | depth +00000000-0000-0000-0000-000000000007 | 1 +00000000-0000-0000-0000-000000000008 | 1 + +# Two starts. d is reported once, from b, which is nearer. e is as near to both, and goes to +# the start that the list names first. +SELECT a_id, b_id, depth FROM GRAPH_TABLE( + edges MATCH (a)-[:E]->{1,2}(b) + WHERE a.id IN ('00000000-0000-0000-0000-00000000000b', '00000000-0000-0000-0000-00000000000a') + COLUMNS (a.id AS a_id, b.id AS b_id, depth AS depth) +) ORDER BY b_id; +---- +a_id | b_id | depth +00000000-0000-0000-0000-00000000000a | 00000000-0000-0000-0000-00000000000c | 1 +00000000-0000-0000-0000-00000000000b | 00000000-0000-0000-0000-00000000000d | 1 +00000000-0000-0000-0000-00000000000b | 00000000-0000-0000-0000-00000000000e | 1 + +SELECT a_id, b_id, depth FROM GRAPH_TABLE( + edges MATCH (a)-[:E]->{1,2}(b) + WHERE a.id IN ('00000000-0000-0000-0000-00000000000a', '00000000-0000-0000-0000-00000000000b') + COLUMNS (a.id AS a_id, b.id AS b_id, depth AS depth) +) ORDER BY b_id; +---- +a_id | b_id | depth +00000000-0000-0000-0000-00000000000a | 00000000-0000-0000-0000-00000000000c | 1 +00000000-0000-0000-0000-00000000000b | 00000000-0000-0000-0000-00000000000d | 1 +00000000-0000-0000-0000-00000000000a | 00000000-0000-0000-0000-00000000000e | 1 + +# With no start named every node is one, and between two that are as near the smaller id wins. +SELECT a_id, b_id, depth FROM GRAPH_TABLE( + edges MATCH (a)-[:E]->{1,2}(b) + COLUMNS (a.id AS a_id, b.id AS b_id, depth AS depth) +) ORDER BY b_id; +---- +a_id | b_id | depth +00000000-0000-0000-0000-000000000003 | 00000000-0000-0000-0000-000000000001 | 1 +00000000-0000-0000-0000-000000000001 | 00000000-0000-0000-0000-000000000002 | 1 +00000000-0000-0000-0000-000000000002 | 00000000-0000-0000-0000-000000000003 | 1 +00000000-0000-0000-0000-000000000005 | 00000000-0000-0000-0000-000000000005 | 1 +00000000-0000-0000-0000-000000000006 | 00000000-0000-0000-0000-000000000007 | 1 +00000000-0000-0000-0000-000000000006 | 00000000-0000-0000-0000-000000000008 | 1 +00000000-0000-0000-0000-00000000000a | 00000000-0000-0000-0000-00000000000c | 1 +00000000-0000-0000-0000-00000000000b | 00000000-0000-0000-0000-00000000000d | 1 +00000000-0000-0000-0000-00000000000a | 00000000-0000-0000-0000-00000000000e | 1 + +# Several steps written out, each node named. +SELECT a_id, b_id, c_id FROM GRAPH_TABLE( + edges MATCH (a)-[:E]->(b)-[:E]->(c) + WHERE a.id = '00000000-0000-0000-0000-000000000001' + COLUMNS (a.id AS a_id, b.id AS b_id, c.id AS c_id) +); +---- +a_id | b_id | c_id +00000000-0000-0000-0000-000000000001 | 00000000-0000-0000-0000-000000000002 | 00000000-0000-0000-0000-000000000003 + +# WHERE is applied to what the walk reached. +SELECT b_id FROM GRAPH_TABLE( + edges MATCH (a)-[:E]->{1,3}(b) + WHERE a.id = '00000000-0000-0000-0000-000000000001' AND b.id <> '00000000-0000-0000-0000-000000000002' + COLUMNS (b.id AS b_id) +) ORDER BY b_id; +---- +b_id +00000000-0000-0000-0000-000000000001 +00000000-0000-0000-0000-000000000003 + +# With no start named, a written-out pattern starts from every node that has an edge: six paths. +SELECT COUNT(*) FROM GRAPH_TABLE(edges MATCH (a)-[:E]->(b)-[:E]->(c) COLUMNS (c.id AS c_id)); +---- +count +6 + +# A pattern names its columns: with no COLUMNS it is refused. +SELECT id, depth FROM GRAPH_TABLE( + edges MATCH (a)-[:E]->(b) WHERE a.id = '00000000-0000-0000-0000-000000000001' +); +---- +error: PlanError + +# A walk needs an upper bound, and the bound is at most 10. +SELECT b_id FROM GRAPH_TABLE(edges MATCH (a)-[:E]->{1,10}(b) + WHERE a.id = '00000000-0000-0000-0000-000000000007' COLUMNS (b.id AS b_id)); +---- +b_id +00000000-0000-0000-0000-000000000008 + +SELECT b_id FROM GRAPH_TABLE(edges MATCH (a)-[:E]->{1,11}(b) COLUMNS (b.id AS b_id)); +---- +error: BfsDepthExceeded + +SELECT b_id FROM GRAPH_TABLE(edges MATCH (a)-[:E]->{1,}(b) COLUMNS (b.id AS b_id)); +---- +error: UnboundedTraversal + +# A deleted edge is no longer walked, and an edge whose end is changed leads to the new end. +DELETE FROM edges WHERE id = 2; +---- +rows affected: 1 + +UPDATE edges SET target_id = '00000000-0000-0000-0000-000000000009' WHERE id = 1; +---- +rows affected: 1 + +SELECT b_id, depth FROM GRAPH_TABLE( + edges MATCH (a)-[:E]->{1,3}(b) + WHERE a.id = '00000000-0000-0000-0000-000000000001' + COLUMNS (b.id AS b_id, depth AS depth) +); +---- +b_id | depth +00000000-0000-0000-0000-000000000009 | 1 diff --git a/v2/contextdb/tests/sql/graph_single_hop.sql b/v2/contextdb/tests/sql/graph_single_hop.sql new file mode 100644 index 000000000..0b557733e --- /dev/null +++ b/v2/contextdb/tests/sql/graph_single_hop.sql @@ -0,0 +1,179 @@ +# GRAPH_TABLE over an edge table, one hop: one row for each edge that matches, never one row for +# each target. An edge table is a table with source_id, target_id and edge_type. + +CREATE TABLE links ( + id INTEGER PRIMARY KEY, + source_id UUID NOT NULL, + target_id UUID NOT NULL, + edge_type TEXT NOT NULL +); + +# 1 -> 3 twice, under two types; 2 -> 3; and 4 -> 4, an edge from a node to itself. +INSERT INTO links (id, source_id, target_id, edge_type) +VALUES (1, '00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'LINKS'), + (2, '00000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'LINKS'), + (3, '00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'CITES'), + (4, '00000000-0000-0000-0000-000000000004', '00000000-0000-0000-0000-000000000004', 'LINKS'); +---- +rows affected: 4 + +# With no node named, every edge of the type is a row: two edges into node 3 are two rows. +SELECT a_id, b_id FROM GRAPH_TABLE( + links MATCH (a)-[:LINKS]->(b) COLUMNS (a.id AS a_id, b.id AS b_id) +) ORDER BY a_id, b_id; +---- +a_id | b_id +00000000-0000-0000-0000-000000000001 | 00000000-0000-0000-0000-000000000003 +00000000-0000-0000-0000-000000000002 | 00000000-0000-0000-0000-000000000003 +00000000-0000-0000-0000-000000000004 | 00000000-0000-0000-0000-000000000004 + +# Any type: two edges of two types between the same two nodes are two rows. +SELECT a_id, b_id FROM GRAPH_TABLE( + links MATCH (a)-[]->(b) + WHERE a.id = '00000000-0000-0000-0000-000000000001' + COLUMNS (a.id AS a_id, b.id AS b_id) +); +---- +a_id | b_id +00000000-0000-0000-0000-000000000001 | 00000000-0000-0000-0000-000000000003 +00000000-0000-0000-0000-000000000001 | 00000000-0000-0000-0000-000000000003 + +# Against the arrow: the nodes with an edge into node 3. +SELECT b_id FROM GRAPH_TABLE( + links MATCH (a)<-[:LINKS]-(b) + WHERE a.id = '00000000-0000-0000-0000-000000000003' + COLUMNS (b.id AS b_id) +) ORDER BY b_id; +---- +b_id +00000000-0000-0000-0000-000000000001 +00000000-0000-0000-0000-000000000002 + +# The same edges, named by the node they arrive at. +SELECT a_id, depth FROM GRAPH_TABLE( + links MATCH (a)-[:LINKS]->(b) + WHERE b.id = '00000000-0000-0000-0000-000000000003' + COLUMNS (a.id AS a_id, depth AS depth) +) ORDER BY a_id; +---- +a_id | depth +00000000-0000-0000-0000-000000000001 | 1 +00000000-0000-0000-0000-000000000002 | 1 + +# Either way round: an edge is followed from whichever end the node is at. +SELECT a_id, b_id FROM GRAPH_TABLE( + links MATCH (a)-[:LINKS]-(b) + WHERE a.id = '00000000-0000-0000-0000-000000000003' + COLUMNS (a.id AS a_id, b.id AS b_id) +) ORDER BY b_id; +---- +a_id | b_id +00000000-0000-0000-0000-000000000003 | 00000000-0000-0000-0000-000000000001 +00000000-0000-0000-0000-000000000003 | 00000000-0000-0000-0000-000000000002 + +# An edge from a node to itself is one edge, and either way round it is one row. +SELECT a_id, b_id FROM GRAPH_TABLE( + links MATCH (a)-[:LINKS]-(b) + WHERE a.id = '00000000-0000-0000-0000-000000000004' + COLUMNS (a.id AS a_id, b.id AS b_id) +); +---- +a_id | b_id +00000000-0000-0000-0000-000000000004 | 00000000-0000-0000-0000-000000000004 + +# A node with no edge has no row, and that is an answer. +SELECT b_id FROM GRAPH_TABLE( + links MATCH (a)-[:LINKS]->(b) + WHERE a.id = '00000000-0000-0000-0000-000000000009' + COLUMNS (b.id AS b_id) +); +---- +b_id + +# This table declares no UNIQUE rule over an edge's three values, so a second row with the same +# three is a second edge, and one hop returns both. +INSERT INTO links (id, source_id, target_id, edge_type) +VALUES (5, '00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'LINKS'); +---- +rows affected: 1 + +SELECT a_id, b_id FROM GRAPH_TABLE( + links MATCH (a)-[:LINKS]->(b) + WHERE a.id = '00000000-0000-0000-0000-000000000001' + COLUMNS (a.id AS a_id, b.id AS b_id) +); +---- +a_id | b_id +00000000-0000-0000-0000-000000000001 | 00000000-0000-0000-0000-000000000003 +00000000-0000-0000-0000-000000000001 | 00000000-0000-0000-0000-000000000003 + +# A table that declares a UNIQUE rule has one edge for each value of it. A column beside the +# three is part of what makes an edge when the rule names it. +CREATE TABLE keyed ( + id INTEGER PRIMARY KEY, + source_id UUID NOT NULL, + target_id UUID NOT NULL, + edge_type TEXT NOT NULL, + role TEXT NOT NULL, + UNIQUE (source_id, target_id, edge_type, role) +); + +INSERT INTO keyed (id, source_id, target_id, edge_type, role) +VALUES (1, '00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000002', 'LINKS', 'author'), + (2, '00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000002', 'LINKS', 'editor'); +---- +rows affected: 2 + +INSERT INTO keyed (id, source_id, target_id, edge_type, role) +VALUES (3, '00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000002', 'LINKS', 'author'); +---- +error: UniqueViolation + +SELECT b_id FROM GRAPH_TABLE( + keyed MATCH (a)-[:LINKS]->(b) + WHERE a.id = '00000000-0000-0000-0000-000000000001' + COLUMNS (b.id AS b_id) +); +---- +b_id +00000000-0000-0000-0000-000000000002 +00000000-0000-0000-0000-000000000002 + +# COLUMNS gives the ids of the nodes a pattern names and the depth, and nothing else of a node. +SELECT x FROM GRAPH_TABLE(links MATCH (a)-[:LINKS]->(b) COLUMNS (b.edge_type AS x)); +---- +error: PlanError + +# A table that is not there is reported before anything else. +SELECT b_id FROM GRAPH_TABLE(nowhere MATCH (a)-[]->(b) COLUMNS (b.id AS b_id)); +---- +error: TableNotFound + +# A table without the three edge columns holds no edges: a pattern over it is refused, whatever +# another table holds. +CREATE TABLE pairs (id INTEGER PRIMARY KEY, source_id UUID NOT NULL, target_id UUID NOT NULL); + +SELECT b_id FROM GRAPH_TABLE(pairs MATCH (a)-[]->(b) COLUMNS (b.id AS b_id)); +---- +error: PlanError + +# With no node named an undirected hop gives each edge both ways round and a self-loop once: +# 3 edges between two nodes and 1 loop. +SELECT COUNT(*) FROM GRAPH_TABLE(links MATCH (a)-[:LINKS]-(b) COLUMNS (a.id AS a_id)); +---- +count +7 + +# A step is followed at least once, and its lower bound is not above its upper. +SELECT b_id FROM GRAPH_TABLE(links MATCH (a)-[:LINKS]->{0,2}(b) COLUMNS (b.id AS b_id)); +---- +error: PlanError + +SELECT b_id FROM GRAPH_TABLE(links MATCH (a)-[:LINKS]->{3,2}(b) COLUMNS (b.id AS b_id)); +---- +error: PlanError + +# A label on a node would select nothing, so it is refused. +SELECT b_id FROM GRAPH_TABLE(links MATCH (a:Doc)-[:LINKS]->(b) COLUMNS (b.id AS b_id)); +---- +error: PlanError diff --git a/v2/contextdb/tests/sql/group_by.sql b/v2/contextdb/tests/sql/group_by.sql new file mode 100644 index 000000000..0a3e4d262 --- /dev/null +++ b/v2/contextdb/tests/sql/group_by.sql @@ -0,0 +1,199 @@ +# GROUP BY: one row for each set of grouping values, in the order of those values, NULL last. +# `plain` and `kept` hold the same rows; `kept` keeps the number of its rows for each ctx and +# for each ctx and conn, and every statement gives the same answer over either. + +CREATE TABLE plain (id INTEGER PRIMARY KEY, ctx TEXT NOT NULL, conn TEXT, bytes INTEGER); +CREATE TABLE kept ( + id INTEGER PRIMARY KEY, + ctx TEXT NOT NULL, + conn TEXT, + bytes INTEGER, + UNIQUE (ctx, conn, id) +) MAINTAIN COUNT (ctx), (ctx, conn); +INSERT INTO plain (id, ctx, conn, bytes) +VALUES (1, 'a', 'x', 10), (2, 'a', 'y', 20), (3, 'a', 'x', 30), (4, 'b', 'x', 40), + (5, 'b', NULL, NULL), (6, 'c', 'y', 60); +INSERT INTO kept (id, ctx, conn, bytes) +VALUES (1, 'a', 'x', 10), (2, 'a', 'y', 20), (3, 'a', 'x', 30), (4, 'b', 'x', 40), + (5, 'b', NULL, NULL), (6, 'c', 'y', 60); + +# A grouped COUNT(*) with and without a kept count: the same groups in the same order. +SELECT ctx, COUNT(*) FROM plain GROUP BY ctx; +---- +ctx | count +a | 3 +b | 2 +c | 1 + +SELECT ctx, COUNT(*) FROM kept GROUP BY ctx; +---- +ctx | count +a | 3 +b | 2 +c | 1 + +# Grouped by the rest of a kept list, with its leading column given. +SELECT conn, COUNT(*) AS n FROM plain WHERE ctx = 'b' GROUP BY conn; +---- +conn | n +x | 1 +NULL | 1 + +SELECT conn, COUNT(*) AS n FROM kept WHERE ctx = 'b' GROUP BY conn; +---- +conn | n +x | 1 +NULL | 1 + +# Grouped by columns no list of `kept` holds a count for: answered from the rows. +SELECT conn, COUNT(*) AS n FROM kept GROUP BY conn; +---- +conn | n +x | 3 +y | 2 +NULL | 1 + +# Every aggregate, each skipping NULL. AVG is a REAL. +SELECT ctx, COUNT(bytes), SUM(bytes), MIN(bytes), MAX(bytes), AVG(bytes) FROM plain GROUP BY ctx; +---- +ctx | count | sum | min | max | avg +a | 3 | 60 | 10 | 30 | 20.0 +b | 1 | 40 | 40 | 40 | 40.0 +c | 1 | 60 | 60 | 60 | 60.0 + +# Any expression groups. +SELECT bytes / 30 AS thirds, COUNT(*) AS n FROM plain GROUP BY bytes / 30; +---- +thirds | n +0 | 2 +1 | 2 +2 | 1 +NULL | 1 + +# HAVING keeps the groups it holds for. +SELECT ctx, COUNT(*) AS n FROM plain GROUP BY ctx HAVING COUNT(*) > 1; +---- +ctx | n +a | 3 +b | 2 + +# DISTINCT, ORDER BY and LIMIT stand around a grouped read, and it reads a WITH name or a join. +SELECT ctx, COUNT(*) AS n FROM plain GROUP BY ctx ORDER BY n DESC, ctx LIMIT 1; +---- +ctx | n +a | 3 + +SELECT DISTINCT COUNT(*) AS n FROM plain GROUP BY bytes / 30 ORDER BY n; +---- +n +1 +2 + +WITH named AS (SELECT ctx FROM plain WHERE conn IS NOT NULL) +SELECT ctx, COUNT(*) AS n FROM named GROUP BY ctx; +---- +ctx | n +a | 3 +b | 1 +c | 1 + +SELECT p.ctx, COUNT(*) AS n FROM plain p JOIN kept k ON p.id = k.id WHERE k.conn = 'x' +GROUP BY p.ctx; +---- +ctx | n +a | 2 +b | 1 + +# Without GROUP BY an aggregate is over every row the statement reaches. AVG of no value is NULL. +SELECT AVG(bytes) FROM plain; +---- +avg +32.0 + +SELECT AVG(bytes) FROM plain WHERE id = 5; +---- +avg +NULL + +# A select item that is neither grouped nor an aggregate is refused when the statement is +# planned. +SELECT ctx, conn, COUNT(*) FROM plain GROUP BY ctx; +---- +error: PlanError + +# A count list declared DESC leaves its groups greatest first, NULL last. +CREATE TABLE days (id INTEGER PRIMARY KEY, day INTEGER NOT NULL); +CREATE INDEX days_day ON days (day DESC); +ALTER TABLE days SET MAINTAIN COUNT (day DESC); +INSERT INTO days (id, day) VALUES (1, 1), (2, 2), (3, 2), (4, 3); +SELECT day, COUNT(*) AS n FROM days GROUP BY day; +---- +day | n +3 | 1 +2 | 2 +1 | 1 + +# Any expression is grouped, and LIMIT and OFFSET are over the groups. +SELECT id / 2 AS half, COUNT(*) AS n FROM days GROUP BY id / 2 ORDER BY half LIMIT 1 OFFSET 1; +---- +half | n +1 | 2 + +# A window function is not a condition on groups. +SELECT day FROM days GROUP BY day HAVING ROW_NUMBER() OVER (ORDER BY day) = 1; +---- +error: PlanError + +# A column named twice groups once. +CREATE TABLE pair (id INTEGER PRIMARY KEY, a TEXT, b TEXT, UNIQUE (a, b, id)) MAINTAIN COUNT (a, b); +INSERT INTO pair (id, a, b) VALUES (1, 'x', 'p'), (2, 'x', 'q'); +SELECT a, COUNT(*) AS n FROM pair GROUP BY a, a; +---- +a | n +x | 2 + +# A grouping expression of unlike types keeps its values apart: the text 'never' is a group of +# its own, not part of a timestamp's. +CREATE TABLE stamps (id INTEGER PRIMARY KEY, ts TIMESTAMP); +INSERT INTO stamps (id, ts) VALUES (1, '2026-01-01T00:00:00Z'), (2, NULL), (3, NULL); +SELECT COUNT(*) AS n FROM stamps GROUP BY COALESCE(ts, 'never') ORDER BY n; +---- +n +1 +2 + +# One name stands for one column, whichever qualifier a statement writes it with. +SELECT plain.ctx, COUNT(*) AS n FROM plain GROUP BY ctx ORDER BY ctx; +---- +ctx | n +a | 3 +b | 2 +c | 1 + +# A number in GROUP BY is not a column's place: it is refused (row 55 of the differences). +SELECT COUNT(*) AS n FROM plain GROUP BY 1; +---- +error: PlanError + +# AVG is a REAL from its first value, so a sum past 64 bits is answered. +CREATE TABLE big (id INTEGER PRIMARY KEY, x INTEGER); +INSERT INTO big (id, x) VALUES (1, 5000000000000000000), (2, 5000000000000000000); +SELECT AVG(x) FROM big; +---- +avg +5e18 + +# The same SELECT written twice in a grouped statement is one expression. +SELECT bytes + (SELECT 1) AS y FROM plain WHERE id <= 2 GROUP BY bytes + (SELECT 1) ORDER BY y; +---- +y +11 +21 + +# An unaliased function is named after the function, and ORDER BY may use that name. +SELECT ctx, COUNT(*) FROM plain GROUP BY ctx ORDER BY count DESC, ctx; +---- +ctx | count +a | 3 +b | 2 +c | 1 diff --git a/v2/contextdb/tests/sql/in_lists.sql b/v2/contextdb/tests/sql/in_lists.sql index 7bf8fd02d..2c2c38e78 100644 --- a/v2/contextdb/tests/sql/in_lists.sql +++ b/v2/contextdb/tests/sql/in_lists.sql @@ -112,20 +112,12 @@ SELECT id FROM stock WHERE (ref, bin) IN (('550e8400-e29b-41d4-a716-446655440002 id 2 -# Refused by name: a row value anywhere but beside IN, one of another length than its partner, -# and a list that is a SELECT. -SELECT id FROM stock WHERE (kind, bin) = ('bolt', 1); ----- -error: PlanError - +# Refused by name: a row value of another length than its partner, and a list that is a +# SELECT. SELECT id FROM stock WHERE (kind, bin) IN (('bolt', 1, 2)); ---- error: PlanError -SELECT id FROM stock WHERE id IN (SELECT id FROM stock); ----- -error: PlanError - # UPDATE and DELETE find their rows the same way. UPDATE stock SET qty = 0 WHERE id IN (1, 2); ---- diff --git a/v2/contextdb/tests/sql/insert.sql b/v2/contextdb/tests/sql/insert.sql index 11b59618e..712b99e9b 100644 --- a/v2/contextdb/tests/sql/insert.sql +++ b/v2/contextdb/tests/sql/insert.sql @@ -67,5 +67,34 @@ error: PlanError SELECT COUNT(*) FROM items WHERE id = 7; ---- -COUNT +count +0 + +# A SELECT among the VALUES is worked out before the row is stored. +CREATE TABLE counted (id INTEGER PRIMARY KEY, seen INTEGER); +INSERT INTO counted (id, seen) VALUES (1, 0), (2, 0); +INSERT INTO counted (id, seen) VALUES (3, (SELECT COUNT(*) FROM counted)); +---- +rows affected: 1 + +SELECT seen FROM counted WHERE id = 3; +---- +seen +2 + +# A comparison of unlike types with the value a SELECT gives is refused in VALUES, and nothing is stored. +CREATE TABLE words (id INTEGER PRIMARY KEY, label TEXT); +INSERT INTO words (id, label) VALUES (1, 'seven'); +CREATE TABLE flags (id INTEGER PRIMARY KEY, ok BOOLEAN); +INSERT INTO flags (id, ok) VALUES (1, 10 = (SELECT label FROM words WHERE id = 1)); +---- +error: PlanError + +INSERT INTO flags (id, ok) VALUES (2, 10 NOT IN (SELECT label FROM words WHERE id = 99)); +---- +error: PlanError + +SELECT COUNT(*) FROM flags; +---- +count 0 diff --git a/v2/contextdb/tests/sql/joins.sql b/v2/contextdb/tests/sql/joins.sql new file mode 100644 index 000000000..276835d53 --- /dev/null +++ b/v2/contextdb/tests/sql/joins.sql @@ -0,0 +1,124 @@ +# Joins: INNER, LEFT and CROSS, with the names a statement may give its tables. + +CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL); +CREATE TABLE tags (id INTEGER PRIMARY KEY, item_id INTEGER, label TEXT); +CREATE INDEX tags_item ON tags (item_id); +INSERT INTO items (id, name) VALUES (1, 'a'), (2, 'b'), (3, 'c'); +INSERT INTO tags (id, item_id, label) VALUES (10, 1, 'x'), (11, 1, 'y'), (12, 2, 'x'), (13, NULL, 'z'); + +# An inner join gives one row for each pair the condition holds for. A qualifier may be the +# table's own name, and a result column is named by its column alone. +SELECT items.id, tags.label FROM items INNER JOIN tags ON items.id = tags.item_id +ORDER BY items.id, tags.label; +---- +id | label +1 | x +1 | y +2 | x + +# A bare JOIN is an inner join, and a name after a table is its alias with or without AS. +SELECT x.name, y.label FROM items x JOIN tags y ON x.id = y.item_id WHERE y.label = 'x' +ORDER BY x.id; +---- +name | label +a | x +b | x + +# A left join keeps a left row that nothing matches, with NULL for the right side. +SELECT i.id, t.label FROM items AS i LEFT JOIN tags AS t ON i.id = t.item_id +ORDER BY i.id, t.label; +---- +id | label +1 | x +1 | y +2 | x +3 | NULL + +# CROSS JOIN gives the rows of an inner join whose condition always holds. +SELECT i.id, t.id FROM items i CROSS JOIN tags t WHERE t.id >= 12 ORDER BY i.id, t.id; +---- +id | id +1 | 12 +1 | 13 +2 | 12 +2 | 13 +3 | 12 +3 | 13 + +SELECT i.id, t.id FROM items i INNER JOIN tags t ON 1 = 1 WHERE t.id >= 12 ORDER BY i.id, t.id; +---- +id | id +1 | 12 +1 | 13 +2 | 12 +2 | 13 +3 | 12 +3 | 13 + +# A qualifier that names no table or alias of the statement is refused, though another table +# has the column. +SELECT id FROM items WHERE x.name = 'a'; +---- +error: ColumnNotFound + +# A join condition that cannot be worked out is a refusal, never fewer rows. +SELECT i.id FROM items i JOIN tags t ON -t.label > 0; +---- +error: PlanError + +# Three tables: an inner join and a left join after it, each table under an alias. A tag with +# no note is kept with NULL. +CREATE TABLE notes (id INTEGER PRIMARY KEY, tag_id INTEGER, note TEXT); +INSERT INTO notes (id, tag_id, note) VALUES (100, 10, 'n10'), (101, 12, 'n12'); +SELECT i.id, t.label, n.note FROM items AS i INNER JOIN tags AS t ON i.id = t.item_id +LEFT JOIN notes n ON n.tag_id = t.id ORDER BY i.id, t.label; +---- +id | label | note +1 | x | n10 +1 | y | NULL +2 | x | n12 + +# Keywords in lower case say the same as the first statement of this script. +select items.id, tags.label from items inner join tags on items.id = tags.item_id +order by items.id, tags.label; +---- +id | label +1 | x +1 | y +2 | x + +# A name two relations give is refused, and so is a table named twice. +SELECT id FROM items LEFT JOIN tags ON items.id = tags.item_id; +---- +error: PlanError + +SELECT * FROM items JOIN items ON items.id = items.id; +---- +error: PlanError + +# A WHERE with a SELECT in it filters a join. +SELECT i.id, t.label FROM items i JOIN tags t ON i.id = t.item_id +WHERE i.id IN (SELECT item_id FROM tags WHERE label = 'y') ORDER BY t.label; +---- +id | label +1 | x +1 | y + +# A bare ORDER BY name that the select list gives is that column, not the first of that name. +SELECT tags.id FROM items JOIN tags ON items.id = tags.item_id ORDER BY id DESC; +---- +id +12 +11 +10 + +# The name of an unaliased function is an output column, read before any input column of the +# same name (Postgres). +CREATE TABLE ca (id INTEGER PRIMARY KEY, count INTEGER); +CREATE TABLE cb (id INTEGER PRIMARY KEY, count INTEGER); +INSERT INTO ca (id, count) VALUES (1, 10); +INSERT INTO cb (id, count) VALUES (1, 20); +SELECT COUNT(*) FROM ca JOIN cb ON ca.id = cb.id ORDER BY count; +---- +count +1 diff --git a/v2/contextdb/tests/sql/json_fields.sql b/v2/contextdb/tests/sql/json_fields.sql new file mode 100644 index 000000000..be5872388 --- /dev/null +++ b/v2/contextdb/tests/sql/json_fields.sql @@ -0,0 +1,154 @@ +# A field of a JSON value: -> gives it as JSON and ->> as text. + +CREATE TABLE docs (id INTEGER PRIMARY KEY, doc JSON); +INSERT INTO docs (id, doc) +VALUES (1, '{"kind":"note","n":5,"tags":["a","b"],"o":{"a":1,"b":2}}'), + (2, '{"kind":"note","n":"5","o":{"b":2,"a":1}}'), + (3, '{"kind":"task","n":5.5,"done":true}'), + (4, NULL); + +SELECT id, doc -> 'kind' AS kind, doc ->> 'kind' AS word FROM docs ORDER BY id; +---- +id | kind | word +1 | "note" | note +2 | "note" | note +3 | "task" | task +4 | NULL | NULL + +# A number after -> is a place in an array, from 0, and a field of a field is reached in turn. +SELECT doc -> 'tags' -> 1 AS second, doc -> 'o' ->> 'b' AS b FROM docs WHERE id = 1; +---- +second | b +"b" | 2 + +# A field that is not there, or a field of what is not an object, is NULL. +SELECT id, doc -> 'done' AS done, doc -> 'kind' -> 'x' AS x FROM docs ORDER BY id; +---- +id | done | x +1 | NULL | NULL +2 | NULL | NULL +3 | true | NULL +4 | NULL | NULL + +# JSON values are equal as values of their own type, a number by its value however it is written: the number 5 is 5.0 and is not the text "5". +SELECT id FROM docs WHERE doc -> 'n' = '5.0' ORDER BY id; +---- +id +1 + +SELECT id FROM docs WHERE doc -> 'n' = '"5"' ORDER BY id; +---- +id +2 + +# An object is equal whatever order its keys were written in. +SELECT id FROM docs WHERE doc -> 'o' = '{"b":2,"a":1}' ORDER BY id; +---- +id +1 +2 + +# Conditions on two fields are joined with AND as any others are. +SELECT id FROM docs WHERE doc -> 'kind' = '"note"' AND doc -> 'n' = '"5"' ORDER BY id; +---- +id +2 + +# An index over a field is declared with the field in parentheses, and answers the same. +CREATE INDEX docs_kind ON docs ((doc -> 'kind')); +SELECT id FROM docs WHERE doc -> 'kind' = '"note"' ORDER BY id; +---- +id +1 +2 + +SELECT id FROM docs WHERE doc -> 'kind' = '"task"' AND doc -> 'n' = '5.5' ORDER BY id; +---- +id +3 + +# A row written after the index was made is found through it. +INSERT INTO docs (id, doc) VALUES (5, '{"kind":"task"}'); +SELECT id FROM docs WHERE doc -> 'kind' = '"task"' ORDER BY id; +---- +id +3 +5 + +# A quoted literal beside a JSON value is read as JSON: 'true' is the boolean, a bracketed +# list that array, in its order; a boolean is not a number's equal. +SELECT id FROM docs WHERE doc -> 'done' = 'true' ORDER BY id; +---- +id +3 + +SELECT id FROM docs WHERE doc -> 'done' = '1'; +---- +id + +SELECT id FROM docs WHERE doc -> 'tags' = '["b","a"]'; +---- +id + +SELECT id FROM docs WHERE doc -> 'tags' = '["a","b"]'; +---- +id +1 + +# Arrays or objects of different sizes are never equal, though one begins as the other does. +SELECT id FROM docs WHERE doc -> 'tags' = '["a"]' OR doc -> 'o' = '{"a":1}'; +---- +id + +# A word that is not JSON is refused by name, not matched against nothing. +SELECT id FROM docs WHERE doc -> 'kind' = 'active'; +---- +error: PlanError + +# A field's index follows its rows: found by what a row holds now, not by what it held. +CREATE INDEX docs_n ON docs ((doc -> 'n')); +UPDATE docs SET doc = '{"kind":"note","n":7}' WHERE id = 1; +DELETE FROM docs WHERE id = 3; +INSERT INTO docs (id, doc) VALUES (6, '{"n":5}'); +SELECT id FROM docs WHERE doc -> 'n' = '7'; +---- +id +1 + +SELECT id FROM docs WHERE doc -> 'n' = '5.0'; +---- +id +6 + +SELECT id FROM docs WHERE doc -> 'n' = '5.5'; +---- +id + +# Objects sort as Postgres jsonb sorts them: fewer pairs first, then key by key as text, so {"a":2} < {"aa":1} < {"b":1}; and since keys compare in storage order, shorter first, {"b":1,"d":1} < {"aa":1,"c":1}. +INSERT INTO docs (id, doc) VALUES (7, '{"b":1}'), (8, '{"aa":1}'), (9, '{"a":2}'), (10, '{"aa":1,"c":1}'), (11, '{"b":1,"d":1}'); +SELECT id FROM docs WHERE id > 6 ORDER BY doc; +---- +id +9 +8 +7 +11 +10 + +# Whole numbers past the largest signed 64-bit one stay different numbers. +INSERT INTO docs (id, doc) VALUES (12, '{"n":9223372036854775808}'); +SELECT id FROM docs WHERE doc -> 'n' = '9223372036854775809'; +---- +id + +# Values of different kinds sort as Postgres sorts jsonb: null, string, number, boolean, array, object. +INSERT INTO docs (id, doc) VALUES (13, '"s"'), (14, '{"a":1}'), (15, 'null'), (16, 'true'), (17, '[1]'), (18, '5'); +SELECT id FROM docs WHERE id > 12 ORDER BY doc; +---- +id +15 +13 +18 +16 +17 +14 diff --git a/v2/contextdb/tests/sql/key_length.sql b/v2/contextdb/tests/sql/key_length.sql index e7a0e68d3..9e7059004 100644 --- a/v2/contextdb/tests/sql/key_length.sql +++ b/v2/contextdb/tests/sql/key_length.sql @@ -164,12 +164,12 @@ rows affected: 1 SELECT COUNT(*) FROM mid WHERE u = 'ppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppaxxxxxxxxxxxxxxxxxxx'; ---- -COUNT +count 2 SELECT COUNT(*) FROM mid WHERE u = 'ppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppexxxxxxxxxxxxxxxxxxx'; ---- -COUNT +count 1 SELECT id FROM mid WHERE t > 'ppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppcxxxxxxxxxxxxxxxxxxx' ORDER BY id; diff --git a/v2/contextdb/tests/sql/like_between.sql b/v2/contextdb/tests/sql/like_between.sql new file mode 100644 index 000000000..9e282641f --- /dev/null +++ b/v2/contextdb/tests/sql/like_between.sql @@ -0,0 +1,78 @@ +# LIKE matches text against a pattern; BETWEEN is a range with both ends in it. + +CREATE TABLE parts (id INTEGER PRIMARY KEY, name TEXT, share REAL); +INSERT INTO parts (id, name, share) +VALUES (1, 'sensor-1', 0.5), (2, 'sensor-22', 1.0), (3, 'item_3', 0.05), (4, 'itemX3', 0.1), + (5, '50% off', NULL), (6, NULL, 0.75); + +# % stands for any run of characters, none included. +SELECT id FROM parts WHERE name LIKE 'sensor%' ORDER BY id; +---- +id +1 +2 + +# _ stands for exactly one character. +SELECT id FROM parts WHERE name LIKE 'sensor-_' ORDER BY id; +---- +id +1 + +SELECT id FROM parts WHERE name LIKE 'item_3' ORDER BY id; +---- +id +3 +4 + +# After a backslash, % and _ are the characters themselves. +SELECT id FROM parts WHERE name LIKE 'item\_3' ORDER BY id; +---- +id +3 + +SELECT id FROM parts WHERE name LIKE '50\%%' ORDER BY id; +---- +id +5 + +# A pattern with neither matches the whole text only, and upper and lower case differ. +SELECT id FROM parts WHERE name LIKE 'sensor' OR name LIKE 'ITEM_3' ORDER BY id; +---- +id + +# NOT LIKE is every row with a name the pattern does not match; a NULL name is in neither. +SELECT id FROM parts WHERE name NOT LIKE '%3%' ORDER BY id; +---- +id +1 +2 +5 + +# BETWEEN includes both of its ends. +SELECT id FROM parts WHERE share BETWEEN 0.5 AND 1.0 ORDER BY id; +---- +id +1 +2 +6 + +SELECT id FROM parts WHERE id BETWEEN 2 AND 3 ORDER BY id; +---- +id +2 +3 + +# NOT BETWEEN is every row with a value outside the range; a NULL value is in neither. +SELECT id FROM parts WHERE share NOT BETWEEN 0 AND 0.1 ORDER BY id; +---- +id +1 +2 +6 + +# AND after a range's second end is the next condition. +SELECT id FROM parts WHERE id BETWEEN 1 AND 4 AND name LIKE 'item%' ORDER BY id; +---- +id +3 +4 diff --git a/v2/contextdb/tests/sql/memory_limit.sql b/v2/contextdb/tests/sql/memory_limit.sql index 38df9e620..bcef922cb 100644 --- a/v2/contextdb/tests/sql/memory_limit.sql +++ b/v2/contextdb/tests/sql/memory_limit.sql @@ -38,3 +38,8 @@ SHOW MEMORY_LIMIT; ---- limit | used | available | startup_ceiling | ceiling_refresh_failures none | * | * | * | * + +# A ceiling no number holds is a syntax error. +SET MEMORY_LIMIT 99999999999999999999G; +---- +error: ParseError diff --git a/v2/contextdb/tests/sql/order_limit.sql b/v2/contextdb/tests/sql/order_limit.sql index ecd10495a..115462f07 100644 --- a/v2/contextdb/tests/sql/order_limit.sql +++ b/v2/contextdb/tests/sql/order_limit.sql @@ -121,17 +121,29 @@ id | points 1 | 30 2 | NULL -# With no ORDER BY, a read through an index comes in the index's order: its values, then the -# row's key, whatever order the rows were written in. -CREATE TABLE unordered (id INTEGER PRIMARY KEY, grp INTEGER NOT NULL); -CREATE INDEX unordered_by_grp ON unordered (grp); -INSERT INTO unordered (id, grp) VALUES (9, 2), (3, 1), (7, 2), (1, 1), (5, 2), (4, 1); -SELECT id, grp FROM unordered WHERE grp >= 1; ----- -id | grp -1 | 1 +# An indexed read gives the same order on every route: rows written out of key order, read +# through an index with a filter and no ORDER BY, come by indexed value and then by key (CDB-309). +CREATE TABLE shelf (id INTEGER PRIMARY KEY, slot INTEGER NOT NULL); +CREATE INDEX shelf_slot ON shelf (slot); +INSERT INTO shelf (id, slot) VALUES (9, 2), (3, 1), (7, 2), (1, 2), (5, 1), (8, 3); + +SELECT id, slot FROM shelf WHERE slot >= 1; +---- +id | slot 3 | 1 -4 | 1 -5 | 2 +5 | 1 +1 | 2 7 | 2 9 | 2 +8 | 3 + +# ORDER BY a whole number is not a column's place: it is refused, as the list of differences +# from Postgres says (row 55), never taken for a constant. +SELECT id FROM shelf ORDER BY 1 DESC LIMIT 2; +---- +error: PlanError + +# Two output columns of one name that ORDER BY names are ambiguous, never read as a table column. +SELECT slot AS id, id AS id FROM shelf ORDER BY id; +---- +error: PlanError diff --git a/v2/contextdb/tests/sql/order_offset.sql b/v2/contextdb/tests/sql/order_offset.sql new file mode 100644 index 000000000..87879e758 --- /dev/null +++ b/v2/contextdb/tests/sql/order_offset.sql @@ -0,0 +1,66 @@ +# ORDER BY any expressions, and OFFSET: the rows left out before the first one returned. + +CREATE TABLE readings (id INTEGER PRIMARY KEY, tag TEXT, pref TEXT, fallback TEXT, score INTEGER); +INSERT INTO readings (id, tag, pref, fallback, score) +VALUES (1, 'a', NULL, 'm', 3), (2, 'b', 'k', 'z', 1), (3, 'c', NULL, 'b', 2), (4, 'd', 'x', NULL, 2); + +SELECT tag FROM readings ORDER BY COALESCE(pref, fallback); +---- +tag +c +b +a +d + +SELECT tag FROM readings ORDER BY score + 1 DESC, tag DESC; +---- +tag +a +d +c +b + +# Any expression is a sort key: false sorts before true. +SELECT tag FROM readings ORDER BY score = 2 DESC, tag; +---- +tag +c +d +a +b + +SELECT tag FROM readings ORDER BY tag LIKE '%d' DESC, score DESC, id; +---- +tag +d +a +c +b + +# Without OFFSET the answer starts at the first row. +SELECT id FROM readings ORDER BY id LIMIT 2; +---- +id +1 +2 + +SELECT id FROM readings ORDER BY id LIMIT 2 OFFSET 1; +---- +id +2 +3 + +SELECT id FROM readings ORDER BY id DESC OFFSET 3; +---- +id +1 + +# An OFFSET past the last row is an empty answer. +SELECT id FROM readings ORDER BY id LIMIT 2 OFFSET 4; +---- +id + +# A COUNT is one row, so an OFFSET past it leaves no row. +SELECT COUNT(*) FROM readings OFFSET 1; +---- +count diff --git a/v2/contextdb/tests/sql/propagate.sql b/v2/contextdb/tests/sql/propagate.sql index 326baba22..5aee1c43a 100644 --- a/v2/contextdb/tests/sql/propagate.sql +++ b/v2/contextdb/tests/sql/propagate.sql @@ -213,36 +213,16 @@ id | status 00000000-0000-0000-0000-000000000032 | released 00000000-0000-0000-0000-000000000033 | revoked -# A ring of edges ends: 101 cites 102, 102 cites 103, 103 cites 101, and 104 is joined to -# nothing. Each claim follows once and the statement ends. An edge whose source is no claim -# is passed over. -CREATE TABLE ring_claims (id UUID PRIMARY KEY, status TEXT NOT NULL) -STATE MACHINE (status: active -> [invalidated]) -PROPAGATE ON EDGE CITES INCOMING STATE invalidated SET invalidated; -INSERT INTO ring_claims (id, status) -VALUES ('00000000-0000-0000-0000-000000000101', 'active'), ('00000000-0000-0000-0000-000000000102', 'active'), ('00000000-0000-0000-0000-000000000103', 'active'), ('00000000-0000-0000-0000-000000000104', 'active'); -INSERT INTO edges (id, source_id, target_id, edge_type) -VALUES (101, '00000000-0000-0000-0000-000000000101', '00000000-0000-0000-0000-000000000102', 'CITES'), (102, '00000000-0000-0000-0000-000000000102', '00000000-0000-0000-0000-000000000103', 'CITES'), (103, '00000000-0000-0000-0000-000000000103', '00000000-0000-0000-0000-000000000101', 'CITES'), (104, '00000000-0000-0000-0000-000000000999', '00000000-0000-0000-0000-000000000101', 'CITES'); -UPDATE ring_claims SET status = 'invalidated' WHERE id = '00000000-0000-0000-0000-000000000101'; ----- -rows affected: 1 - -SELECT id, status FROM ring_claims ORDER BY id; ----- -id | status -00000000-0000-0000-0000-000000000101 | invalidated -00000000-0000-0000-0000-000000000102 | invalidated -00000000-0000-0000-0000-000000000103 | invalidated -00000000-0000-0000-0000-000000000104 | active - -# A ring under ABORT ON FAILURE ends the same way: the row the ring comes back to is already in -# the state asked for, so it is left alone, and not refused for lacking a move out of it. +# A ring of edges ends: 111 cites 112, 112 cites 113, 113 cites 111, and 114 is joined to nothing. +# Each claim follows once and the statement ends, under ABORT ON FAILURE too: the row the ring +# comes back to is already in the state asked for, so it is left alone, and not refused for +# lacking a move out of it. An edge whose source is no claim is passed over. CREATE TABLE ring_firm (id UUID PRIMARY KEY, status TEXT NOT NULL) STATE MACHINE (status: active -> [invalidated]) PROPAGATE ON EDGE CITES_FIRM INCOMING STATE invalidated SET invalidated ABORT ON FAILURE; -INSERT INTO ring_firm (id, status) VALUES ('00000000-0000-0000-0000-000000000111', 'active'), ('00000000-0000-0000-0000-000000000112', 'active'), ('00000000-0000-0000-0000-000000000113', 'active'); +INSERT INTO ring_firm (id, status) VALUES ('00000000-0000-0000-0000-000000000111', 'active'), ('00000000-0000-0000-0000-000000000112', 'active'), ('00000000-0000-0000-0000-000000000113', 'active'), ('00000000-0000-0000-0000-000000000114', 'active'); INSERT INTO edges (id, source_id, target_id, edge_type) -VALUES (111, '00000000-0000-0000-0000-000000000111', '00000000-0000-0000-0000-000000000112', 'CITES_FIRM'), (112, '00000000-0000-0000-0000-000000000112', '00000000-0000-0000-0000-000000000113', 'CITES_FIRM'), (113, '00000000-0000-0000-0000-000000000113', '00000000-0000-0000-0000-000000000111', 'CITES_FIRM'); +VALUES (111, '00000000-0000-0000-0000-000000000111', '00000000-0000-0000-0000-000000000112', 'CITES_FIRM'), (112, '00000000-0000-0000-0000-000000000112', '00000000-0000-0000-0000-000000000113', 'CITES_FIRM'), (113, '00000000-0000-0000-0000-000000000113', '00000000-0000-0000-0000-000000000111', 'CITES_FIRM'), (114, '00000000-0000-0000-0000-000000000999', '00000000-0000-0000-0000-000000000111', 'CITES_FIRM'); UPDATE ring_firm SET status = 'invalidated' WHERE id = '00000000-0000-0000-0000-000000000111'; ---- rows affected: 1 @@ -253,6 +233,7 @@ id | status 00000000-0000-0000-0000-000000000111 | invalidated 00000000-0000-0000-0000-000000000112 | invalidated 00000000-0000-0000-0000-000000000113 | invalidated +00000000-0000-0000-0000-000000000114 | active # With no MAX DEPTH a change is followed ten edges and the eleventh row stays: 201 feeds 202, # and so on to 20c, twelve nodes in a chain. @@ -283,31 +264,27 @@ id | status 00000000-0000-0000-0000-00000000020b | stopped 00000000-0000-0000-0000-00000000020c | running -# An upsert that changes a state is followed as an UPDATE is. -CREATE TABLE up_projects (id INTEGER PRIMARY KEY, status TEXT NOT NULL) -STATE MACHINE (status: active -> [archived]); -CREATE TABLE up_tasks ( - id INTEGER PRIMARY KEY, - status TEXT NOT NULL, - project_id INTEGER REFERENCES up_projects(id) ON STATE archived PROPAGATE SET invalidated -) STATE MACHINE (status: active -> [invalidated]); -INSERT INTO up_projects (id, status) VALUES (1, 'active'), (2, 'active'); -INSERT INTO up_tasks (id, status, project_id) -VALUES (1, 'active', 1), (2, 'active', 2), (3, 'active', 1); -INSERT INTO up_projects (id, status) VALUES (1, 'active') -ON CONFLICT (id) DO UPDATE SET status = 'archived'; +# A row that references its own table is followed along the chain: four rows on, and with no MAX DEPTH ten rows on and not the eleventh. +CREATE TABLE fk_chain (id INTEGER PRIMARY KEY, status TEXT NOT NULL, prev INTEGER REFERENCES fk_chain(id) ON STATE closed PROPAGATE SET closed) STATE MACHINE (status: open -> [closed]); +INSERT INTO fk_chain (id, status, prev) VALUES (1, 'open', NULL), (2, 'open', 1), (3, 'open', 2), (4, 'open', 3), (5, 'open', 4), (6, 'open', 5), (7, 'open', 6), (8, 'open', 7), (9, 'open', 8), (10, 'open', 9), (11, 'open', 10), (12, 'open', 11); +UPDATE fk_chain SET status = 'closed' WHERE id = 1; +SELECT id, status FROM fk_chain WHERE id IN (5, 11, 12) ORDER BY id; ---- -rows affected: 1 - -SELECT id, status FROM up_tasks ORDER BY id; +id | status +5 | closed +11 | closed +12 | open + +# An upsert that changes a state is followed as an UPDATE is, for the rows of that row only. +INSERT INTO tasks (id, status, project_id) VALUES (5, 'active', 2), (6, 'active', 4); +INSERT INTO projects (id, status) VALUES (2, 'active') ON CONFLICT (id) DO UPDATE SET status = 'archived'; +SELECT id, status FROM tasks WHERE id >= 5 ORDER BY id; ---- id | status -1 | invalidated -2 | active -3 | invalidated +5 | invalidated +6 | active -# A follower whose state column is IMMUTABLE cannot follow. Without ABORT ON FAILURE the -# statement stands and the follower is left as it is; with it the statement is refused whole. +# A state that is IMMUTABLE takes no state machine: a state never changed has no next state. CREATE TABLE gate_projects (id INTEGER PRIMARY KEY, status TEXT NOT NULL) STATE MACHINE (status: active -> [archived]); CREATE TABLE lax_tasks ( @@ -315,36 +292,5 @@ CREATE TABLE lax_tasks ( status TEXT NOT NULL IMMUTABLE, project_id INTEGER REFERENCES gate_projects(id) ON STATE archived PROPAGATE SET invalidated ) STATE MACHINE (status: active -> [invalidated]); -CREATE TABLE firm_tasks ( - id INTEGER PRIMARY KEY, - status TEXT NOT NULL IMMUTABLE, - project_id INTEGER REFERENCES gate_projects(id) ON STATE archived PROPAGATE SET invalidated ABORT ON FAILURE -) STATE MACHINE (status: active -> [invalidated]); -INSERT INTO gate_projects (id, status) VALUES (1, 'active'), (2, 'active'); -INSERT INTO lax_tasks (id, status, project_id) VALUES (1, 'active', 1), (2, 'active', 1); -INSERT INTO firm_tasks (id, status, project_id) VALUES (1, 'active', 2), (2, 'active', 2); -UPDATE gate_projects SET status = 'archived' WHERE id = 1; ----- -rows affected: 1 - -SELECT id, status FROM lax_tasks ORDER BY id; ----- -id | status -1 | active -2 | active - -UPDATE gate_projects SET status = 'archived' WHERE id = 2; ---- -error: PropagationAborted - -SELECT id, status FROM gate_projects ORDER BY id; ----- -id | status -1 | archived -2 | active - -SELECT id, status FROM firm_tasks ORDER BY id; ----- -id | status -1 | active -2 | active +error: SchemaInvalid diff --git a/v2/contextdb/tests/sql/rank_policy.sql b/v2/contextdb/tests/sql/rank_policy.sql new file mode 100644 index 000000000..589508f65 --- /dev/null +++ b/v2/contextdb/tests/sql/rank_policy.sql @@ -0,0 +1,83 @@ +# USE RANK orders a search by the column's formula, before the LIMIT. From [1, 0]: task 1 ranks 1 +# (result 10), task 2 ranks 5 (no result), task 3 ranks 3 (result 11, failure), task 4 ranks 1.5 +# (results 12 and 13: the lowest key, 12, is used), task 5 ranks 1 (no result), task 6 has none. +CREATE TABLE results (id INTEGER PRIMARY KEY, task_id INTEGER NOT NULL, success BOOLEAN NOT NULL); +CREATE INDEX results_task_id_idx ON results (task_id); +CREATE TABLE tasks ( + id INTEGER PRIMARY KEY, + confidence REAL, + v VECTOR(2) RANK_POLICY ( + JOIN results ON task_id, + FORMULA '{confidence} + {vector_score} * coalesce({success}, 1.0)', + SORT_KEY effective_confidence + ) +); +INSERT INTO tasks (id, confidence, v) +VALUES (6, NULL, [0.0, 1.0]), (3, 3.0, [-1.0, 0.0]), (5, 1.0, [0.0, 1.0]), + (1, 0.0, [1.0, 0.0]), (4, 0.5, [2.0, 0.0]), (2, 5.0, [0.0, 1.0]); +INSERT INTO results (id, task_id, success) +VALUES (13, 4, FALSE), (12, 4, TRUE), (11, 3, FALSE), (10, 1, TRUE); + +SELECT id FROM tasks ORDER BY v <=> [1.0, 0.0] LIMIT 6; +---- +id +1 +4 +2 +5 +6 +3 + +# Highest rank first, equal ranks (1 and 5) in key order, the task with no rank last. +SELECT id FROM tasks ORDER BY v <=> [1.0, 0.0] USE RANK effective_confidence LIMIT 6; +---- +id +2 +3 +4 +1 +5 +6 + +# The best are taken before the LIMIT and OFFSET, not from the nearest. +SELECT id FROM tasks ORDER BY v <=> [1.0, 0.0] USE RANK effective_confidence LIMIT 2 OFFSET 2; +---- +id +4 +1 + +# No rank or score column is added. +SELECT * FROM tasks ORDER BY v <=> [1.0, 0.0] USE RANK effective_confidence LIMIT 1; +---- +id | confidence | v +2 | 5.0 | [0.0, 1.0] + +SELECT id FROM tasks ORDER BY id USE RANK effective_confidence LIMIT 2; +---- +error: UseRankRequiresVectorOrder + +SELECT id FROM tasks ORDER BY v <=> [1.0, 0.0] USE RANK effective_confidence; +---- +error: UseRankRequiresLimit + +SELECT id FROM tasks ORDER BY v <=> [1.0, 0.0] USE RANK nothing LIMIT 2; +---- +error: RankPolicyNotFound + +SELECT id FROM tasks ORDER BY v <=> ROW_VECTOR('tasks', 'v', 1) LIMIT 2; +---- +error: PlanError + +# Task 1's lowest-key result (20, success) ranks it, though the index also holds success. +CREATE TABLE runs (id INTEGER PRIMARY KEY, task_id INTEGER NOT NULL, success BOOLEAN NOT NULL); +CREATE INDEX runs_task_idx ON runs (task_id, success); +CREATE TABLE jobs (id INTEGER PRIMARY KEY, v VECTOR(2) RANK_POLICY ( + JOIN runs ON task_id, FORMULA '{vector_score} * coalesce({success}, 1.0)', SORT_KEY s)); +INSERT INTO jobs (id, v) VALUES (1, [1.0, 0.0]), (2, [1.0, 1.0]); +INSERT INTO runs (id, task_id, success) VALUES (21, 1, FALSE), (20, 1, TRUE); + +SELECT id FROM jobs ORDER BY v <=> [1.0, 0.0] USE RANK s LIMIT 2; +---- +id +1 +2 diff --git a/v2/contextdb/tests/sql/refusals.sql b/v2/contextdb/tests/sql/refusals.sql index 9353b572e..5aae0e23d 100644 --- a/v2/contextdb/tests/sql/refusals.sql +++ b/v2/contextdb/tests/sql/refusals.sql @@ -21,10 +21,11 @@ SELECT id, nope FROM notes; ---- error: ColumnNotFound -# A sort key the engine cannot work out is refused, never answered unsorted. +# A sort key the engine cannot work out is refused, never answered unsorted: this version has +# no function of that name. SELECT tag FROM notes ORDER BY UPPER(tag); ---- -error: OrderByExpressionNotSupported +error: PlanError # A key that names no row is an empty answer. SELECT id, tag FROM notes WHERE id = 404; diff --git a/v2/contextdb/tests/sql/refusals_later.sql b/v2/contextdb/tests/sql/refusals_later.sql new file mode 100644 index 000000000..f91686551 --- /dev/null +++ b/v2/contextdb/tests/sql/refusals_later.sql @@ -0,0 +1,176 @@ +# What this version does not read is refused by name when the statement is planned: no table +# named here exists, and none is looked up. + +# The clauses that describe or steer a vector index. +CREATE TABLE q (id INTEGER PRIMARY KEY, v VECTOR(3) SEARCH (candidates = 64)); +---- +error: PlanError + +CREATE TABLE q (id INTEGER PRIMARY KEY, v VECTOR(3) IVF (lists = 16)); +---- +error: PlanError + +# After the clauses this version reads, they are still refused by name and not as a syntax error. +CREATE TABLE q (id INTEGER PRIMARY KEY, tenant TEXT NOT NULL, v VECTOR(3) PARTITION_KEY (tenant) MAX_PARTITIONS 4 SEARCH_MODE AUTO IVF (LISTS = 64, PROBES = 8)); +---- +error: PlanError + +SELECT id FROM q ORDER BY v <=> [1.0, 0.0, 0.0] USE VECTOR INDEXED (candidates = 64) LIMIT 1; +---- +error: PlanError + +# Triggers, events and their delivery, removal by age, and the store's own settings. +CREATE TRIGGER on_note ON notes WHEN INSERT; +---- +error: PlanError + +DROP TRIGGER on_note; +---- +error: PlanError + +CREATE EVENT TYPE note_added WHEN INSERT ON notes; +---- +error: PlanError + +CREATE SINK audit; +---- +error: PlanError + +CREATE ROUTE note_added TO audit; +---- +error: PlanError + +DROP ROUTE note_added TO audit; +---- +error: PlanError + +CREATE SCHEDULE nightly; +---- +error: PlanError + +DROP SCHEDULE nightly; +---- +error: PlanError + +PURGE FROM notes WHERE id = 1; +---- +error: PlanError + +DISCARD FROM notes WHERE id = 1; +---- +error: PlanError + +SET DISK_LIMIT '1G'; +---- +error: PlanError + +SHOW DISK_LIMIT; +---- +error: PlanError + +SET MAINTENANCE_POLL_INTERVAL 5; +---- +error: PlanError + +SET READ_CACHE_SHARE 50; +---- +error: PlanError + +SET STORAGE_COMPACTION ON; +---- +error: PlanError + +CREATE TABLE q (id INTEGER PRIMARY KEY, until TIMESTAMP EXPIRES); +---- +error: PlanError + +CREATE TABLE q (id INTEGER PRIMARY KEY, parent INTEGER) FOLLOWS PARENT PURGE; +---- +error: PlanError + +# What belongs to several tenants and to sync. +DECLARE TENANT TABLE POLICY notes; +---- +error: PlanError + +SHOW TENANT TABLE POLICY; +---- +error: PlanError + +SHOW SYNC BINDINGS; +---- +error: PlanError + +SHOW SYNC_CONFLICT_POLICY; +---- +error: PlanError + +SHOW DELIVERY OUTCOMES; +---- +error: PlanError + +# What no version reads, each by its own kind where it has one. +CREATE PROCEDURE tidy() AS 'DELETE FROM notes'; +---- +error: StoredProcNotSupported + +CREATE FUNCTION twice(n INTEGER) AS 'n * 2'; +---- +error: StoredProcNotSupported + +SELECT id FROM notes WHERE body MATCH 'word'; +---- +error: FullTextSearchNotSupported + +WITH RECURSIVE up AS (SELECT id FROM notes) SELECT id FROM up; +---- +error: RecursiveCteNotSupported + +SELECT id FROM notes WHERE EXISTS (SELECT id FROM tags); +---- +error: SubqueryNotSupported + +SELECT id, RANK() OVER (ORDER BY id) AS r FROM notes; +---- +error: WindowFunctionNotSupported + +# A row value stands beside =, <> and IN, and nowhere else. +SELECT (id, id) FROM notes; +---- +error: PlanError + +SELECT id FROM notes INTERSECT SELECT id FROM tags; +---- +error: PlanError + +SELECT id FROM notes EXCEPT SELECT id FROM tags; +---- +error: PlanError + +INSERT INTO notes (id) SELECT id FROM tags; +---- +error: PlanError + +SELECT n.id FROM notes n RIGHT JOIN tags t ON n.id = t.id; +---- +error: PlanError + +SELECT n.id FROM notes n FULL JOIN tags t ON n.id = t.id; +---- +error: PlanError + +SELECT n.id FROM notes n, tags t; +---- +error: PlanError + +BEGIN; +---- +error: PlanError + +COMMIT; +---- +error: PlanError + +ROLLBACK; +---- +error: PlanError diff --git a/v2/contextdb/tests/sql/state_machine.sql b/v2/contextdb/tests/sql/state_machine.sql index 46da245a1..d60f9cd6d 100644 --- a/v2/contextdb/tests/sql/state_machine.sql +++ b/v2/contextdb/tests/sql/state_machine.sql @@ -146,42 +146,3 @@ SELECT id, state FROM devices; ---- id | state 1 | stopped - -# A row that references another follows that row's transition: when a project becomes -# archived, the tasks that name it become invalidated. A task of another project, and a task -# that names no project, stay as they are. -CREATE TABLE projects (id INTEGER PRIMARY KEY, status TEXT NOT NULL) -STATE MACHINE (status: active -> [paused, archived], paused -> [active, archived]); -CREATE TABLE project_tasks ( - id INTEGER PRIMARY KEY, - status TEXT NOT NULL, - project_id INTEGER REFERENCES projects(id) ON STATE archived PROPAGATE SET invalidated -) STATE MACHINE (status: active -> [invalidated, superseded]); -INSERT INTO projects (id, status) VALUES (1, 'active'), (2, 'active'); -INSERT INTO project_tasks (id, status, project_id) -VALUES (1, 'active', 1), (2, 'active', 1), (3, 'active', 2), (4, 'active', NULL); - -# A transition to another state than the one the reference names moves no task. -UPDATE projects SET status = 'paused' WHERE id = 1; ----- -rows affected: 1 - -SELECT id, status FROM project_tasks ORDER BY id; ----- -id | status -1 | active -2 | active -3 | active -4 | active - -UPDATE projects SET status = 'archived' WHERE id = 1; ----- -rows affected: 1 - -SELECT id, status FROM project_tasks ORDER BY id; ----- -id | status -1 | invalidated -2 | invalidated -3 | active -4 | active diff --git a/v2/contextdb/tests/sql/subqueries.sql b/v2/contextdb/tests/sql/subqueries.sql new file mode 100644 index 000000000..8ace9c8ee --- /dev/null +++ b/v2/contextdb/tests/sql/subqueries.sql @@ -0,0 +1,84 @@ +# A SELECT inside a statement: after IN, and as one value. + +CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT); +CREATE TABLE tags (id INTEGER PRIMARY KEY, item_id INTEGER, label TEXT); +INSERT INTO items (id, name) VALUES (1, 'a'), (2, 'b'), (3, 'c'); +INSERT INTO tags (id, item_id, label) VALUES (10, 1, 'x'), (11, 1, 'y'), (12, 2, 'x'); + +SELECT name FROM items WHERE id IN (SELECT item_id FROM tags WHERE label = 'x') ORDER BY id; +---- +name +a +b + +SELECT name FROM items WHERE id NOT IN (SELECT item_id FROM tags) ORDER BY id; +---- +name +c + +# The SELECT after IN gives one column. +SELECT name FROM items WHERE id IN (SELECT item_id, label FROM tags); +---- +error: PlanError + +# A SELECT in parentheses that gives one row of one column is that value, wherever a value may +# stand; one that gives no row is NULL. +SELECT name FROM items WHERE id = (SELECT MAX(item_id) FROM tags); +---- +name +b + +SELECT name, (SELECT COUNT(*) FROM tags) AS n FROM items WHERE id = 3; +---- +name | n +c | 3 + +SELECT name FROM items WHERE id = (SELECT item_id FROM tags WHERE label = 'none'); +---- +name + +# More than one row or column is not one value. +SELECT name FROM items WHERE id = (SELECT item_id FROM tags); +---- +error: PlanError + +SELECT name FROM items WHERE id = (SELECT item_id, label FROM tags WHERE id = 10); +---- +error: PlanError + +# A SELECT that reads the row of the statement around it, and EXISTS, are refused by name. +SELECT name FROM items WHERE id IN (SELECT item_id FROM tags WHERE tags.label = items.name); +---- +error: SubqueryNotSupported + +SELECT name FROM items WHERE EXISTS (SELECT id FROM tags); +---- +error: SubqueryNotSupported + +# A SELECT as a value has that value wherever the expression is worked out: beside an aggregate, +# in HAVING, and beside a window function. +SELECT COUNT(*) AS n, (SELECT 10) AS k FROM items; +---- +n | k +3 | 10 + +SELECT id FROM items GROUP BY id HAVING COUNT(*) > (SELECT 0) ORDER BY id; +---- +id +1 +2 +3 + +SELECT id, (SELECT 10) AS k, ROW_NUMBER() OVER (ORDER BY id) AS rn FROM items ORDER BY id; +---- +id | k | rn +1 | 10 | 1 +2 | 10 | 2 +3 | 10 | 3 + +# An unaliased window function is named row_number and an unaliased one-column SELECT by its column. +SELECT (SELECT label FROM tags WHERE id = 10), ROW_NUMBER() OVER (ORDER BY id DESC) FROM items ORDER BY label, row_number LIMIT 2; +---- +label | row_number +x | 1 +x | 2 diff --git a/v2/contextdb/tests/sql/union.sql b/v2/contextdb/tests/sql/union.sql new file mode 100644 index 000000000..007ec572c --- /dev/null +++ b/v2/contextdb/tests/sql/union.sql @@ -0,0 +1,149 @@ +# UNION ALL puts the rows of two SELECTs together; UNION also drops the rows that repeat. + +CREATE TABLE a (id INTEGER PRIMARY KEY, v TEXT); +CREATE TABLE b (id INTEGER PRIMARY KEY, v TEXT); +INSERT INTO a (id, v) VALUES (1, 'x'), (2, 'y'), (3, 'y'); +INSERT INTO b (id, v) VALUES (1, 'y'), (2, 'z'); + +# UNION ALL keeps every row, and the result's columns are named by the first SELECT. +SELECT v FROM a UNION ALL SELECT v FROM b ORDER BY v; +---- +v +x +y +y +y +z + +# UNION keeps one of each, whichever SELECT it came from. +SELECT v FROM a UNION SELECT v FROM b ORDER BY v; +---- +v +x +y +z + +# ORDER BY names a column as the first SELECT names it, even when the others call it by another name. +SELECT 2 AS n UNION SELECT 1 ORDER BY n; +---- +n +1 +2 + +SELECT v AS w FROM a UNION SELECT v FROM b ORDER BY w; +---- +w +x +y +z + +# ORDER BY, LIMIT and OFFSET are over the whole. +SELECT id, v FROM a UNION ALL SELECT id, v FROM b ORDER BY v DESC, id LIMIT 2; +---- +id | v +2 | z +1 | y + +SELECT v FROM a UNION SELECT v FROM b ORDER BY v LIMIT 1 OFFSET 1; +---- +v +y + +# A UNION stands wherever a SELECT may. +WITH whole AS (SELECT v FROM a UNION ALL SELECT v FROM b) +SELECT COUNT(*) AS n FROM whole; +---- +n +5 + +SELECT id FROM a WHERE v IN (SELECT v FROM b UNION SELECT v FROM a WHERE id = 1) ORDER BY id; +---- +id +1 +2 +3 + +# The SELECTs give the same number of columns, of types that match. Both are refused when the +# statement is planned: these tables hold no row. +CREATE TABLE e1 (id INTEGER PRIMARY KEY, n INTEGER); +CREATE TABLE e2 (id INTEGER PRIMARY KEY, s TEXT); +SELECT id, n FROM e1 UNION SELECT id FROM e2; +---- +error: PlanError + +SELECT n FROM e1 UNION ALL SELECT s FROM e2; +---- +error: PlanError + +# A chain of UNION and UNION ALL is read from the left: the first two drop repeats, the third +# keeps all it adds. ORDER BY, LIMIT and OFFSET are over the whole. +SELECT v FROM a UNION SELECT v FROM b UNION ALL SELECT v FROM a ORDER BY v LIMIT 3 OFFSET 1; +---- +v +x +y +y + +# A NULL beside a number is one column of the number's type: NULL goes last going up. +SELECT NULL AS n UNION SELECT 1 ORDER BY n; +---- +n +1 +NULL + +# ORDER BY a whole number is not a column's place: it is refused, as the list of differences +# from Postgres says (row 55), never taken for a constant. +SELECT 2 AS x UNION ALL SELECT 1 AS x ORDER BY 1 ASC LIMIT 1; +---- +error: PlanError + +# A number and text do not match, nor do a timestamp and text. +SELECT (SELECT 2) AS x UNION ALL SELECT 'abc' AS x ORDER BY x ASC LIMIT 2; +---- +error: PlanError + +CREATE TABLE ts_tbl (id INTEGER PRIMARY KEY, ts TIMESTAMP); +CREATE TABLE txt_tbl (id INTEGER PRIMARY KEY, txt TEXT); +SELECT ts FROM ts_tbl UNION ALL SELECT txt FROM txt_tbl ORDER BY ts; +---- +error: PlanError + +# The ORDER BY of a UNION names columns of its result, never an expression. +SELECT 2 AS x UNION ALL SELECT 1 AS x ORDER BY (SELECT 1); +---- +error: PlanError + +SELECT 2 AS x UNION ALL SELECT 1 AS x ORDER BY x + 1; +---- +error: PlanError + +# A SELECT that stands for a value has the type of its column: a whole number here. +SELECT (SELECT 2) AS x UNION ALL SELECT 1 AS x ORDER BY x LIMIT 1; +---- +x +1 + +# A quoted literal beside a TIMESTAMP column is text, and text does not meet a timestamp. +SELECT ts FROM ts_tbl UNION ALL SELECT '2026-01-01T00:00:00Z'; +---- +error: PlanError + +# An aggregate's type is its own: COUNT(*) + 1 is a whole number and meets one. +SELECT COUNT(*) + 1 AS x FROM a UNION ALL SELECT 1 ORDER BY x; +---- +x +1 +4 + +# A whole number and a REAL are the same only when they have the same exact value, so a UNION +# gives the same rows however its arms stand. 2^53 is a REAL and a whole number; +# 2^53 + 1 is a whole number no REAL holds. (Postgres reads 9007199254740992.0 as NUMERIC: exact.) +SELECT 9007199254740992.0 AS x UNION SELECT 9007199254740992 AS x UNION SELECT 9007199254740993 AS x ORDER BY x; +---- +x +* +9007199254740993 + +SELECT 1 AS one WHERE 9007199254740993 = 9007199254740992.0; +---- +one diff --git a/v2/contextdb/tests/sql/update_delete.sql b/v2/contextdb/tests/sql/update_delete.sql index e498f807c..be271b83c 100644 --- a/v2/contextdb/tests/sql/update_delete.sql +++ b/v2/contextdb/tests/sql/update_delete.sql @@ -104,3 +104,59 @@ k | v 99 | one 100 | two 101 | three + +# An UPDATE finds its rows with LIKE and BETWEEN as a SELECT does. +CREATE TABLE stock (id INTEGER PRIMARY KEY, name TEXT, qty INTEGER); +INSERT INTO stock (id, name, qty) VALUES (1, 'bolt-1', 5), (2, 'bolt-2', 15), (3, 'nut-1', 7), (4, 'bolt-3', 9); +UPDATE stock SET qty = 0 WHERE name LIKE 'bolt%' AND qty BETWEEN 1 AND 10; +---- +rows affected: 2 + +SELECT id, qty FROM stock ORDER BY id; +---- +id | qty +1 | 0 +2 | 15 +3 | 7 +4 | 0 + +# A SELECT inside a write is read once, before the write changes a row. +CREATE TABLE jobs (id INTEGER PRIMARY KEY, status TEXT NOT NULL, points INTEGER NOT NULL); +INSERT INTO jobs (id, status, points) VALUES (1, 'open', 1), (2, 'open', 20), (3, 'done', 30), (4, 'done', 5); +UPDATE jobs SET points = (SELECT MAX(points) FROM jobs) WHERE id IN (SELECT id FROM jobs WHERE status = 'open'); +---- +rows affected: 2 + +SELECT id, points FROM jobs ORDER BY id; +---- +id | points +1 | 30 +2 | 30 +3 | 30 +4 | 5 + +DELETE FROM jobs WHERE id IN (SELECT id FROM jobs WHERE status = 'done'); +---- +rows affected: 2 + +SELECT id FROM jobs ORDER BY id; +---- +id +1 +2 + +# A row is changed once in a statement, though its new key is met again further along the keys +# the statement reads: 1, 2 and 3 move to 11, 12 and 13 and stay there, though 11, 12 and 13 are +# still below 100. +CREATE TABLE steps (id INTEGER PRIMARY KEY, n INTEGER NOT NULL); +INSERT INTO steps (id, n) VALUES (1, 10), (2, 20), (3, 30); +UPDATE steps SET id = id + 10 WHERE id < 100; +---- +rows affected: 3 + +SELECT id, n FROM steps ORDER BY id; +---- +id | n +11 | 10 +12 | 20 +13 | 30 diff --git a/v2/contextdb/tests/sql/vector_declarations.sql b/v2/contextdb/tests/sql/vector_declarations.sql deleted file mode 100644 index bbbb02bbd..000000000 --- a/v2/contextdb/tests/sql/vector_declarations.sql +++ /dev/null @@ -1,119 +0,0 @@ -# What the declaration of a VECTOR column refuses, each by the name of its kind. A refused -# CREATE TABLE declares nothing: after each group the table is still not there. - -# A PARTITION_KEY column is a column of the same table, -CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) PARTITION_KEY (nope)); ----- -error: InvalidVectorPartitionDeclaration - -# declared NOT NULL, -CREATE TABLE docs (id INTEGER PRIMARY KEY, tenant TEXT, v VECTOR(3) PARTITION_KEY (tenant)); ----- -error: InvalidVectorPartitionDeclaration - -# of a type whose values are equal or not and nothing between: not REAL, JSON or VECTOR, -CREATE TABLE docs (id INTEGER PRIMARY KEY, weight REAL NOT NULL, v VECTOR(3) PARTITION_KEY (weight)); ----- -error: InvalidVectorPartitionDeclaration - -CREATE TABLE docs (id INTEGER PRIMARY KEY, meta JSON NOT NULL, v VECTOR(3) PARTITION_KEY (meta)); ----- -error: InvalidVectorPartitionDeclaration - -CREATE TABLE docs (id INTEGER PRIMARY KEY, other VECTOR(2) NOT NULL, v VECTOR(3) PARTITION_KEY (other)); ----- -error: InvalidVectorPartitionDeclaration - -# named once, -CREATE TABLE docs (id INTEGER PRIMARY KEY, tenant TEXT NOT NULL, v VECTOR(3) PARTITION_KEY (tenant, tenant)); ----- -error: InvalidVectorPartitionDeclaration - -# and not the vector column itself. -CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) PARTITION_KEY (v) NOT NULL); ----- -error: InvalidVectorPartitionDeclaration - -SELECT id FROM docs; ----- -error: TableNotFound - -# MAX_PARTITIONS needs a PARTITION_KEY, and is a whole number from 1 to the largest the engine -# keeps. -CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) MAX_PARTITIONS 4); ----- -error: InvalidVectorPartitionDeclaration - -CREATE TABLE docs (id INTEGER PRIMARY KEY, tenant TEXT NOT NULL, v VECTOR(3) PARTITION_KEY (tenant) MAX_PARTITIONS 0); ----- -error: InvalidVectorPartitionDeclaration - -CREATE TABLE docs (id INTEGER PRIMARY KEY, tenant TEXT NOT NULL, v VECTOR(3) PARTITION_KEY (tenant) MAX_PARTITIONS -1); ----- -error: InvalidVectorPartitionDeclaration - -CREATE TABLE docs (id INTEGER PRIMARY KEY, tenant TEXT NOT NULL, v VECTOR(3) PARTITION_KEY (tenant) MAX_PARTITIONS 99999999999); ----- -error: InvalidVectorPartitionDeclaration - -# A vector has at least one number. -CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(0)); ----- -error: InvalidVectorPolicyDeclaration - -SELECT id FROM docs; ----- -error: TableNotFound - -# The clauses that describe or steer an index are read by a later version. Each is refused by -# its name, alone or after the clauses this version reads, and never as a syntax error. -CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) SEARCH (TARGET_ACCURACY = 95, EXPECTED_VECTORS = 1000000)); ----- -error: PlanError - -CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) IVF (LISTS = 64, PROBES = 8)); ----- -error: PlanError - -CREATE TABLE docs ( - id INTEGER PRIMARY KEY, - tenant TEXT NOT NULL, - v VECTOR(3) PARTITION_KEY (tenant) MAX_PARTITIONS 4 SEARCH_MODE AUTO IVF (LISTS = 64, PROBES = 8) -); ----- -error: PlanError - -SELECT id FROM docs; ----- -error: TableNotFound - -# The name was free all along. The column is declared with room for one partition and searched -# INDEXED; ALTER changes each: searched EXACT, an ordinary search answers, and with the limit -# raised a second partition is accepted. -CREATE TABLE docs ( - id INTEGER PRIMARY KEY, - tenant TEXT NOT NULL, - v VECTOR(3) PARTITION_KEY (tenant) MAX_PARTITIONS 1 SEARCH_MODE INDEXED -); -ALTER TABLE docs ALTER COLUMN v SET SEARCH_MODE EXACT; ----- -rows affected: 0 - -ALTER TABLE docs ALTER COLUMN v SET MAX_PARTITIONS 512; ----- -rows affected: 0 - -INSERT INTO docs (id, tenant, v) VALUES (1, 'north', [1.0, 0.0, 0.0]); -INSERT INTO docs (id, tenant, v) VALUES (2, 'south', [0.0, 1.0, 0.0]); ----- -rows affected: 1 - -SELECT id FROM docs ORDER BY v <=> [1.0, 0.0, 0.0] LIMIT 1; ----- -id -1 - -SELECT id FROM docs ORDER BY v <=> [1.0, 0.0, 0.0] USE VECTOR EXACT LIMIT 1; ----- -id -1 diff --git a/v2/contextdb/tests/sql/vector_inspection.sql b/v2/contextdb/tests/sql/vector_inspection.sql index fe1622b93..2c157a5f7 100644 --- a/v2/contextdb/tests/sql/vector_inspection.sql +++ b/v2/contextdb/tests/sql/vector_inspection.sql @@ -18,7 +18,7 @@ INSERT INTO c_small (id, v) VALUES (1, [1.0, 0.0, 0.0, 0.0]), (2, [0.0, 1.0, 0.0 SHOW VECTOR_INDEXES; ---- -table | column | dimension | quantization | vector_count | bytes | partition_key_columns | max_partitions | live_partitions | search_mode | declared_auto_index_at | effective_auto_index_at | declared_consolidation_mode | declared_consolidation_change_percent | declared_consolidation_tombstone_percent | effective_consolidation_mode | effective_consolidation_change_percent | effective_consolidation_tombstone_percent | pending_inserts | tombstones | durable_vector_bytes | durable_index_bytes | indexed_available | maintenance_state | maintenance_vectors_total | maintenance_vectors_done | maintenance_vectors_remaining | unavailable_partitions | stalled_partitions | broad_route | recovery_action +table | column | dimension | quantization | vector_count | bytes | partition_key_columns | max_partitions | live_partitions | search_mode | declared_indexing_threshold | effective_indexing_threshold | declared_compaction_mode | declared_compaction_change_percent | declared_compaction_tombstone_percent | effective_compaction_mode | effective_compaction_change_percent | effective_compaction_tombstone_percent | pending_tuples | tombstones | durable_vector_bytes | durable_index_bytes | indexed_available | maintenance_state | maintenance_vectors_total | maintenance_vectors_done | maintenance_vectors_remaining | unavailable_partitions | stalled_partitions | broad_route | recovery_action a_plain | v | 3 | F32 | 0 | 0 | [] | NULL | 0 | AUTO | NULL | 100000 | NULL | NULL | NULL | PERCENT | 20 | 10 | 0 | 0 | 0 | 0 | true | idle | 0 | 0 | 0 | 0 | 0 | fan_out | none b_parts | v | 2 | F32 | 4 | 0 | ["a","b"] | 256 | 3 | AUTO | NULL | 100000 | NULL | NULL | NULL | PERCENT | 20 | 10 | 4 | 0 | 0 | 0 | true | idle | 0 | 0 | 0 | 0 | 0 | fan_out | none c_small | v | 4 | SQ8 | 2 | 0 | [] | NULL | 1 | AUTO | NULL | 100000 | NULL | NULL | NULL | PERCENT | 20 | 10 | 2 | 0 | 0 | 0 | true | idle | 0 | 0 | 0 | 0 | 0 | fan_out | none @@ -26,7 +26,7 @@ c_small | v | 4 | SQ8 | 2 | 0 | [] | NULL | 1 | AUTO | NULL | 100000 | NULL | NU # A column with no key has one partition, there before its first vector. SHOW VECTOR_PARTITIONS; ---- -table | column | partition_key | live_rows | pending_inserts | tombstones | durable_vector_bytes | durable_index_bytes | indexed_available | availability_reason | maintenance_state | maintenance_reason | maintenance_vectors_total | maintenance_vectors_done | maintenance_vectors_remaining | lists | probes | recovery_action +table | column | partition_key | live_rows | pending_tuples | tombstones | durable_vector_bytes | durable_index_bytes | indexed_available | availability_reason | maintenance_state | maintenance_reason | maintenance_vectors_total | maintenance_vectors_done | maintenance_vectors_remaining | lists | probes | recovery_action a_plain | v | {} | 0 | 0 | 0 | 0 | 0 | true | none | idle | none | 0 | 0 | 0 | NULL | NULL | none b_parts | v | {"a":"x","b":1} | 2 | 2 | 0 | 0 | 0 | true | none | idle | none | 0 | 0 | 0 | NULL | NULL | none b_parts | v | {"a":"x","b":2} | 1 | 1 | 0 | 0 | 0 | true | none | idle | none | 0 | 0 | 0 | NULL | NULL | none @@ -35,7 +35,7 @@ c_small | v | {} | 2 | 2 | 0 | 0 | 0 | true | none | idle | none | 0 | 0 | 0 | N SHOW VECTOR_PARTITIONS FOR b_parts.v; ---- -table | column | partition_key | live_rows | pending_inserts | tombstones | durable_vector_bytes | durable_index_bytes | indexed_available | availability_reason | maintenance_state | maintenance_reason | maintenance_vectors_total | maintenance_vectors_done | maintenance_vectors_remaining | lists | probes | recovery_action +table | column | partition_key | live_rows | pending_tuples | tombstones | durable_vector_bytes | durable_index_bytes | indexed_available | availability_reason | maintenance_state | maintenance_reason | maintenance_vectors_total | maintenance_vectors_done | maintenance_vectors_remaining | lists | probes | recovery_action b_parts | v | {"a":"x","b":1} | 2 | 2 | 0 | 0 | 0 | true | none | idle | none | 0 | 0 | 0 | NULL | NULL | none b_parts | v | {"a":"x","b":2} | 1 | 1 | 0 | 0 | 0 | true | none | idle | none | 0 | 0 | 0 | NULL | NULL | none b_parts | v | {"a":"y","b":1} | 1 | 1 | 0 | 0 | 0 | true | none | idle | none | 0 | 0 | 0 | NULL | NULL | none @@ -43,13 +43,13 @@ b_parts | v | {"a":"y","b":1} | 1 | 1 | 0 | 0 | 0 | true | none | idle | none | # LIMIT cuts the list with FOR or without; OFFSET, after LIMIT only, skips rows first. SHOW VECTOR_PARTITIONS LIMIT 2; ---- -table | column | partition_key | live_rows | pending_inserts | tombstones | durable_vector_bytes | durable_index_bytes | indexed_available | availability_reason | maintenance_state | maintenance_reason | maintenance_vectors_total | maintenance_vectors_done | maintenance_vectors_remaining | lists | probes | recovery_action +table | column | partition_key | live_rows | pending_tuples | tombstones | durable_vector_bytes | durable_index_bytes | indexed_available | availability_reason | maintenance_state | maintenance_reason | maintenance_vectors_total | maintenance_vectors_done | maintenance_vectors_remaining | lists | probes | recovery_action a_plain | v | {} | 0 | 0 | 0 | 0 | 0 | true | none | idle | none | 0 | 0 | 0 | NULL | NULL | none b_parts | v | {"a":"x","b":1} | 2 | 2 | 0 | 0 | 0 | true | none | idle | none | 0 | 0 | 0 | NULL | NULL | none SHOW VECTOR_PARTITIONS FOR b_parts.v LIMIT 2 OFFSET 1; ---- -table | column | partition_key | live_rows | pending_inserts | tombstones | durable_vector_bytes | durable_index_bytes | indexed_available | availability_reason | maintenance_state | maintenance_reason | maintenance_vectors_total | maintenance_vectors_done | maintenance_vectors_remaining | lists | probes | recovery_action +table | column | partition_key | live_rows | pending_tuples | tombstones | durable_vector_bytes | durable_index_bytes | indexed_available | availability_reason | maintenance_state | maintenance_reason | maintenance_vectors_total | maintenance_vectors_done | maintenance_vectors_remaining | lists | probes | recovery_action b_parts | v | {"a":"x","b":2} | 1 | 1 | 0 | 0 | 0 | true | none | idle | none | 0 | 0 | 0 | NULL | NULL | none b_parts | v | {"a":"y","b":1} | 1 | 1 | 0 | 0 | 0 | true | none | idle | none | 0 | 0 | 0 | NULL | NULL | none @@ -61,3 +61,17 @@ error: TableNotFound SHOW VECTOR_PARTITIONS FOR b_parts.a; ---- error: UnknownVectorIndex + +# A syntax error: OFFSET stands only after LIMIT, FOR names a table and a column, and the index +# list takes no FOR. +SHOW VECTOR_PARTITIONS OFFSET 1; +---- +error: ParseError + +SHOW VECTOR_PARTITIONS FOR b_parts; +---- +error: ParseError + +SHOW VECTOR_INDEXES FOR b_parts.v; +---- +error: ParseError diff --git a/v2/contextdb/tests/sql/vector_policy.sql b/v2/contextdb/tests/sql/vector_policy.sql index 66157f1d6..d7060b354 100644 --- a/v2/contextdb/tests/sql/vector_policy.sql +++ b/v2/contextdb/tests/sql/vector_policy.sql @@ -1,24 +1,24 @@ # The clauses of a VECTOR column that say how its vectors are kept and when they are grouped for -# search: WITH (quantization), AUTO_INDEX_AT and CONSOLIDATION. Each is declared alone and all +# search: WITH (quantization), INDEXING_THRESHOLD and COMPACTION. Each is declared alone and all # together in the one order they are written in, after which SHOW VECTOR_INDEXES gives back what # was declared and what is in force. A clause not written is NULL as declared and its default # in force: 100000 vectors, and regrouping at 20 percent changed or 10 percent removed. CREATE TABLE a_reduced (id INTEGER PRIMARY KEY, v VECTOR(3) WITH (quantization = 'SQ8')); -CREATE TABLE b_sized (id INTEGER PRIMARY KEY, v VECTOR(3) AUTO_INDEX_AT 5000); -CREATE TABLE c_both (id INTEGER PRIMARY KEY, v VECTOR(3) CONSOLIDATION (CHANGE_PERCENT = 25, TOMBSTONE_PERCENT = 5)); -CREATE TABLE d_change (id INTEGER PRIMARY KEY, v VECTOR(3) CONSOLIDATION (CHANGE_PERCENT = 25)); -CREATE TABLE e_never (id INTEGER PRIMARY KEY, v VECTOR(3) CONSOLIDATION NONE); +CREATE TABLE b_sized (id INTEGER PRIMARY KEY, v VECTOR(3) INDEXING_THRESHOLD 5000); +CREATE TABLE c_both (id INTEGER PRIMARY KEY, v VECTOR(3) COMPACTION (CHANGE_PERCENT = 25, TOMBSTONE_PERCENT = 5)); +CREATE TABLE d_change (id INTEGER PRIMARY KEY, v VECTOR(3) COMPACTION (CHANGE_PERCENT = 25)); +CREATE TABLE e_never (id INTEGER PRIMARY KEY, v VECTOR(3) COMPACTION NONE); CREATE TABLE f_whole ( id INTEGER PRIMARY KEY, tenant TEXT NOT NULL, v VECTOR(3) WITH (quantization = 'SQ8') PARTITION_KEY (tenant) MAX_PARTITIONS 4 SEARCH_MODE EXACT - AUTO_INDEX_AT 5000 CONSOLIDATION (CHANGE_PERCENT = 25, TOMBSTONE_PERCENT = 5) + INDEXING_THRESHOLD 5000 COMPACTION (CHANGE_PERCENT = 25, TOMBSTONE_PERCENT = 5) ); SHOW VECTOR_INDEXES; ---- -table | column | dimension | quantization | vector_count | bytes | partition_key_columns | max_partitions | live_partitions | search_mode | declared_auto_index_at | effective_auto_index_at | declared_consolidation_mode | declared_consolidation_change_percent | declared_consolidation_tombstone_percent | effective_consolidation_mode | effective_consolidation_change_percent | effective_consolidation_tombstone_percent | pending_inserts | tombstones | durable_vector_bytes | durable_index_bytes | indexed_available | maintenance_state | maintenance_vectors_total | maintenance_vectors_done | maintenance_vectors_remaining | unavailable_partitions | stalled_partitions | broad_route | recovery_action +table | column | dimension | quantization | vector_count | bytes | partition_key_columns | max_partitions | live_partitions | search_mode | declared_indexing_threshold | effective_indexing_threshold | declared_compaction_mode | declared_compaction_change_percent | declared_compaction_tombstone_percent | effective_compaction_mode | effective_compaction_change_percent | effective_compaction_tombstone_percent | pending_tuples | tombstones | durable_vector_bytes | durable_index_bytes | indexed_available | maintenance_state | maintenance_vectors_total | maintenance_vectors_done | maintenance_vectors_remaining | unavailable_partitions | stalled_partitions | broad_route | recovery_action a_reduced | v | 3 | SQ8 | 0 | 0 | [] | NULL | 0 | AUTO | NULL | 100000 | NULL | NULL | NULL | PERCENT | 20 | 10 | 0 | 0 | 0 | 0 | true | idle | 0 | 0 | 0 | 0 | 0 | fan_out | none b_sized | v | 3 | F32 | 0 | 0 | [] | NULL | 0 | AUTO | 5000 | 5000 | NULL | NULL | NULL | PERCENT | 20 | 10 | 0 | 0 | 0 | 0 | true | idle | 0 | 0 | 0 | 0 | 0 | fan_out | none c_both | v | 3 | F32 | 0 | 0 | [] | NULL | 0 | AUTO | NULL | 100000 | PERCENT | 25 | 5 | PERCENT | 25 | 5 | 0 | 0 | 0 | 0 | true | idle | 0 | 0 | 0 | 0 | 0 | fan_out | none @@ -26,71 +26,34 @@ d_change | v | 3 | F32 | 0 | 0 | [] | NULL | 0 | AUTO | NULL | 100000 | PERCENT e_never | v | 3 | F32 | 0 | 0 | [] | NULL | 0 | AUTO | NULL | 100000 | NONE | NULL | NULL | NONE | NULL | NULL | 0 | 0 | 0 | 0 | true | idle | 0 | 0 | 0 | 0 | 0 | fan_out | none f_whole | v | 3 | SQ8 | 0 | 0 | ["tenant"] | 4 | 0 | EXACT | 5000 | 5000 | PERCENT | 25 | 5 | PERCENT | 25 | 5 | 0 | 0 | 0 | 0 | true | idle | 0 | 0 | 0 | 0 | 0 | fan_out | none -# What a declaration refuses, each by the name of its kind. A way of keeping a vector that is -# neither F32 nor SQ8, -CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) WITH (quantization = 'PQ')); ----- -error: InvalidVectorPolicyDeclaration - -# an AUTO_INDEX_AT that is not a positive number, or is past the largest the engine keeps, -CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) AUTO_INDEX_AT 0); ----- -error: InvalidVectorPolicyDeclaration - -CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) AUTO_INDEX_AT -1); ----- -error: InvalidVectorPolicyDeclaration - -CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) AUTO_INDEX_AT 99999999999999999999); ----- -error: InvalidVectorPolicyDeclaration - -# and a percentage that is not a whole number from 1 to 100. -CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) CONSOLIDATION (CHANGE_PERCENT = 0)); ----- -error: InvalidVectorPolicyDeclaration - -CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) CONSOLIDATION (TOMBSTONE_PERCENT = 101)); ----- -error: InvalidVectorPolicyDeclaration - -# SQ4, IVF (...) and SEARCH (...) are read by a later version: refused by name, not as a syntax -# error. +# SQ4 is read by a later version: refused by name, not as a syntax error. CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) WITH (quantization = 'SQ4')); ---- error: PlanError -CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) IVF (LISTS = 64, PROBES = 8)); ----- -error: PlanError - -CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) SEARCH (TARGET_ACCURACY = 95, EXPECTED_VECTORS = 1000000)); ----- -error: PlanError - -# A syntax error: a clause out of its order, and a CONSOLIDATION list that is empty, names a +# A syntax error: a clause out of its order, and a COMPACTION list that is empty, names a # member twice or names another member. -CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) AUTO_INDEX_AT 5000 SEARCH_MODE EXACT); +CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) INDEXING_THRESHOLD 5000 SEARCH_MODE EXACT); ---- error: ParseError -CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) CONSOLIDATION NONE AUTO_INDEX_AT 5000); +CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) COMPACTION NONE INDEXING_THRESHOLD 5000); ---- error: ParseError -CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) AUTO_INDEX_AT 5000 WITH (quantization = 'SQ8')); +CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) INDEXING_THRESHOLD 5000 WITH (quantization = 'SQ8')); ---- error: ParseError -CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) CONSOLIDATION ()); +CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) COMPACTION ()); ---- error: ParseError -CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) CONSOLIDATION (CHANGE_PERCENT = 25, CHANGE_PERCENT = 30)); +CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) COMPACTION (CHANGE_PERCENT = 25, CHANGE_PERCENT = 30)); ---- error: ParseError -CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) CONSOLIDATION (LISTS = 4)); +CREATE TABLE docs (id INTEGER PRIMARY KEY, v VECTOR(3) COMPACTION (LISTS = 4)); ---- error: ParseError diff --git a/v2/contextdb/tests/sql/vector_search.sql b/v2/contextdb/tests/sql/vector_search.sql index 1813056b6..d7d26df93 100644 --- a/v2/contextdb/tests/sql/vector_search.sql +++ b/v2/contextdb/tests/sql/vector_search.sql @@ -83,7 +83,7 @@ id | similarity # A distance with no name is called what any unnamed expression is called. SELECT id, v <=> '[1,0,0,0]' FROM points ORDER BY v <=> '[1,0,0,0]' LIMIT 2; ---- -id | expr +id | ?column? 1 | 0.0 2 | 0.0 @@ -242,7 +242,7 @@ id | status SHOW VECTOR_PARTITIONS FOR claims.v; ---- -table | column | partition_key | live_rows | pending_inserts | tombstones | durable_vector_bytes | durable_index_bytes | indexed_available | availability_reason | maintenance_state | maintenance_reason | maintenance_vectors_total | maintenance_vectors_done | maintenance_vectors_remaining | lists | probes | recovery_action +table | column | partition_key | live_rows | pending_tuples | tombstones | durable_vector_bytes | durable_index_bytes | indexed_available | availability_reason | maintenance_state | maintenance_reason | maintenance_vectors_total | maintenance_vectors_done | maintenance_vectors_remaining | lists | probes | recovery_action claims | v | {} | 2 | 2 | 0 | 0 | 0 | true | none | idle | none | 0 | 0 | 0 | NULL | NULL | none UPDATE claims SET status = 'active' WHERE id IN (1, 2, 3); @@ -257,3 +257,98 @@ id 5 3 4 + +# A distance is a value of the row: <=> stands wherever an expression may. No LIMIT orders every +# row with a vector (row 6 has none and is in no answer): +SELECT id FROM points WHERE id > 3 ORDER BY v <=> '[1,0,0,0]'; +---- +id +5 +7 +8 +4 + +# in a WHERE beside a search; in the select list; farthest first; with a second sort key at one +# distance (rows 1 and 2 are both 0); between two columns. +SELECT id FROM points WHERE v <=> '[1,0,0,0]' < 1.5 ORDER BY v <=> '[1,0,0,0]' LIMIT 4; +---- +id +1 +2 +5 +3 + +SELECT id, v <=> '[1,0,0,0]' AS distance FROM points WHERE id IN (1, 4, 5) ORDER BY distance DESC LIMIT 3; +---- +id | distance +4 | 2.0 +5 | * +1 | 0.0 + +SELECT id FROM points ORDER BY v <=> '[1,0,0,0]', id DESC LIMIT 1; +---- +id +2 + +CREATE TABLE pairs (id INTEGER PRIMARY KEY, a VECTOR(2), b VECTOR(2)); +INSERT INTO pairs (id, a, b) VALUES (3, [0.0, 1.0], [1.0, 0.0]), (1, [1.0, 0.0], [0.0, 1.0]), (2, [1.0, 0.0], [1.0, 0.0]); +SELECT id FROM pairs ORDER BY a <=> b LIMIT 3; +---- +id +2 +1 +3 + +# EXCLUDE VECTOR rows stay out of an indexed-WHERE search and an aliased one. Row 1 is nearest. +CREATE TABLE held (id INTEGER PRIMARY KEY, status TEXT NOT NULL, grp INTEGER NOT NULL, v VECTOR(2)) +STATE MACHINE (status: active -> [gone], gone -> [active]) PROPAGATE ON STATE gone EXCLUDE VECTOR; +CREATE INDEX held_grp ON held (grp); +INSERT INTO held (id, status, grp, v) VALUES (1, 'active', 1, [1.0, 0.0]), (2, 'active', 1, [0.5, 0.5]), (3, 'active', 2, [0.0, 1.0]); +UPDATE held SET status = 'gone' WHERE id = 1; +---- +rows affected: 1 + +SELECT id FROM held WHERE grp = 1 ORDER BY v <=> [1.0, 0.0] LIMIT 5; +---- +id +2 + +SELECT id FROM held h ORDER BY h.v <=> [1.0, 0.0] LIMIT 5; +---- +id +2 +3 + +# On a table with EXCLUDE VECTOR states <=> is answered only as ORDER BY v <=> q LIMIT n. +SELECT id FROM held ORDER BY v <=> [1.0, 0.0]; +---- +error: PlanError + +SELECT id FROM held ORDER BY v <=> [1.0, 0.0] DESC LIMIT 5; +---- +error: PlanError + +SELECT id FROM held ORDER BY (v <=> [1.0, 0.0]) + 0 LIMIT 5; +---- +error: PlanError + +SELECT id, v <=> [1.0, 0.0] AS distance FROM held WHERE id = 1; +---- +error: PlanError + +# Row 6 has no vector: in no answer, however the sort key is wrapped or followed. +SELECT id FROM points ORDER BY (v <=> [1.0, 0.0, 0.0, 0.0]) + 0 LIMIT 10; +---- +id +1 +2 +5 +3 +7 +8 +4 + +# LIMIT 0 is still validated. +SELECT id FROM points ORDER BY v <=> [1.0, 0.0, 0.0] LIMIT 0; +---- +error: VectorIndexDimensionMismatch diff --git a/v2/contextdb/tests/sql/vector_search_refusals.sql b/v2/contextdb/tests/sql/vector_search_refusals.sql index f1497f958..6ba06dd30 100644 --- a/v2/contextdb/tests/sql/vector_search_refusals.sql +++ b/v2/contextdb/tests/sql/vector_search_refusals.sql @@ -5,17 +5,6 @@ CREATE TABLE docs (id INTEGER PRIMARY KEY, title TEXT, closeness REAL, v VECTOR( INSERT INTO docs (id, title, v, w) VALUES (1, 'one', [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]), (2, 'two', [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]); -# A search needs a LIMIT: without one it is not supported in this version. The refusal has no -# kind of its own: it is the one every statement of a later version gets, and its sentence -# names a vector search without LIMIT. -SELECT id FROM docs ORDER BY v <=> [1.0, 0.0, 0.0]; ----- -error: PlanError - -SELECT id, v <=> [1.0, 0.0, 0.0] AS distance FROM docs ORDER BY distance; ----- -error: PlanError - # USE VECTOR belongs to a search, not to a plain ORDER BY. SELECT id FROM docs ORDER BY id USE VECTOR EXACT LIMIT 2; ---- @@ -34,101 +23,13 @@ SELECT id FROM docs ORDER BY v <=> '[1,0,0,0]' LIMIT 2; ---- error: VectorIndexDimensionMismatch -# INDEXED is not refused for rows that no maintenance cycle has grouped yet: asked for in the -# statement or declared on the column, it searches every one of them, as EXACT and AUTO do. -SELECT id FROM docs ORDER BY v <=> [1.0, 0.0, 0.0] USE VECTOR INDEXED LIMIT 2; ----- -id -1 -2 - -SELECT id FROM docs ORDER BY v <=> [1.0, 0.0, 0.0] USE VECTOR EXACT LIMIT 2; ----- -id -1 -2 - -CREATE TABLE indexed (id INTEGER PRIMARY KEY, v VECTOR(3) SEARCH_MODE INDEXED); -INSERT INTO indexed (id, v) VALUES (1, [0.0, 1.0, 0.0]), (2, [1.0, 0.0, 0.0]); -SELECT id FROM indexed ORDER BY v <=> [1.0, 0.0, 0.0] LIMIT 2; ----- -id -2 -1 - -SELECT id FROM indexed ORDER BY v <=> [1.0, 0.0, 0.0] USE VECTOR EXACT LIMIT 2; ----- -id -2 -1 - -SELECT id FROM indexed ORDER BY v <=> [1.0, 0.0, 0.0] USE VECTOR AUTO LIMIT 2; ----- -id -2 -1 - -# <=> in ORDER BY is the whole of vector search: there is no search function, no vector taken -# from another row, and no ranking by a policy in this version. +# There is no search function, and a distance is not carried into a write: an UPDATE's value, a +# DELETE's filter. (A vector taken from another row is refused in rank_policy.sql, and every +# other use of <=> is an answer in vector_search.sql.) SELECT vector_search(v, [1.0, 0.0, 0.0], 2) FROM docs; ---- error: PlanError -SELECT id FROM docs ORDER BY v <=> ROW_VECTOR('docs', 'v', 1) LIMIT 2; ----- -error: PlanError - -SELECT id FROM docs ORDER BY v <=> [1.0, 0.0, 0.0] USE RANK effective_confidence LIMIT 2; ----- -error: PlanError - -# A distance has a value only for the rows of a search, as that search's one ascending sort key. -# Refused by name: a distance in a WHERE, with a search beside it or without; -SELECT id FROM docs WHERE v <=> [1.0, 0.0, 0.0] < 0.5; ----- -error: PlanError - -SELECT id FROM docs WHERE v <=> [1.0, 0.0, 0.0] < 0.5 ORDER BY v <=> [1.0, 0.0, 0.0] LIMIT 2; ----- -error: PlanError - -# in a select list whose statement does not order by it; -SELECT id, v <=> [1.0, 0.0, 0.0] AS distance FROM docs; ----- -error: PlanError - -SELECT id, v <=> [1.0, 0.0, 0.0] AS distance FROM docs ORDER BY id LIMIT 2; ----- -error: PlanError - -# farthest first, and beside a second sort key; -SELECT id FROM docs ORDER BY v <=> [1.0, 0.0, 0.0] DESC LIMIT 2; ----- -error: PlanError - -SELECT id FROM docs ORDER BY v <=> [1.0, 0.0, 0.0], id LIMIT 2; ----- -error: PlanError - -# in the select list of a search, to another vector or from another column than the ORDER BY's; -SELECT id, v <=> [0.0, 1.0, 0.0] AS other FROM docs ORDER BY v <=> [1.0, 0.0, 0.0] LIMIT 2; ----- -error: PlanError - -SELECT id, w <=> [1.0, 0.0, 0.0] AS other FROM docs ORDER BY v <=> [1.0, 0.0, 0.0] LIMIT 2; ----- -error: PlanError - -# between two columns, and from something that is not a column; -SELECT id FROM docs ORDER BY v <=> w LIMIT 2; ----- -error: PlanError - -SELECT id FROM docs ORDER BY [0.0, 1.0, 0.0] <=> [1.0, 0.0, 0.0] LIMIT 2; ----- -error: PlanError - -# and in a statement that writes. UPDATE docs SET closeness = v <=> [1.0, 0.0, 0.0]; ---- error: PlanError diff --git a/v2/contextdb/tests/sql/where.sql b/v2/contextdb/tests/sql/where.sql index b7eb6124b..042072356 100644 --- a/v2/contextdb/tests/sql/where.sql +++ b/v2/contextdb/tests/sql/where.sql @@ -79,6 +79,12 @@ SELECT id FROM readings WHERE NULL ORDER BY id; ---- id +# NULL is unknown unless the other side settles the answer, whichever side it is on. +SELECT NULL AND FALSE AS a, FALSE AND NULL AS b, NULL AND TRUE AS c, TRUE AND TRUE AS d, TRUE OR NULL AS e, NULL OR TRUE AS f, NULL OR FALSE AS g, FALSE OR FALSE AS h, NOT NULL AS i, NULL = NULL AS j; +---- +a | b | c | d | e | f | g | h | i | j +false | false | NULL | true | true | true | NULL | false | NULL | NULL + # AND, OR and NOT. AND binds tighter than OR. SELECT id FROM readings WHERE a > 6 AND b > 0 ORDER BY id; ---- diff --git a/v2/contextdb/tests/sql/window.sql b/v2/contextdb/tests/sql/window.sql new file mode 100644 index 000000000..a0f9897f3 --- /dev/null +++ b/v2/contextdb/tests/sql/window.sql @@ -0,0 +1,117 @@ +# ROW_NUMBER() OVER: the rows of each partition numbered 1, 2, 3 in the window's order. + +CREATE TABLE sessions (id INTEGER PRIMARY KEY, ctx TEXT NOT NULL, at INTEGER NOT NULL); +INSERT INTO sessions (id, ctx, at) +VALUES (1, 'a', 10), (2, 'a', 30), (3, 'a', 30), (4, 'a', 20), (5, 'b', 5), (6, 'b', 7), (7, 'c', 1); + +# The newest rows of each partition, each partition with its own bound. Rows 2 and 3 are at +# the same time and get different numbers, in the order the window goes on to give. +WITH ranked AS ( + SELECT ctx, id, ROW_NUMBER() OVER (PARTITION BY ctx ORDER BY at DESC, id ASC) AS r + FROM sessions +) +SELECT ctx, id, r FROM ranked WHERE (ctx = 'a' AND r <= 3) OR (ctx = 'b' AND r <= 1) +ORDER BY ctx, r; +---- +ctx | id | r +a | 2 | 1 +a | 3 | 2 +a | 4 | 3 +b | 6 | 1 + +# An index in the window's order changes the work and not the answer. +CREATE INDEX sessions_newest ON sessions (ctx ASC, at DESC, id ASC); +WITH ranked AS ( + SELECT ctx, id, ROW_NUMBER() OVER (PARTITION BY ctx ORDER BY at DESC, id ASC) AS r + FROM sessions +) +SELECT ctx, id, r FROM ranked WHERE (ctx = 'a' AND r <= 3) OR (ctx = 'b' AND r <= 1) +ORDER BY ctx, r; +---- +ctx | id | r +a | 2 | 1 +a | 3 | 2 +a | 4 | 3 +b | 6 | 1 + +# That index is newest first and does not serve oldest first: the rows are sorted, and the +# answer is the same as an index would give. +WITH ranked AS ( + SELECT ctx, id, ROW_NUMBER() OVER (PARTITION BY ctx ORDER BY at ASC, id ASC) AS r FROM sessions +) +SELECT ctx, id, r FROM ranked WHERE ctx = 'a' AND r <= 2 ORDER BY r; +---- +ctx | id | r +a | 1 | 1 +a | 4 | 2 + +# Without PARTITION BY the whole input is one partition. +SELECT id, ROW_NUMBER() OVER (ORDER BY at DESC, id ASC) AS r FROM sessions ORDER BY r LIMIT 3; +---- +id | r +2 | 1 +3 | 2 +4 | 3 + +# Every other window form is refused by name: no ORDER BY, another function, an aggregate. +SELECT id, ROW_NUMBER() OVER (PARTITION BY ctx) AS r FROM sessions; +---- +error: WindowFunctionNotSupported + +SELECT id, RANK() OVER (ORDER BY at) AS r FROM sessions; +---- +error: WindowFunctionNotSupported + +SELECT id, SUM(at) OVER (PARTITION BY ctx ORDER BY at) AS total FROM sessions; +---- +error: WindowFunctionNotSupported + +# A bound written < stops one number sooner than <=. +WITH ranked AS ( + SELECT ctx, id, ROW_NUMBER() OVER (PARTITION BY ctx ORDER BY at DESC, id ASC) AS r + FROM sessions +) +SELECT id, r FROM ranked WHERE ctx = 'a' AND r < 3 ORDER BY r; +---- +id | r +2 | 1 +3 | 2 + +# Two alternatives that name one partition: the larger bound is the one that holds. +WITH ranked AS ( + SELECT ctx, id, ROW_NUMBER() OVER (PARTITION BY ctx ORDER BY at DESC, id ASC) AS r + FROM sessions +) +SELECT id, r FROM ranked WHERE (ctx = 'a' AND r <= 1) OR (ctx = 'a' AND r <= 2) ORDER BY r; +---- +id | r +2 | 1 +3 | 2 + +# One window to a SELECT, and a partition or an order that is a column and nothing computed. +SELECT ROW_NUMBER() OVER (ORDER BY at) AS x, ROW_NUMBER() OVER (ORDER BY id) AS y FROM sessions; +---- +error: WindowFunctionNotSupported + +SELECT ROW_NUMBER() OVER (PARTITION BY ctx ORDER BY at + 1) FROM sessions; +---- +error: WindowFunctionNotSupported + +# Two OR branches that name one partition in two spellings are one partition. +CREATE TABLE spots (id INTEGER PRIMARY KEY, grp REAL, who UUID); +CREATE INDEX spots_grp ON spots (grp, id); +CREATE INDEX spots_who ON spots (who, id); +INSERT INTO spots (id, grp, who) VALUES (1, 1.0, '0000000a-0000-0000-0000-00000000000a'), (2, 1.0, '0000000a-0000-0000-0000-00000000000a'); +WITH w AS (SELECT id, grp, ROW_NUMBER() OVER (PARTITION BY grp ORDER BY id) AS rn FROM spots) +SELECT id, rn FROM w WHERE (grp = 1 AND rn <= 1) OR (grp = 1.0 AND rn <= 2) ORDER BY id; +---- +id | rn +1 | 1 +2 | 2 + +WITH w AS (SELECT id, who, ROW_NUMBER() OVER (PARTITION BY who ORDER BY id) AS rn FROM spots) +SELECT id, rn FROM w WHERE (who = '0000000A-0000-0000-0000-00000000000A' AND rn <= 1) OR (who = '0000000a-0000-0000-0000-00000000000a' AND rn <= 2) ORDER BY id; +---- +id | rn +1 | 1 +2 | 2 diff --git a/v2/contextdb/tests/store.rs b/v2/contextdb/tests/store.rs index a8af7d68d..c20a8ef0f 100644 --- a/v2/contextdb/tests/store.rs +++ b/v2/contextdb/tests/store.rs @@ -22,10 +22,7 @@ fn a_fresh_store_is_one_folder_and_works_with_no_configuration() { other => panic!("a fresh store answered {other:?} when asked for a table"), } - support::run( - &db, - "CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT)", - ); + support::run(&db, support::NOTES); assert_eq!(db.table_names(), ["notes"]); db.execute( "INSERT INTO notes (id, body) VALUES ($id, $body)", @@ -49,9 +46,7 @@ fn what_was_committed_is_there_after_close_and_reopen() { let db = support::open(&folder); support::declare(&db); support::insert(&db, 1..=20); - let tx = db.transaction().expect("begin"); - support::insert(&tx, 21..=40); - tx.commit().expect("commit"); + support::insert_together(&db, 21..=40); support::run(&db, "DELETE FROM t WHERE id > 35"); support::close(db); @@ -62,6 +57,23 @@ fn what_was_committed_is_there_after_close_and_reopen() { support::insert(&db, 36..=36); support::close(db); support::assert_rows_are(&support::open(&folder), 1..=36); + + // A handle closed here refuses by name, a second close is allowed. + let db = support::open(&folder); + let tx = db.transaction().expect("begin"); + db.close().expect("close"); + db.close().expect("close a second time"); + let select = "SELECT id FROM t"; + assert!(matches!( + support::refusal(&db, select), + Error::DatabaseClosed + )); + assert!(matches!( + support::refusal(&tx, select), + Error::DatabaseClosed + )); + assert!(matches!(tx.commit(), Err(Error::DatabaseClosed))); + assert!(matches!(db.transaction(), Err(Error::DatabaseClosed))); } #[test] @@ -84,17 +96,29 @@ fn a_second_writer_is_refused_at_once_naming_the_holder_and_the_next_open_needs_ // The holder is waiting for a line and will not let go, so an open that returns at all has // not waited for it. Refused twice: a refused open takes nothing away from the holder. for _ in 0..2 { - match support::open_with(&folder, DatabaseOpenOptions::default()) { - Err(Error::DatabaseLocked { holder_pid, path }) => { + let Err(refusal) = support::open_with(&folder, DatabaseOpenOptions::default()) else { + panic!("a second writer was let in beside the first"); + }; + let said = refusal.to_string(); + match refusal { + Error::DatabaseLocked { holder_pid, path } => { assert_eq!( holder_pid, holder.id(), "the refusal names the process that holds it" ); assert_eq!(path, folder, "the refusal names the store"); + assert_eq!( + said, + format!( + "another session holds this store for writing: process {holder_pid} \ + holds {}; open a read session to read it", + folder.display() + ), + "the refusal names the holder, the path and how to read" + ); } - Err(other) => panic!("a second writer was refused as {other:?}"), - Ok(_) => panic!("a second writer was let in beside the first"), + other => panic!("a second writer was refused as {other:?}"), } } holder.tell("commit"); @@ -207,7 +231,7 @@ fn a_store_closed_here_opens_again_while_a_child_process_holds_a_copy_of_its_loc #[test] fn a_grouping_is_there_after_close_and_reopen() { - let (folder, db) = support::built("grouping-after-reopen", 16, "AUTO_INDEX_AT 1000", 2000); + let (folder, db) = support::built("grouping-after-reopen", 16, "INDEXING_THRESHOLD 1000", 2000); let query = support::gathered(99_000, 16); let sql = support::by_mode(None, "INDEXED", 10); // The partitions as inspection lists them, and an indexed search's rows and work. diff --git a/v2/contextdb/tests/support/mod.rs b/v2/contextdb/tests/support/mod.rs index 9d6f6f385..fbd841f62 100644 --- a/v2/contextdb/tests/support/mod.rs +++ b/v2/contextdb/tests/support/mod.rs @@ -8,7 +8,7 @@ // Each test program uses a part of this module; the rest would be reported as never used. #![allow(dead_code)] -use std::collections::{BTreeMap, HashMap}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::fmt; use std::fs::{self, File}; use std::io::{self, BufRead, BufReader, Write}; @@ -24,8 +24,8 @@ use std::sync::mpsc::{self, Receiver, RecvTimeoutError}; use std::time::Duration; use contextdb::{ - Database, DatabaseOpenOptions, Error, QueryResult, ReadSession, StorageBackend, Transaction, - Value, WrapStorage, params, + ContextId, Database, DatabaseOpenOptions, Error, QueryResult, ReadSession, ReadSessionOptions, + ScopeLabel, StorageBackend, Transaction, Uuid, Value, WrapStorage, params, }; // ---- folders and opening ---- @@ -73,6 +73,30 @@ pub fn close(db: Database) { db.close().expect("close the store"); } +/// Closes a store and opens it again with no configuration. +pub fn reopen(db: Database, folder: &Path) -> Database { + close(db); + open(folder) +} + +/// Opens a store for writing under a memory limit of this many bytes. It must open. +pub fn open_limited(folder: &Path, limit: usize) -> Database { + let mut options = DatabaseOpenOptions::default(); + options.memory_limit = Some(limit); + open_with(folder, options).unwrap_or_else(|error| { + panic!("an open under a limit of {limit} bytes was refused: {error:?}") + }) +} + +/// Opens a store for reading, under a memory limit when one is given. It must open. +pub fn open_reader(folder: &Path, limit: Option) -> ReadSession { + let mut options = ReadSessionOptions::default(); + options.memory_limit = limit; + ReadSession::open_with_options(folder, options).unwrap_or_else(|error| { + panic!("a reader under a limit of {limit:?} was refused: {error:?}") + }) +} + // ---- statements ---- /// Whatever runs a statement: the writer, one of its transactions, or a reader. @@ -138,6 +162,114 @@ pub fn refusal(on: &impl Run, sql: &str) -> Error { } } +/// One column of what `SHOW MEMORY_LIMIT` reports. +pub fn memory_shown(on: &impl Run, column: &str) -> Value { + let report = run(on, "SHOW MEMORY_LIMIT"); + let at = report + .columns() + .iter() + .position(|name| name == column) + .unwrap_or_else(|| panic!("SHOW MEMORY_LIMIT has no column {column}")); + match report.rows() { + [row] => row[at].clone(), + rows => panic!("SHOW MEMORY_LIMIT returned {} rows", rows.len()), + } +} + +/// The bytes `SHOW MEMORY_LIMIT` reports as used. +pub fn memory_used(on: &impl Run) -> usize { + match memory_shown(on, "used") { + Value::Int64(bytes) => bytes as usize, + other => panic!("SHOW MEMORY_LIMIT reports {other:?} as used"), + } +} + +/// The first column of every row a statement returns, which must be an INTEGER. +pub fn ids(on: &impl Run, sql: &str) -> Vec { + rows(on, sql) + .iter() + .map(|row| match row.first() { + Some(Value::Int64(id)) => *id, + other => panic!("{sql}\nreturned {other:?} where an INTEGER was wanted"), + }) + .collect() +} + +/// What a table is printed back as. +pub fn printed(db: &Database, table: &str) -> String { + db.declaration(table) + .unwrap_or_else(|error| panic!("the declaration of {table} was refused: {error:?}")) +} + +/// Asserts that what these tables are printed back as declares the same tables in an empty +/// store (made under `prefix`), printed the same. The tables are named in the order they may be +/// declared in. Gives back the printed texts, in that order. +pub fn assert_roundtrips(prefix: &str, db: &Database, tables: &[&str]) -> Vec { + let texts: Vec = tables.iter().map(|table| printed(db, table)).collect(); + let again = open(&folder(&format!("{prefix}-again"))); + for text in &texts { + for statement in text.split_inclusive(";\n") { + run(&again, statement); + } + } + for (table, text) in tables.iter().zip(&texts) { + let declared = again.declaration(table).expect("the declaration"); + assert_eq!( + &declared, text, + "{prefix}: {table} declared from its printed text" + ); + } + texts +} + +// ---- who is asking ---- + +/// Context number `n`. +pub fn context(n: u128) -> Uuid { + Uuid::from_u128(0x00C0_0000 + n) +} + +/// Access-control id number `n`. +pub fn acl(n: u128) -> Uuid { + Uuid::from_u128(0x00AC_0000 + n) +} + +/// A handle narrowed to the Contexts with these numbers. +pub fn in_contexts(db: &Database, numbers: &[u128]) -> Database { + db.scoped_with_contexts(context_set(numbers)) +} + +/// The length of the store's data file, in bytes. +pub fn data_file(folder: &Path) -> u64 { + fs::metadata(folder.join("data")) + .expect("the store's data file") + .len() +} + +/// The keys of a search's answer, in its order; each must be an INTEGER. +pub fn near_ids(answer: &[Near]) -> Vec { + answer + .iter() + .map(|near| match near.key { + Value::Int64(id) => id, + ref other => panic!("the key {other:?} is not an INTEGER"), + }) + .collect() +} + +/// The Contexts with these numbers. +pub fn context_set(numbers: &[u128]) -> BTreeSet { + numbers + .iter() + .map(|n| ContextId::new(context(*n))) + .collect() +} + +/// The scope labels with these names. +pub fn label_set(names: &[&str]) -> BTreeSet { + names.iter().map(|name| ScopeLabel::new(*name)).collect() +} + // ---- the table most tests use ---- /// Row `n` of this table is `(n, "row-000000n", n % 10)`: see [`row`]. @@ -180,6 +312,13 @@ pub fn insert(on: &impl Run, numbers: impl IntoIterator) { } } +/// Inserts the rows with these numbers in one transaction and commits it. +pub fn insert_together(db: &Database, numbers: impl IntoIterator) { + let tx = db.transaction().expect("begin"); + insert(&tx, numbers); + tx.commit().expect("commit"); +} + /// Asserts that the table holds exactly the rows with these numbers, each one whole, and that /// the kept count and the index say the same as the rows. pub fn assert_rows_are(on: &impl Run, numbers: RangeInclusive) { @@ -697,6 +836,55 @@ pub fn insert_docs( } } +/// The words of a declaration in lower case and its quoted texts as they are written: what the +/// declaration says, whatever the order, the spacing and the punctuation it says it in. A type +/// is given the name it is printed under, and a quoted name that needs no quotes loses them. +pub fn words(sql: &str) -> Vec { + let mut found = Vec::new(); + let mut rest = sql.chars().peekable(); + while let Some(first) = rest.next() { + if first == '\'' || first == '"' { + let mut text = String::from(first); + loop { + let next = rest.next().expect("a quoted text ends with its quote"); + text.push(next); + // The quote written twice is one quote of the text. + if next == first && rest.next_if_eq(&first).is_none() { + break; + } + } + let inner = &text[1..text.len() - 1]; + let plain = first == '"' + && inner.starts_with(|c: char| c.is_ascii_lowercase() || c == '_') + && inner + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'); + found.push(if plain { inner.to_owned() } else { text }); + } else if first.is_ascii_alphanumeric() || first == '_' { + let mut word = String::from(first.to_ascii_lowercase()); + while let Some(next) = + rest.next_if(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '.') + { + word.push(next.to_ascii_lowercase()); + } + match word.as_str() { + "int" => found.push("integer".to_owned()), + "bool" => found.push("boolean".to_owned()), + "float" => found.push("real".to_owned()), + "state_machine" => found.extend(["state".to_owned(), "machine".to_owned()]), + _ => found.push(word), + } + } + } + found +} + +/// The index of `events` by kind and then newest first. +pub const EVENTS_INDEX: &str = "CREATE INDEX events_kind_seq ON events (kind ASC, seq DESC)"; + +/// A table of notes, each a key and a body. +pub const NOTES: &str = "CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT)"; + /// A text value, for comparing with a column of a stored row. pub fn text(value: &str) -> Value { Value::Text(value.to_owned()) @@ -1017,6 +1205,17 @@ impl StorageBackend for Watched { } } +/// The child's store opened for reading through [`pausing_at_read`]'s door, with its flag and +/// count. +pub fn reader_pausing(role: &Role) -> (ReadSession, Arc, Arc) { + let (door, searching, reads) = pausing_at_read(role.number("pause_at")); + let mut options = ReadSessionOptions::default(); + options.storage = Some(door); + let reader = + ReadSession::open_with_options(&role.folder, options).expect("open the store for reading"); + (reader, searching, reads) +} + /// A storage door for a child that is to be stopped inside one statement. While the flag it /// returns is set it counts the reads of the data file, and at read number `pause_at` it /// announces `reading` and waits for a line from the parent; `pause_at` 0 never stops. Returns diff --git a/v2/contextdb/tests/table_source.rs b/v2/contextdb/tests/table_source.rs index 26a333ec4..4573c4dbc 100644 --- a/v2/contextdb/tests/table_source.rs +++ b/v2/contextdb/tests/table_source.rs @@ -4,16 +4,14 @@ mod support; -use std::collections::BTreeSet; +use contextdb::{Error, Principal, Value, params}; -use contextdb::{ContextId, Error, Principal, ScopeLabel, Uuid, Value, params}; +use support::{acl, context, context_set, label_set}; #[test] fn a_narrowed_reader_naming_a_hidden_row_by_its_key_is_refused_by_the_rule_that_hid_it() { let folder = support::folder("table-source-hidden-row-by-key"); let db = support::open(&folder); - let context = |n: u128| Uuid::from_u128(0x00C0_0000 + n); - let acl = |n: u128| Uuid::from_u128(0x00AC_0000 + n); // Row 1 of each table is in the reader's view and row 2 is hidden by the table's rule. support::run( @@ -60,8 +58,7 @@ fn a_narrowed_reader_naming_a_hidden_row_by_its_key_is_refused_by_the_rule_that_ ) .expect("grant access id 1"); - let contexts: BTreeSet = [ContextId::new(context(1))].into(); - let labels: BTreeSet = [ScopeLabel::new("public")].into(); + let (contexts, labels) = (context_set(&[1]), label_set(&["public"])); let agent = Principal::Agent("a".to_owned()); let in_one = db.scoped_with_constraints(Some(contexts), None, None); let public = db.scoped_with_constraints(None, Some(labels), None); diff --git a/v2/contextdb/tests/transaction_numbers.rs b/v2/contextdb/tests/transaction_numbers.rs index c0b27a437..6cf386c2b 100644 --- a/v2/contextdb/tests/transaction_numbers.rs +++ b/v2/contextdb/tests/transaction_numbers.rs @@ -207,3 +207,34 @@ fn a_vector_column_is_partitioned_by_the_number_of_the_transaction_that_wrote_th assert_eq!(ids, (first..first + 5).collect::>()); } } + +#[test] +fn a_position_and_a_row_of_every_kind_of_value_survive_json() { + use contextdb::{ + Uuid, + serde_json::{self, json}, + }; + assert_eq!( + serde_json::to_string(&TxId(7)).unwrap(), + "7", + "a position is its bare number" + ); + let row = vec![ + Value::Null, + Value::Bool(true), + Value::Int64(-3), + Value::Float64(1.5), + Value::Text("t".into()), + Value::Uuid(Uuid::from_u128(9)), + Value::Timestamp(5), + Value::Json(json!({"k": [1, null]})), + Value::Vector(vec![0.5, 1.0]), + Value::TxId(TxId(7)), + ]; + let text = serde_json::to_string(&row).unwrap(); + assert_eq!( + serde_json::from_str::>(&text).unwrap(), + row, + "a host reads back what it saved: {text}" + ); +} diff --git a/v2/contextdb/tests/transactions.rs b/v2/contextdb/tests/transactions.rs index fd0985107..9336feff8 100644 --- a/v2/contextdb/tests/transactions.rs +++ b/v2/contextdb/tests/transactions.rs @@ -85,9 +85,7 @@ fn a_transaction_sees_its_own_writes_and_a_dropped_or_rolled_back_one_leaves_not ); // A transaction that commits something does reach the file, so the count above means it. - let tx = db.transaction().expect("begin"); - support::insert(&tx, 2..=3); - tx.commit().expect("commit"); + support::insert_together(&db, 2..=3); assert!( written.load(Ordering::SeqCst) > before, "a commit did not reach the file" @@ -525,6 +523,39 @@ fn a_transaction_that_declares_a_table_may_not_also_write_rows() { support::refusal(&db, "SELECT tag FROM t"), Error::ColumnNotFound { .. } )); + + // Declarations overtaken by another commit: of three transactions begun from the same + // tables, two that declare different tables commit and one that declares a name taken + // meanwhile is refused; a row staged before an index was declared is refused, not + // committed without its entry; an index declared while a row commits has that row. + let db = support::open(&support::folder("declarations-overtaken")); + support::declare(&db); + support::insert(&db, 1..=1); + let declaring = [ + "CREATE TABLE a (id INTEGER PRIMARY KEY)", + "CREATE TABLE b (id INTEGER PRIMARY KEY)", + "CREATE TABLE a (id INTEGER PRIMARY KEY, more TEXT)", + ]; + let [first, second, third] = declaring.map(|sql| { + let tx = db.transaction().expect("begin"); + support::run(&tx, sql); + tx + }); + first.commit().expect("the first declaration commits"); + second.commit().expect("a table of another name commits"); + assert!(matches!(third.commit(), Err(Error::SchemaInvalid { .. }))); + assert_eq!(db.table_names(), ["a", "b", "t"]); + let tx = db.transaction().expect("begin"); + support::insert(&tx, 2..=2); + support::run(&db, "CREATE INDEX t_early ON t (name)"); + assert!(matches!(tx.commit(), Err(Error::SchemaInvalid { .. }))); + support::assert_rows_are(&db, 1..=1); + let tx = db.transaction().expect("begin"); + support::run(&tx, "CREATE INDEX t_by_name ON t (name)"); + support::insert(&db, 2..=2); + tx.commit().expect("commit the index"); + let named = "SELECT id FROM t WHERE name = 'row-0000002'"; + assert_eq!(support::rows(&db, named), [[Value::Int64(2)]]); } #[test] @@ -532,13 +563,12 @@ fn a_statement_commits_while_a_cycle_works_out_a_step() { use std::sync::Mutex; use std::sync::atomic::AtomicBool; use std::sync::mpsc; - use std::time::Duration; // 2,000 sealed vectors of 256 numbers in three blocks, and their build begun. const DIMENSION: usize = 256; let folder = support::folder("commit-beside-a-step"); let db = support::open(&folder); - support::declare_docs(&db, DIMENSION, "AUTO_INDEX_AT 1000"); + support::declare_docs(&db, DIMENSION, "INDEXING_THRESHOLD 1000"); support::load_docs(&db, 1..=2000, "a", |n| support::gathered(n, DIMENSION)); let report = support::cycle(&db); assert_eq!( @@ -548,18 +578,19 @@ fn a_statement_commits_while_a_cycle_works_out_a_step() { support::close(db); // The storage door holds the first read of 64 KiB or more made once it is armed: a block - // read by the step the cycle works out. It says so, and waits to be let go. + // read by the step the cycle works out. It says so, and waits to be let go. The cycle and + // the INSERT say when they finish, so each wait below is answered by what happened first. let armed = Arc::new(AtomicBool::new(false)); - let (holding, held) = mpsc::channel::<()>(); + let (said, heard) = mpsc::channel::<&str>(); let (let_go, go) = mpsc::channel::<()>(); let go = Mutex::new(go); let mut options = DatabaseOpenOptions::default(); options.storage = Some(support::storage({ - let armed = armed.clone(); + let (armed, said) = (armed.clone(), said.clone()); move |call| { let large = matches!(&call, Call::Read(_, bytes) if bytes.len() >= 64 << 10); if large && armed.swap(false, Ordering::SeqCst) { - holding.send(()).expect("the test listens"); + said.send("held").expect("the test listens"); let go = go.lock().expect("one read is held"); go.recv().expect("the test lets the read go"); } @@ -570,27 +601,36 @@ fn a_statement_commits_while_a_cycle_works_out_a_step() { armed.store(true, Ordering::SeqCst); let db = &db; - let (inserted, in_time, cycled) = std::thread::scope(|scope| { - let cycle = scope.spawn(|| db.run_maintenance_cycle()); - held.recv_timeout(Duration::from_secs(20)) - .expect("a step of the build reads a block"); + let (inserted, cycled) = std::thread::scope(|scope| { + let cycle = scope.spawn({ + let said = said.clone(); + move || { + let cycled = db.run_maintenance_cycle(); + said.send("cycle").expect("the test listens"); + cycled + } + }); + assert_eq!( + heard.recv(), + Ok("held"), + "a step of the build reads a block" + ); // The cycle is inside its step. An INSERT on another thread returns while it is. - let (done, returned) = mpsc::channel::<()>(); let insert = scope.spawn(move || { let row = support::gathered(9001, DIMENSION); let outcome = support::insert_doc(db, 9001, "a", Some(row)); - done.send(()).expect("the test listens"); + said.send("insert").expect("the test listens"); outcome.map(|_| db.committed_watermark()) }); - let in_time = returned.recv_timeout(Duration::from_secs(20)).is_ok(); + assert_eq!( + heard.recv(), + Ok("insert"), + "the INSERT returned while the step was held" + ); let_go.send(()).expect("the held read listens"); let inserted = insert.join().expect("the thread of the INSERT"); - (inserted, in_time, cycle.join().expect("the cycle's thread")) + (inserted, cycle.join().expect("the cycle's thread")) }); - assert!( - in_time, - "the INSERT waited for the step the cycle was working out" - ); let after = inserted.expect("an INSERT beside a cycle"); assert!(after > before, "the INSERT committed"); cycled.expect("the cycle whose read was held"); diff --git a/v2/contextdb/tests/vectors.rs b/v2/contextdb/tests/vectors.rs index e18aac431..f1cda81e8 100644 --- a/v2/contextdb/tests/vectors.rs +++ b/v2/contextdb/tests/vectors.rs @@ -10,20 +10,9 @@ mod support; use std::collections::BTreeMap; -use contextdb::{Database, ReadSession, Value, params}; - -use support::{Near, Run}; - -/// The keys of an answer, in its order. -fn ids(answer: &[Near]) -> Vec { - answer - .iter() - .map(|near| match near.key { - Value::Int64(id) => id, - ref other => panic!("the key {other:?} is not an INTEGER"), - }) - .collect() -} +use contextdb::{Database, Value, params}; + +use support::{Near, Run, near_ids as ids}; /// Changes the vector of one row of `docs`, or takes it away for `None`. fn set_vector(on: &impl Run, id: i64, vector: Option>) { @@ -134,10 +123,9 @@ fn exact_search_returns_the_true_nearest_vectors() { through(&db, "after one cycle"); support::seal_all(&db); through(&db, "after the last cycle"); - support::close(db); - let db = support::open(&folder); + let db = support::reopen(db, &folder); through(&db, "after close and reopen"); - let reader = ReadSession::open(&folder).expect("open the store for reading"); + let reader = support::open_reader(&folder, None); through(&reader, "through a read session"); } } @@ -251,8 +239,7 @@ fn exact_search_rescores_from_stored_vectors() { // The same after everything pending is sealed, and after the store is opened again. support::seal_all(&db); - support::close(db); - let db = support::open(&folder); + let db = support::reopen(db, &folder); let stored = support::stored(&db, support::DOCS); for query in left_behind.iter().rev().take(20) { for k in [1, 10, 1000] { @@ -284,7 +271,7 @@ fn exact_search_reads_its_own_snapshot() { let query = support::vector(7, DIMENSION); let doubled: Vec = query.iter().map(|number| number * 2.0).collect(); set_vector(&db, 160, Some(doubled)); - let reader = ReadSession::open(&folder).expect("open the store for reading"); + let reader = support::open_reader(&folder, None); // Holds a search over every partition, and over each one, to the rows `on` itself reads. fn agrees(on: &impl Run, query: &[f32], what: &str) -> Vec { @@ -799,7 +786,7 @@ fn a_search_that_has_to_look_twice_returns_the_true_nearest() { let wanted = stored.nearest(not_near, &AHEAD, 10); assert_eq!(ids(&wanted), (11..=20).collect::>()); through(&db, &stored, "near rows filtered out, ten rows pending"); - let reader = ReadSession::open(&folder).expect("open the store for reading"); + let reader = support::open_reader(&folder, None); through(&reader, &stored, "the same through a read session"); // The same without a filter once the near rows are deleted: their slots stay in the block, @@ -881,7 +868,7 @@ fn a_row_two_entries_lead_to_is_in_the_answer_once_and_pushes_no_row_out() { set_vector(&db, 30, Some(toward(0.86, 3))); let (answer, _) = nearest_ten(&db, "row 30 pending with a slot of its earlier vector"); assert_eq!(answer, [41, 42, 30, 43, 44, 45, 46, 47, 48, 49]); - let reader = ReadSession::open(&folder).expect("open the store for reading"); + let reader = support::open_reader(&folder, None); nearest_ten(&reader, "the same through a read session"); // Two slots of one vector, one of them left behind. Rows 1 to 8, row 20, row 50 and diff --git a/v2/contextdb/tests/vectors_index.rs b/v2/contextdb/tests/vectors_index.rs index f8b85f488..3ff33089e 100644 --- a/v2/contextdb/tests/vectors_index.rs +++ b/v2/contextdb/tests/vectors_index.rs @@ -1,5 +1,5 @@ //! The index of a VECTOR column: a partition of a column that is large enough is cut into -//! groups, and a search under INDEXED, or under AUTO from `AUTO_INDEX_AT` vectors on, looks at +//! groups, and a search under INDEXED, or under AUTO from `INDEXING_THRESHOLD` vectors on, looks at //! the nearest groups first. Every row it returns has its true distance; a column below its //! size is searched whole and pays nothing; and INDEXED is refused by name where the index //! cannot serve the statement. @@ -8,6 +8,7 @@ mod support; use std::collections::BTreeSet; use std::io; +use std::path::Path; use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering}; @@ -18,7 +19,7 @@ use contextdb::{ const DIMENSION: usize = 16; /// The clause under which a partition of 2,000 rows is cut into groups. -const GROUPED: &str = "AUTO_INDEX_AT 1000"; +const GROUPED: &str = "INDEXING_THRESHOLD 1000"; /// Question `j`: a vector near one of the eight directions the rows are scattered around. fn question(j: i64) -> Vec { @@ -69,23 +70,17 @@ fn an_indexed_search_reads_sketches_before_blocks() { const ROWS: i64 = 256; let folder = support::folder("indexed-reads-sketches"); let db = support::open(&folder); - support::declare_docs(&db, WIDE, "AUTO_INDEX_AT 256"); + support::declare_docs(&db, WIDE, "INDEXING_THRESHOLD 256"); support::load_docs(&db, 1..=ROWS, "a", |n| support::ringed(n, ROWS, WIDE)); support::upkeep(&db); assert_eq!(lists(&support::the_partition(&db)), Value::Int64(16)); support::close(db); - // Each search runs first in a session of its own, so every page it needs is read once. let query = support::ringed(157, 2 * ROWS, WIDE); let read_by = |mode: &str| -> u64 { - let (door, bytes) = support::counting_bytes_read(); - let mut options = ReadSessionOptions::default(); - options.storage = Some(door); - let reader = ReadSession::open_with_options(&folder, options).expect("open for reading"); - let opened = bytes.load(Ordering::SeqCst); - let result = support::answer(&reader, &support::by_mode(None, mode, 10), &query); - assert_eq!(result.rows().len(), 10, "rows under {mode}"); - bytes.load(Ordering::SeqCst) - opened + let (bytes, result) = read_alone(&folder, &support::by_mode(None, mode, 10), &query); + assert_eq!(result.expect(mode).rows().len(), 10, "rows under {mode}"); + bytes }; // EXACT reads every block. INDEXED reads what EXACT does not, the centres and the // sketches, and still reads less: it left blocks unread. @@ -211,12 +206,12 @@ fn refused_whole_while_one_partition_is_behind(name: &str, clauses: &str, indexe fn indexed_is_refused_whole_when_one_partition_is_behind() { refused_whole_while_one_partition_is_behind( "behind-use-vector", - "PARTITION_KEY (ctx) AUTO_INDEX_AT 1000", + "PARTITION_KEY (ctx) INDEXING_THRESHOLD 1000", "INDEXED", ); refused_whole_while_one_partition_is_behind( "behind-declared", - "PARTITION_KEY (ctx) SEARCH_MODE INDEXED AUTO_INDEX_AT 1000", + "PARTITION_KEY (ctx) SEARCH_MODE INDEXED INDEXING_THRESHOLD 1000", "", ); } @@ -231,10 +226,10 @@ fn auto_and_exact( } #[test] -fn auto_uses_groupings_from_auto_index_at_on() { - // Two built partitions of 1,200 under AUTO_INDEX_AT 2000: the count is over the selected +fn auto_uses_groupings_from_indexing_threshold_on() { + // Two built partitions of 1,200 under INDEXING_THRESHOLD 2000: the count is over the selected // partitions together. - let clauses = "PARTITION_KEY (ctx) AUTO_INDEX_AT 2000"; + let clauses = "PARTITION_KEY (ctx) INDEXING_THRESHOLD 2000"; let (_, db) = support::built("auto-threshold", DIMENSION, clauses, 1200); support::load_docs(&db, 1201..=2400, "b", gathered); support::upkeep(&db); @@ -261,12 +256,12 @@ fn auto_uses_groupings_from_auto_index_at_on() { ); // A column below its declared size stays ungrouped however many cycles run: 1,000 rows - // under AUTO_INDEX_AT 50000 are not 50,000, though one partition holds a hundredth of it. + // under INDEXING_THRESHOLD 50000 are not 50,000, though one partition holds a hundredth of it. let index_bytes = |db: &contextdb::Database| { let index = support::shown(db, "SHOW VECTOR_INDEXES").remove(0); support::whole(&index, "durable_index_bytes") }; - let clauses = "PARTITION_KEY (ctx) AUTO_INDEX_AT 50000"; + let clauses = "PARTITION_KEY (ctx) INDEXING_THRESHOLD 50000"; let (_, db) = support::built("auto-below-declared", DIMENSION, clauses, 400); support::load_docs(&db, 401..=1000, "b", gathered); for _ in 0..3 { @@ -279,15 +274,18 @@ fn auto_uses_groupings_from_auto_index_at_on() { assert_eq!(grouped, [Value::Null, Value::Null]); assert_eq!(index_bytes(&db), 0); - // With no AUTO_INDEX_AT the number in force is 100,000: a partition of 1,200 stays + // With no INDEXING_THRESHOLD the number in force is 100,000: a partition of 1,200 stays // ungrouped, and AUTO over it is EXACT. let (_, db) = support::built("auto-undeclared", DIMENSION, "", 1200); let index = support::shown(&db, "SHOW VECTOR_INDEXES").remove(0); assert_eq!( - support::field(&index, "declared_auto_index_at"), + support::field(&index, "declared_indexing_threshold"), &Value::Null ); - assert_eq!(support::whole(&index, "effective_auto_index_at"), 100_000); + assert_eq!( + support::whole(&index, "effective_indexing_threshold"), + 100_000 + ); assert_eq!(lists(&support::the_partition(&db)), Value::Null); assert_eq!(index_bytes(&db), 0); let [auto, exact] = auto_and_exact(&db, None, &query); @@ -300,7 +298,7 @@ fn auto_uses_groupings_from_auto_index_at_on() { #[test] fn auto_searches_each_partition_by_what_its_grouping_saves() { - let clauses = "PARTITION_KEY (ctx) AUTO_INDEX_AT 1000"; + let clauses = "PARTITION_KEY (ctx) INDEXING_THRESHOLD 1000"; let (_, db) = support::built("auto-each-partition", DIMENSION, clauses, 2000); // Five pending rows under another context, nearer the question than any row of the first. let query = question(3); @@ -447,7 +445,7 @@ fn a_search_with_a_filter_on_rows_widens_until_it_is_whole() { let every = search(&db, None, "INDEXED", 5000).expect("every row"); support::assert_sound(&every, &stored, all, &query, 2000, "a LIMIT above the rows"); - let clauses = "SEARCH_MODE INDEXED AUTO_INDEX_AT 1000"; + let clauses = "SEARCH_MODE INDEXED INDEXING_THRESHOLD 1000"; let (_, declared) = support::built("filter-widens-declared", DIMENSION, clauses, 2000); support::assert_indexed_refused(search(&declared, few, "", 10), "SEARCH_MODE INDEXED"); } @@ -545,7 +543,7 @@ fn an_indexed_search_short_of_its_limit_is_refused_before_the_whole_table_is_rea const ROWS: i64 = 256; let folder = support::folder("indexed-refused-before-the-table"); let db = support::open(&folder); - support::declare_docs(&db, WIDE, "AUTO_INDEX_AT 256"); + support::declare_docs(&db, WIDE, "INDEXING_THRESHOLD 256"); support::load_docs(&db, 1..=ROWS, "a", |n| support::ringed(n, ROWS, WIDE)); support::upkeep(&db); assert_eq!(lists(&support::the_partition(&db)), Value::Int64(16)); @@ -558,16 +556,7 @@ fn an_indexed_search_short_of_its_limit_is_refused_before_the_whole_table_is_rea let query = support::ringed(157, 2 * ROWS, WIDE); let wanted = stored.nearest(passes, &query, 10); assert_eq!(wanted.len(), 3); - // Each search runs first in a session of its own, so every page it needs is read once. - let read_by = |mode: &str| -> (u64, contextdb::Result) { - let (door, bytes) = support::counting_bytes_read(); - let mut options = ReadSessionOptions::default(); - options.storage = Some(door); - let reader = ReadSession::open_with_options(&folder, options).expect("open for reading"); - let opened = bytes.load(Ordering::SeqCst); - let outcome = support::search(&reader, &support::by_mode(few, mode, 10), &query); - (bytes.load(Ordering::SeqCst) - opened, outcome) - }; + let read_by = |mode: &str| read_alone(&folder, &support::by_mode(few, mode, 10), &query); // AUTO asks the filter of every row, which is the whole table's work, and answers. let (whole, auto) = read_by("AUTO"); let auto = auto.expect("AUTO, three rows pass"); @@ -586,6 +575,18 @@ fn an_indexed_search_short_of_its_limit_is_refused_before_the_whole_table_is_rea ); } +/// Runs a search in a read session of its own, so every page it needs is read once, and gives +/// the bytes of the data file it read and its answer. +fn read_alone(folder: &Path, sql: &str, query: &[f32]) -> (u64, contextdb::Result) { + let (door, bytes) = support::counting_bytes_read(); + let mut options = ReadSessionOptions::default(); + options.storage = Some(door); + let reader = ReadSession::open_with_options(folder, options).expect("open for reading"); + let opened = bytes.load(Ordering::SeqCst); + let outcome = support::search(&reader, sql, query); + (bytes.load(Ordering::SeqCst) - opened, outcome) +} + /// One store of [`a_nearer_allowed_row_in_a_group_taken_later_is_in_the_answer`], with row /// 507 at these two numbers. fn the_nearer_allowed_row_is_first(name: &str, nearer: (f32, f32)) { @@ -714,7 +715,7 @@ fn a_search_with_no_room_for_its_sketches_is_refused_by_the_memory_limit() { #[test] fn a_filter_of_partition_keys_only_is_no_filter_on_rows() { - let clauses = "PARTITION_KEY (ctx) AUTO_INDEX_AT 1000"; + let clauses = "PARTITION_KEY (ctx) INDEXING_THRESHOLD 1000"; let (_, db) = support::built("keys-only-filter", DIMENSION, clauses, 2000); support::load_docs(&db, 2001..=2005, "b", gathered); support::upkeep(&db); @@ -798,17 +799,8 @@ fn an_indexed_search_whose_first_pass_takes_every_slot_is_refused_before_a_row_i support::close(db); let query = support::vector(2, WIDE); - // Each search runs first in a session of its own, so every page it needs is read once. - let read_by = |mode: &str| -> (u64, contextdb::Result) { - let (door, bytes) = support::counting_bytes_read(); - let mut options = ReadSessionOptions::default(); - options.storage = Some(door); - let reader = ReadSession::open_with_options(&folder, options).expect("open for reading"); - let opened = bytes.load(Ordering::SeqCst); - let sql = support::by_mode(Some("tag = 1"), mode, 2); - let outcome = support::search(&reader, &sql, &query); - (bytes.load(Ordering::SeqCst) - opened, outcome) - }; + let read_by = + |mode: &str| read_alone(&folder, &support::by_mode(Some("tag = 1"), mode, 2), &query); let vector_bytes = 4 * WIDE as u64; let (asked, exact) = read_by("EXACT"); assert_eq!(exact.expect("EXACT, one row passes").rows().len(), 1); diff --git a/v2/contextdb/tests/vectors_inspection.rs b/v2/contextdb/tests/vectors_inspection.rs index 059f1003c..a96dc2885 100644 --- a/v2/contextdb/tests/vectors_inspection.rs +++ b/v2/contextdb/tests/vectors_inspection.rs @@ -27,7 +27,7 @@ fn assert_fields(row: &Shown, wanted: &[(&str, Value)], what: &str) { /// under `b`, which together bring the column to its declared size; and `plain.e`, with no /// key and no vector. fn two_columns(name: &str) -> (std::path::PathBuf, contextdb::Database) { - let clauses = "PARTITION_KEY (ctx) AUTO_INDEX_AT 1000 CONSOLIDATION (CHANGE_PERCENT = 50)"; + let clauses = "PARTITION_KEY (ctx) INDEXING_THRESHOLD 1000 COMPACTION (CHANGE_PERCENT = 50)"; let (folder, db) = support::built(name, 8, clauses, 0); support::run( &db, @@ -63,15 +63,15 @@ fn show_vector_indexes_describes_every_vector_column() { ("max_partitions", int(256)), ("live_partitions", int(2)), ("search_mode", text("AUTO")), - ("declared_auto_index_at", int(1000)), - ("effective_auto_index_at", int(1000)), - ("declared_consolidation_mode", text("PERCENT")), - ("declared_consolidation_change_percent", int(50)), - ("declared_consolidation_tombstone_percent", Value::Null), - ("effective_consolidation_mode", text("PERCENT")), - ("effective_consolidation_change_percent", int(50)), - ("effective_consolidation_tombstone_percent", int(10)), - ("pending_inserts", int(400)), + ("declared_indexing_threshold", int(1000)), + ("effective_indexing_threshold", int(1000)), + ("declared_compaction_mode", text("PERCENT")), + ("declared_compaction_change_percent", int(50)), + ("declared_compaction_tombstone_percent", Value::Null), + ("effective_compaction_mode", text("PERCENT")), + ("effective_compaction_change_percent", int(50)), + ("effective_compaction_tombstone_percent", int(10)), + ("pending_tuples", int(400)), ("tombstones", int(0)), ("durable_vector_bytes", int(600 * 16)), ("durable_index_bytes", int(0)), @@ -103,15 +103,15 @@ fn show_vector_indexes_describes_every_vector_column() { ("max_partitions", Value::Null), ("live_partitions", int(0)), ("search_mode", text("AUTO")), - ("declared_auto_index_at", Value::Null), - ("effective_auto_index_at", int(100_000)), - ("declared_consolidation_mode", Value::Null), - ("declared_consolidation_change_percent", Value::Null), - ("declared_consolidation_tombstone_percent", Value::Null), - ("effective_consolidation_mode", text("PERCENT")), - ("effective_consolidation_change_percent", int(20)), - ("effective_consolidation_tombstone_percent", int(10)), - ("pending_inserts", int(0)), + ("declared_indexing_threshold", Value::Null), + ("effective_indexing_threshold", int(100_000)), + ("declared_compaction_mode", Value::Null), + ("declared_compaction_change_percent", Value::Null), + ("declared_compaction_tombstone_percent", Value::Null), + ("effective_compaction_mode", text("PERCENT")), + ("effective_compaction_change_percent", int(20)), + ("effective_compaction_tombstone_percent", int(10)), + ("pending_tuples", int(0)), ("indexed_available", Value::Bool(true)), ("maintenance_state", text("idle")), ("maintenance_vectors_total", int(0)), @@ -173,6 +173,9 @@ fn show_vector_partitions_lists_partitions_by_key_with_limit_and_offset() { assert_eq!(keys("SHOW VECTOR_PARTITIONS LIMIT 5 OFFSET 2"), [plain]); assert_eq!(keys("SHOW VECTOR_PARTITIONS LIMIT 2"), [a, b]); assert_eq!(keys("SHOW VECTOR_PARTITIONS FOR plain.e"), [plain]); + // Any letter case reads, and LIMIT 0 gives no row. + assert_eq!(keys("show vector_partitions for docs.v limit 5"), [a, b]); + assert!(keys("SHOW VECTOR_PARTITIONS LIMIT 0").is_empty()); let rows = support::shown(&db, "SHOW VECTOR_PARTITIONS"); let text = support::text; @@ -181,14 +184,14 @@ fn show_vector_partitions_lists_partitions_by_key_with_limit_and_offset() { &rows[0], &[ ("live_rows", int(600)), - ("pending_inserts", int(0)), + ("pending_tuples", int(0)), ("tombstones", int(0)), ("durable_vector_bytes", int(600 * 16)), ("durable_index_bytes", int(0)), ("indexed_available", Value::Bool(true)), ("availability_reason", text("none")), ("maintenance_state", text("pending")), - ("maintenance_reason", text("first_grouping")), + ("maintenance_reason", text("unindexed")), ("maintenance_vectors_total", int(600)), ("maintenance_vectors_done", int(0)), ("maintenance_vectors_remaining", int(600)), @@ -202,7 +205,7 @@ fn show_vector_partitions_lists_partitions_by_key_with_limit_and_offset() { &rows[1], &[ ("live_rows", int(400)), - ("pending_inserts", int(400)), + ("pending_tuples", int(400)), ("durable_vector_bytes", int(0)), ("lists", Value::Null), ], @@ -213,7 +216,7 @@ fn show_vector_partitions_lists_partitions_by_key_with_limit_and_offset() { &rows[2], &[ ("live_rows", int(0)), - ("pending_inserts", int(0)), + ("pending_tuples", int(0)), ("tombstones", int(0)), ("durable_vector_bytes", int(0)), ("durable_index_bytes", int(0)), @@ -251,7 +254,13 @@ fn searched(filter: Option<&str>, mode: &str) -> String { fn inspection_and_explain_read_no_block_and_change_nothing() { // One block of 2,000 slots of 72 bytes with keys of 9: 170,004 bytes. const BLOCK: u64 = 4 + 2000 * (72 + 4 + 9); - let (folder, db) = support::built("inspection-reads-no-block", 64, "AUTO_INDEX_AT 1000", 2000); + let (folder, db) = support::built( + "inspection-reads-no-block", + 64, + "INDEXING_THRESHOLD 1000", + 2000, + ); + support::run(&db, "CREATE INDEX docs_ctx ON docs (ctx)"); support::close(db); let (door, bytes) = support::counting_bytes_read(); let mut options = DatabaseOpenOptions::default(); @@ -270,6 +279,22 @@ fn inspection_and_explain_read_no_block_and_change_nothing() { read < BLOCK, "inspection and explain read {read} bytes; the block is {BLOCK}" ); + // A count answered from an index range is read when run and not when explained. + let (count, warm) = ( + "SELECT COUNT(*) FROM docs WHERE ctx = 'a'", + bytes.load(Ordering::SeqCst), + ); + db.explain(count).expect("explain a count"); + assert_eq!( + bytes.load(Ordering::SeqCst), + warm, + "explaining a count read the file" + ); + support::run(&db, count); + assert!( + bytes.load(Ordering::SeqCst) > warm, + "running the count reads its range" + ); assert_eq!(db.committed_watermark(), before); } @@ -281,7 +306,7 @@ fn lines_of(explained: &str) -> Vec<&str> { #[test] fn explain_names_how_each_partition_is_searched() { // Partition a is built; b has 2,000 vectors outside any grouping, twice the declared size. - let clauses = "PARTITION_KEY (ctx) AUTO_INDEX_AT 1000"; + let clauses = "PARTITION_KEY (ctx) INDEXING_THRESHOLD 1000"; let (folder, db) = support::built("explain-routes", 16, clauses, 2000); support::load_docs(&db, 2001..=4000, "b", |n| support::gathered(n, 16)); let reader = ReadSession::open(&folder).expect("open for reading"); @@ -302,7 +327,7 @@ fn explain_names_how_each_partition_is_searched() { for wanted in [ "requested_mode: EXACT", "resolved_mode: EXACT", - "effective_auto_index_at: 1000", + "effective_indexing_threshold: 1000", "aggregate_allowed_vectors: 4000", r#"partition_key_columns: ["ctx"]"#, "partitions: 2", @@ -329,7 +354,7 @@ fn explain_names_how_each_partition_is_searched() { assert!(lines[at + 3].starts_with("probes: "), "{explained}"); assert_eq!( lines[at + 4..at + 6], - ["live_rows: 2000", "outside_grouping: 0"] + ["live_rows: 2000", "unindexed_rows: 0"] ); assert!(explained.contains("\n route: indexed\n"), "{explained}"); assert!(lines.contains(&"partitions: 1") && lines.contains(&"refusal: none")); @@ -338,7 +363,7 @@ fn explain_names_how_each_partition_is_searched() { let explained = explain(&searched(None, "INDEXED")); let refusal = format!("refusal: docs.v{}", support::INDEXED_REFUSED); assert_eq!(lines_of(&explained).last(), Some(&refusal.as_str())); - assert!(explained.contains("outside_grouping: 2000"), "{explained}"); + assert!(explained.contains("unindexed_rows: 2000"), "{explained}"); // Under AUTO each partition goes its own way and nothing is refused. let explained = explain(&searched(None, "AUTO")); @@ -380,29 +405,36 @@ fn explain_names_how_each_partition_is_searched() { "a handle narrowed to Context 1 was told of other partitions:\n{seen}" ); assert_eq!(db.explain(sql).expect("explain"), whole); + // Nor is a handle narrowed to no Context, or to one the table does not hold. + let other = ContextId::new(Uuid::from_u128(3)); + for contexts in [BTreeSet::new(), BTreeSet::from([other])] { + let scoped = db.scoped_with_contexts(contexts); + let seen = scoped.explain(sql).expect("explains"); + assert!(!seen.contains(&one.to_string()), "{seen}"); + } - // Any other statement is a later version's to explain. - match db.explain("SELECT id FROM docs") { + // A statement that reads no stored table is not explained. + match db.explain("SELECT 1") { Err(error) => assert!( error.to_string().ends_with( "explaining this statement is not supported in this version of the library" ), "{error}" ), - Ok(explained) => panic!("a plain SELECT was explained:\n{explained}"), + Ok(explained) => panic!("a SELECT of no table was explained:\n{explained}"), } } #[test] fn explain_says_that_auto_below_the_columns_size_resolves_to_exact() { - // Fifty vectors in a column whose size is the 100,000 of no AUTO_INDEX_AT. + // Fifty vectors in a column whose size is the 100,000 of no INDEXING_THRESHOLD. let (_, db) = support::built("explain-auto-below-its-size", 16, "", 50); let explained = db.explain(&searched(None, "AUTO")).expect("explain"); let lines = lines_of(&explained); for wanted in [ "requested_mode: AUTO", "resolved_mode: EXACT", - "effective_auto_index_at: 100000", + "effective_indexing_threshold: 100000", "aggregate_allowed_vectors: 50", "refusal: none", ] { diff --git a/v2/contextdb/tests/vectors_memory.rs b/v2/contextdb/tests/vectors_memory.rs index 0645d541d..da6f89b34 100644 --- a/v2/contextdb/tests/vectors_memory.rs +++ b/v2/contextdb/tests/vectors_memory.rs @@ -7,7 +7,6 @@ mod support; -use std::path::Path; use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering}; @@ -20,51 +19,6 @@ use support::{Call, Run}; const MIB: usize = 1 << 20; const KIB: usize = 1 << 10; -fn open_limited(folder: &Path, limit: usize) -> Database { - let mut options = DatabaseOpenOptions::default(); - options.memory_limit = Some(limit); - match support::open_with(folder, options) { - Ok(db) => db, - Err(error) => panic!("an open under a limit of {limit} bytes was refused: {error:?}"), - } -} - -fn read_limited(folder: &Path, limit: Option) -> ReadSession { - let mut options = ReadSessionOptions::default(); - options.memory_limit = limit; - match ReadSession::open_with_options(folder, options) { - Ok(reader) => reader, - Err(error) => panic!("a reader under a limit of {limit:?} was refused: {error:?}"), - } -} - -fn reopen(db: Database, folder: &Path) -> Database { - support::close(db); - support::open(folder) -} - -/// One column of what `SHOW MEMORY_LIMIT` reports. -fn shown(on: &impl Run, column: &str) -> Value { - let report = support::run(on, "SHOW MEMORY_LIMIT"); - let at = report - .columns() - .iter() - .position(|name| name == column) - .unwrap_or_else(|| panic!("SHOW MEMORY_LIMIT has no column {column}")); - match report.rows() { - [row] => row[at].clone(), - rows => panic!("SHOW MEMORY_LIMIT returned {} rows", rows.len()), - } -} - -/// The bytes `SHOW MEMORY_LIMIT` reports as used. -fn used(on: &impl Run) -> usize { - match shown(on, "used") { - Value::Int64(bytes) => bytes as usize, - other => panic!("SHOW MEMORY_LIMIT reports {other:?} as used"), - } -} - #[test] fn vector_search_ends_complete_or_refused() { const DIMENSION: usize = 64; @@ -107,7 +61,7 @@ fn vector_search_ends_complete_or_refused() { let outcomes = |on: &dyn Run, state: &str| -> [bool; 2] { [0, 1].map(|number| { let (sql, wanted) = &searches[number]; - let before = used(&on); + let before = support::memory_used(&on); let answered = match support::search(&on, sql, &query) { Ok(result) => { let found = support::found(&result, sql); @@ -117,7 +71,11 @@ fn vector_search_ends_complete_or_refused() { Err(Error::MemoryBudgetExceeded { .. }) => false, Err(other) => panic!("{state}: {sql}\nwas refused as {other:?}"), }; - assert_eq!(used(&on), before, "{state}: memory in use after {sql}"); + assert_eq!( + support::memory_used(&on), + before, + "{state}: memory in use after {sql}" + ); answered }) }; @@ -135,7 +93,7 @@ fn vector_search_ends_complete_or_refused() { 64 * MIB, ]; for limit in limits { - let reader = read_limited(&folder, Some(limit)); + let reader = support::open_reader(&folder, Some(limit)); let answered = outcomes(&reader, &format!("a reader under {limit} bytes")); if limit == 9 * MIB { assert_eq!( @@ -149,17 +107,17 @@ fn vector_search_ends_complete_or_refused() { } } // The same through the writer. - let db = open_limited(&folder, 9 * MIB); + let db = support::open_limited(&folder, 9 * MIB); assert_eq!(outcomes(&db, "the writer under 9 MiB"), [false, false]); assert_eq!(db.memory_used(), 9 * MIB); support::close(db); - let db = open_limited(&folder, 64 * MIB); + let db = support::open_limited(&folder, 64 * MIB); assert_eq!(outcomes(&db, "the writer under 64 MiB"), [true, true]); assert_eq!(db.memory_used(), 17 * MIB); support::close(db); // A cycle under a limit too small for it is refused by name, and nothing was sealed. - let db = open_limited(&folder, 9 * MIB + 64 * KIB); + let db = support::open_limited(&folder, 9 * MIB + 64 * KIB); let before = db.memory_used(); match db.run_maintenance_cycle() { Err(Error::MemoryBudgetExceeded { .. }) => {} @@ -198,16 +156,17 @@ fn vector_search_ends_complete_or_refused() { #[test] fn memory_stays_bounded_as_data_grows_vector() { - const DIMENSION: usize = 3072; - // The large partition, in blocks of 8 + 3,072 bytes of slot, 4 of key end and 9 of key each: - // 12.6 MB, one and a half times the reader's 8 MiB page cache, and the fewest that are. - const LARGE: i64 = 4_069; + const DIMENSION: usize = 768; + // Vectors in the large partition of a plain column. In a block each takes 8 + 768 bytes of + // slot, 4 of key end and 9 of key, so these are 10.5 MB of blocks: 1.25 times the page + // cache of 8 MiB that the reader's limit gives it, and the fewest that are. + const LARGE: i64 = 13_290; const SMALL: i64 = 200; const LIMIT: usize = 16 * MIB; const CACHE: usize = 8 * MIB; const BLOCK: u64 = 262_080; - const { assert!(LARGE as u64 * (8 + 3072 + 4 + 9) > 3 * CACHE as u64 / 2) }; - const { assert!((LARGE as u64 - 1) * (8 + 3072 + 4 + 9) <= 3 * CACHE as u64 / 2) }; + const { assert!(LARGE as u64 * (8 + 768 + 4 + 9) * 4 > 5 * CACHE as u64) }; + const { assert!((LARGE as u64 - 1) * (8 + 768 + 4 + 9) * 4 <= 5 * CACHE as u64) }; let folder = support::folder("memory-bounded-vectors"); let db = support::open(&folder); @@ -248,7 +207,11 @@ fn memory_stays_bounded_as_data_grows_vector() { at_open < BLOCK, "opening the store read {at_open} bytes of it before any statement" ); - assert_eq!(used(&reader), 9 * MIB, "set aside by an open under 16 MiB"); + assert_eq!( + support::memory_used(&reader), + 9 * MIB, + "set aside by an open under 16 MiB" + ); // It searches the small partition and answers, reading a small part of the file. for k in [10, 1000] { @@ -256,7 +219,7 @@ fn memory_stays_bounded_as_data_grows_vector() { let sql = support::nearest_sql("docs", "v", Some("ctx = 'small'"), k); support::assert_nearest(&reader, &sql, &query, &wanted, "the small partition"); assert_eq!( - used(&reader), + support::memory_used(&reader), 9 * MIB, "memory in use once the answer is dropped" ); @@ -280,14 +243,14 @@ fn the_page_cache_follows_the_limit_in_force() { let db = support::open(&folder); assert_eq!(db.memory_limit(), None); assert_eq!(db.memory_used(), 9 * MIB, "set aside with no limit"); - assert_eq!(used(&db), 9 * MIB); + assert_eq!(support::memory_used(&db), 9 * MIB); support::declare(&db); support::insert(&db, 1..=10); support::close(db); // Under a limit the cache is a quarter of it and never less than 8 MiB. for (limit, set_aside) in [(64, 17), (16, 9), (9, 9), (32, 9), (40, 11), (1024, 257)] { - let db = open_limited(&folder, limit * MIB); + let db = support::open_limited(&folder, limit * MIB); assert_eq!(db.memory_limit(), Some(limit * MIB)); assert_eq!( db.memory_used(), @@ -304,9 +267,9 @@ fn the_page_cache_follows_the_limit_in_force() { // A reader's cache follows the limit of its own options, and with none it has no limit // and the smallest cache. for (limit, set_aside) in [(None, 9), (Some(64), 17), (Some(16), 9), (Some(1024), 257)] { - let reader = read_limited(&folder, limit.map(|limit| limit * MIB)); + let reader = support::open_reader(&folder, limit.map(|limit| limit * MIB)); assert_eq!( - used(&reader), + support::memory_used(&reader), set_aside * MIB, "a reader under {limit:?} MiB" ); @@ -322,28 +285,40 @@ fn the_page_cache_follows_the_limit_in_force() { 9 * MIB, "the cache of an open keeps its size" ); - let db = reopen(db, &folder); + let db = support::reopen(db, &folder); assert_eq!(db.memory_limit(), Some(512 * MIB)); assert_eq!( db.memory_used(), 129 * MIB, "set aside under a remembered limit of 512 MiB" ); - assert_eq!(used(&db), 129 * MIB); - assert_eq!(shown(&db, "limit"), Value::Int64(512 * MIB as i64)); - assert_eq!(shown(&db, "available"), Value::Int64(383 * MIB as i64)); + assert_eq!(support::memory_used(&db), 129 * MIB); + assert_eq!( + support::memory_shown(&db, "limit"), + Value::Int64(512 * MIB as i64) + ); + assert_eq!( + support::memory_shown(&db, "available"), + Value::Int64(383 * MIB as i64) + ); // A reader does not take the limit the store remembers. - let reader = read_limited(&folder, None); - assert_eq!(shown(&reader, "limit"), Value::Text("none".to_owned())); - assert_eq!(used(&reader), 9 * MIB); - let reader = read_limited(&folder, Some(16 * MIB)); - assert_eq!(used(&reader), 9 * MIB); - assert_eq!(shown(&reader, "available"), Value::Int64(7 * MIB as i64)); + let reader = support::open_reader(&folder, None); + assert_eq!( + support::memory_shown(&reader, "limit"), + Value::Text("none".to_owned()) + ); + assert_eq!(support::memory_used(&reader), 9 * MIB); + let reader = support::open_reader(&folder, Some(16 * MIB)); + assert_eq!(support::memory_used(&reader), 9 * MIB); + assert_eq!( + support::memory_shown(&reader, "available"), + Value::Int64(7 * MIB as i64) + ); // An open that names a limit has its own cache and leaves what the store remembers. support::close(db); - let db = open_limited(&folder, 64 * MIB); + let db = support::open_limited(&folder, 64 * MIB); assert_eq!(db.memory_used(), 17 * MIB); - let db = reopen(db, &folder); + let db = support::reopen(db, &folder); assert_eq!(db.memory_limit(), Some(512 * MIB)); assert_eq!(db.memory_used(), 129 * MIB); } @@ -398,9 +373,9 @@ fn a_limit_below_the_sessions_cache_is_refused_and_one_above_it_is_taken() { // The limit in force, the memory set aside and the limit the store remembers stay as // they were. assert_eq!(db.memory_limit(), None); - assert_eq!(shown(&db, "limit"), none); + assert_eq!(support::memory_shown(&db, "limit"), none); assert_eq!(db.memory_used(), 9 * MIB); - let db = reopen(db, &folder); + let db = support::reopen(db, &folder); assert_eq!(db.memory_limit(), None, "a refused limit was remembered"); assert_eq!(db.memory_used(), 9 * MIB); @@ -408,10 +383,13 @@ fn a_limit_below_the_sessions_cache_is_refused_and_one_above_it_is_taken() { // sizes its cache from it. set(&db, 512).expect("a limit above what is set aside"); assert_eq!(db.memory_limit(), Some(512 * MIB)); - assert_eq!(shown(&db, "limit"), Value::Int64(512 * MIB as i64)); + assert_eq!( + support::memory_shown(&db, "limit"), + Value::Int64(512 * MIB as i64) + ); assert_eq!(db.memory_used(), 9 * MIB); - assert_eq!(used(&db), 9 * MIB); - let db = reopen(db, &folder); + assert_eq!(support::memory_used(&db), 9 * MIB); + let db = support::reopen(db, &folder); assert_eq!(db.memory_limit(), Some(512 * MIB)); assert_eq!(db.memory_used(), 129 * MIB); // Now 129 MiB is the smallest. @@ -426,7 +404,7 @@ fn a_limit_below_the_sessions_cache_is_refused_and_one_above_it_is_taken() { // Opened with options that name 16 MiB: 9 MiB are set aside. 8 MiB is refused and // 1 GiB is taken, and the next open with no options is under 1 GiB. let folder = support::folder(&format!("limit-below-small-cache-{name}")); - let db = open_limited(&folder, 16 * MIB); + let db = support::open_limited(&folder, 16 * MIB); assert_eq!(db.memory_used(), 9 * MIB); refused_below_the_cache(set(&db, 8), 8 * MIB, 9 * MIB); assert_eq!(db.memory_limit(), Some(16 * MIB)); @@ -437,11 +415,11 @@ fn a_limit_below_the_sessions_cache_is_refused_and_one_above_it_is_taken() { None, "a refused limit was remembered" ); - let db = open_limited(&folder, 16 * MIB); + let db = support::open_limited(&folder, 16 * MIB); set(&db, 1024).expect("a limit above what is set aside"); assert_eq!(db.memory_limit(), Some(1024 * MIB)); assert_eq!(db.memory_used(), 9 * MIB); - let db = reopen(db, &folder); + let db = support::reopen(db, &folder); assert_eq!(db.memory_limit(), Some(1024 * MIB)); assert_eq!(db.memory_used(), 257 * MIB); // Under the 1 GiB the store remembers the cache is 256 MiB, and 64 MiB is refused. @@ -521,10 +499,16 @@ fn a_limit_of_64_mib_is_taken_in_a_store_opened_with_no_limit() { // session already has. set(&db, 64).expect("64 MiB in a session opened with no limit"); assert_eq!(db.memory_limit(), Some(64 * MIB)); - assert_eq!(shown(&db, "limit"), Value::Int64(64 * MIB as i64)); + assert_eq!( + support::memory_shown(&db, "limit"), + Value::Int64(64 * MIB as i64) + ); assert_eq!(db.memory_used(), 9 * MIB); - assert_eq!(used(&db), 9 * MIB); - assert_eq!(shown(&db, "available"), Value::Int64(55 * MIB as i64)); + assert_eq!(support::memory_used(&db), 9 * MIB); + assert_eq!( + support::memory_shown(&db, "available"), + Value::Int64(55 * MIB as i64) + ); // It holds at once for what statements take: a value of 56 MiB is more than the // 55 MiB the limit leaves and is refused by the memory limit; one of 1 MiB is taken. @@ -545,12 +529,18 @@ fn a_limit_of_64_mib_is_taken_in_a_store_opened_with_no_limit() { // The store remembers it: the next plain open is under 64 MiB, with a cache of a // quarter of it, 16 MiB, and 1 MiB set aside before any statement. - let db = reopen(db, &folder); + let db = support::reopen(db, &folder); assert_eq!(db.memory_limit(), Some(64 * MIB)); assert_eq!(db.memory_used(), 17 * MIB); - assert_eq!(used(&db), 17 * MIB); - assert_eq!(shown(&db, "limit"), Value::Int64(64 * MIB as i64)); - assert_eq!(shown(&db, "available"), Value::Int64(47 * MIB as i64)); + assert_eq!(support::memory_used(&db), 17 * MIB); + assert_eq!( + support::memory_shown(&db, "limit"), + Value::Int64(64 * MIB as i64) + ); + assert_eq!( + support::memory_shown(&db, "available"), + Value::Int64(47 * MIB as i64) + ); over_64_mib( db.execute(insert, ¶ms! { "id" => 1_i64, "body" => large.as_str() }), "56 MiB after the reopen", @@ -561,7 +551,7 @@ fn a_limit_of_64_mib_is_taken_in_a_store_opened_with_no_limit() { // The refusal that stays: a session opened under 1 GiB has a cache of 256 MiB, and // 64 MiB is refused there with the action, to open the store with the limit. let folder = support::folder(&format!("limit-64-under-1-gib-{name}")); - let db = open_limited(&folder, 1024 * MIB); + let db = support::open_limited(&folder, 1024 * MIB); assert_eq!(db.memory_used(), 257 * MIB); refused_below_the_cache(set(&db, 64), 64 * MIB, 257 * MIB); assert_eq!(db.memory_limit(), Some(1024 * MIB)); @@ -609,7 +599,7 @@ fn a_cycle_under_a_tight_limit_seals_what_fits_and_is_refused_only_when_one_part // The searches are a reader's, which has no limit of its own: ten rows of everything and // ten of one partition. Returns the rows each search read. - let reader = read_limited(&folder, None); + let reader = support::open_reader(&folder, None); let query = support::vector(95_000, DIMENSION); let searches = [None, Some("ctx = 'p07'")]; let wanted_now = || { @@ -637,7 +627,7 @@ fn a_cycle_under_a_tight_limit_seals_what_fits_and_is_refused_only_when_one_part ); // Under the tight limit every cycle seals at least one partition and none is refused. - let db = open_limited(&folder, TIGHT); + let db = support::open_limited(&folder, TIGHT); let set_aside = db.memory_used(); let mut remaining = ROWS as u64; let mut cycles = 0; @@ -710,7 +700,7 @@ fn a_cycle_under_a_tight_limit_seals_what_fits_and_is_refused_only_when_one_part // Under a limit that leaves less than the block a cycle builds in, the working set of // that one partition does not fit, and the cycle is refused by name. Nothing was staged: // no commit was made and nothing is counted. - let db = open_limited(&folder, SHORT); + let db = support::open_limited(&folder, SHORT); let (set_aside, position) = (db.memory_used(), db.committed_watermark()); match db.run_maintenance_cycle() { Err(Error::MemoryBudgetExceeded { @@ -775,7 +765,7 @@ fn the_memory_of_a_search_is_given_back_when_its_result_is_dropped() { } } let query = support::vector(96_500, DIMENSION); - let reader = read_limited(&folder, Some(16 * MIB)); + let reader = support::open_reader(&folder, Some(16 * MIB)); // A transaction that has staged rows of its own: its searches read those too. let tx = db.transaction().expect("begin"); support::insert_docs(&tx, 401..=420, DIMENSION, ctx); @@ -797,7 +787,7 @@ fn the_memory_of_a_search_is_given_back_when_its_result_is_dropped() { ]; for (on, door) in doors { for sql in &searches { - let before = used(&on); + let before = support::memory_used(&on); let result = match support::search(&on, sql, &query) { Ok(result) => result, Err(error) => panic!("through {door}: {sql}\nwas refused: {error:?}"), @@ -807,7 +797,7 @@ fn the_memory_of_a_search_is_given_back_when_its_result_is_dropped() { "through {door}: the rows of {sql}" ); // While the result lives its rows are counted, so the figure does move. - let held = used(&on); + let held = support::memory_used(&on); assert!( held > before, "through {door}: with the result of {sql}\nin hand, {held} bytes are in use, \ @@ -815,7 +805,7 @@ fn the_memory_of_a_search_is_given_back_when_its_result_is_dropped() { ); drop(result); assert_eq!( - used(&on), + support::memory_used(&on), before, "through {door}: memory in use once the result of {sql}\nis dropped" ); @@ -829,7 +819,7 @@ fn the_memory_of_a_search_is_given_back_when_its_result_is_dropped() { #[test] fn a_commit_with_no_room_for_its_vector_records_changes_nothing() { const DIMENSION: usize = 16; - let (folder, db) = support::built("commit-no-room", DIMENSION, "AUTO_INDEX_AT 1000", 2000); + let (folder, db) = support::built("commit-no-room", DIMENSION, "INDEXING_THRESHOLD 1000", 2000); let rows = "SELECT id, ctx, tag, v FROM docs ORDER BY id"; let untouched = (support::rows(&db, rows), db.committed_watermark()); support::close(db); @@ -869,15 +859,15 @@ fn a_commit_with_no_room_for_its_vector_records_changes_nothing() { let spares = (0..=32).map(|step| step * 64 * KIB).chain([55 * MIB]); for spare in spares { let limit = 9 * MIB + spare; - let db = open_limited(&folder, limit); - let before = used(&db); + let db = support::open_limited(&folder, limit); + let before = support::memory_used(&db); let outcome = attempt(&db); assert_eq!( - used(&db), + support::memory_used(&db), before, "memory in use after a commit under {limit}" ); - let db = reopen(db, &folder); + let db = support::reopen(db, &folder); match outcome { Ok(()) => { assert_eq!(support::int(&db, "SELECT COUNT(*) FROM docs"), 2300); diff --git a/v2/contextdb/tests/vectors_partitions.rs b/v2/contextdb/tests/vectors_partitions.rs index 686595135..e54ef9f24 100644 --- a/v2/contextdb/tests/vectors_partitions.rs +++ b/v2/contextdb/tests/vectors_partitions.rs @@ -7,12 +7,9 @@ mod support; use std::sync::atomic::Ordering; -use contextdb::{ - Database, DatabaseOpenOptions, Error, ReadSession, ReadSessionOptions, Value, VectorIndexRef, - params, -}; +use contextdb::{Database, DatabaseOpenOptions, Error, ReadSession, Value, VectorIndexRef, params}; -use support::{Child, Near, Run}; +use support::{Child, Near, Run, near_ids as ids}; /// A table whose VECTOR column is partitioned by two columns. const NOTES: &str = "SELECT id, ctx, kind, v FROM notes"; @@ -42,16 +39,6 @@ fn under(row: &[Value], ctx: &str, kind: i64) -> bool { row[1] == support::text(ctx) && row[2] == Value::Int64(kind) } -fn ids(answer: &[Near]) -> Vec { - answer - .iter() - .map(|near| match near.key { - Value::Int64(id) => id, - ref other => panic!("the key {other:?} is not an INTEGER"), - }) - .collect() -} - #[test] fn multi_partition_search_returns_one_global_answer() { const DIMENSION: usize = 16; @@ -744,11 +731,7 @@ fn the_partition_cap_counts_live_partitions_while_a_reader_holds_an_earlier_stat /// for a line. Then it searches every partition again and announces each row as /// `now `, then `done`. fn searcher(role: &support::Role) { - let (door, searching, reads) = support::pausing_at_read(role.number("pause_at")); - let mut options = ReadSessionOptions::default(); - options.storage = Some(door); - let reader = - ReadSession::open_with_options(&role.folder, options).expect("open the store for reading"); + let (reader, searching, reads) = support::reader_pausing(role); let query = support::vector(83_000, 64); searching.store(true, std::sync::atomic::Ordering::SeqCst); diff --git a/v2/contextdb/tests/vectors_reduced.rs b/v2/contextdb/tests/vectors_reduced.rs index 2b2df7850..07ec547e4 100644 --- a/v2/contextdb/tests/vectors_reduced.rs +++ b/v2/contextdb/tests/vectors_reduced.rs @@ -114,7 +114,10 @@ fn a_reduced_column_is_grouped_and_searched_as_any_other() { assert_eq!(support::upkeep(&db).0, 16, "the cycles of a build of 2,000"); let index = support::shown(&db, "SHOW VECTOR_INDEXES").remove(0); assert_eq!(support::word(&index, "quantization"), "SQ8"); - assert_eq!(support::whole(&index, "effective_auto_index_at"), 100_000); + assert_eq!( + support::whole(&index, "effective_indexing_threshold"), + 100_000 + ); assert_eq!( support::field(&support::the_partition(&db), "lists"), &Value::Int64(45) diff --git a/v2/contextdb/tests/vectors_statements.rs b/v2/contextdb/tests/vectors_statements.rs index 5d3696adf..e2c6b2e03 100644 --- a/v2/contextdb/tests/vectors_statements.rs +++ b/v2/contextdb/tests/vectors_statements.rs @@ -15,9 +15,6 @@ use support::{Call, Near, Run}; const DIMENSION: usize = 8; -/// How the refusal of a statement that only a later version runs ends. -const LATER_VERSION: &str = "is not supported in this version of the library"; - fn column(table: &str, column: &str) -> VectorIndexRef { VectorIndexRef { table: table.to_owned(), @@ -70,10 +67,13 @@ fn refused_as_indexed(outcome: contextdb::Result, table: } } -/// True for a sentence that names both the function `ROW_VECTOR`, in any letter case, and the -/// `<=>` it was written beside. Every test of that refusal holds it to both. +/// True for a sentence that names the function `ROW_VECTOR`, in any letter case, the `<=>` it was +/// written beside, and the scalar subquery to write instead. Every test of that refusal holds it +/// to all three. fn names_row_vector_beside_a_distance(sentence: &str) -> bool { - sentence.to_uppercase().contains("ROW_VECTOR") && sentence.contains("<=>") + sentence.to_uppercase().contains("ROW_VECTOR") + && sentence.contains("<=>") + && sentence.contains("scalar subquery") } #[test] @@ -149,7 +149,7 @@ fn vector_search_mode_routes_each_request() { let tx = db.transaction().expect("begin"); through(&tx, "a transaction"); tx.rollback(); - let reader = ReadSession::open(&folder).expect("open the store for reading"); + let reader = support::open_reader(&folder, None); through(&reader, "a read session"); // A table of one row and a column declared SEARCH_MODE EXACT, with nothing else set. @@ -180,14 +180,14 @@ const SMALL_RECORD_READS: usize = 4; fn indexed_search_is_refused_at_every_door() { let folder = support::folder("indexed-refused"); let db = support::open(&folder); - declare(&db, "plain", "PARTITION_KEY (ctx) AUTO_INDEX_AT 1000"); + declare(&db, "plain", "PARTITION_KEY (ctx) INDEXING_THRESHOLD 1000"); declare( &db, "indexed", - "PARTITION_KEY (ctx) SEARCH_MODE INDEXED AUTO_INDEX_AT 1000", + "PARTITION_KEY (ctx) SEARCH_MODE INDEXED INDEXING_THRESHOLD 1000", ); declare(&db, "empty", "SEARCH_MODE INDEXED"); - declare(&db, "small", "PARTITION_KEY (ctx) AUTO_INDEX_AT 1000"); + declare(&db, "small", "PARTITION_KEY (ctx) INDEXING_THRESHOLD 1000"); let tx = db.transaction().expect("begin"); fill(&tx, "small", 1..=300); tx.commit().expect("commit"); @@ -207,6 +207,10 @@ fn indexed_search_is_refused_at_every_door() { "plain", search_sql("plain", Some("ctx = 'c1'"), "USE VECTOR INDEXED", 5), ), + ( + "plain", + search_sql("plain", Some("id = 1"), "USE VECTOR INDEXED", 5), + ), ("indexed", search_sql("indexed", None, "", 5)), ( "indexed", @@ -228,7 +232,7 @@ fn indexed_search_is_refused_at_every_door() { db.committed_watermark(), support::int(&db, "SELECT COUNT(*) FROM indexed"), ); - let reader = ReadSession::open(&folder).expect("open the store for reading"); + let reader = support::open_reader(&folder, None); let tx = db.transaction().expect("begin"); for (table, sql) in &asking { // Never an answer, through the writer, a transaction and a reader alike. @@ -236,7 +240,7 @@ fn indexed_search_is_refused_at_every_door() { refused_as_indexed(support::search(&tx, sql, &query), table, sql); refused_as_indexed(support::search(&reader, sql, &query), table, sql); } - // A partition with no grouping and fewer vectors outside one than twice AUTO_INDEX_AT is + // A partition with no grouping and fewer vectors outside one than twice INDEXING_THRESHOLD is // the index's one-group case: INDEXED answers it, and its answer and its work are EXACT's. let small = support::stored(&db, "SELECT id, ctx, tag, v FROM small"); type Scope = (Option<&'static str>, fn(&[Value]) -> bool); @@ -354,10 +358,10 @@ fn indexed_search_is_refused_at_every_door() { } #[test] -fn the_largest_auto_index_at_is_declared_and_served() { +fn the_largest_indexing_threshold_is_declared_and_served() { let folder = support::folder("largest-auto-index-at"); let db = support::open(&folder); - declare(&db, "largest", "AUTO_INDEX_AT 18446744073709551615"); + declare(&db, "largest", "INDEXING_THRESHOLD 18446744073709551615"); fill(&db, "largest", 1..=20); let query = support::vector(91_500, DIMENSION); // The column is below its size: every mode answers exactly, before a cycle and after. @@ -413,7 +417,7 @@ fn vector_query_errors_are_typed() { ) .expect("insert a row"); } - let reader = ReadSession::open(&folder).expect("open the store for reading"); + let reader = support::open_reader(&folder, None); let state = |db: &Database| { let rows = support::rows(db, "SELECT id, ctx, r, v, w FROM docs ORDER BY id"); (rows, db.committed_watermark()) @@ -458,21 +462,6 @@ fn vector_query_errors_are_typed() { other => panic!("{sql}\nwas refused as {other:?}, not as a plan error"), }; - // A search with no LIMIT has no kind of its own: it is refused as every statement of a - // later version is, in a sentence that names it. - for sql in [ - "SELECT id FROM docs ORDER BY v <=> $q", - "SELECT id, v <=> $q AS distance FROM docs ORDER BY distance", - "SELECT id FROM docs WHERE ctx = 'a' ORDER BY v <=> $q USE VECTOR EXACT", - ] { - match refusal(sql, &good, &good) { - Error::PlanError(text) => assert!( - text.contains("vector search without LIMIT") && text.ends_with(LATER_VERSION), - "{sql}\nwas refused in the sentence: {text}" - ), - other => panic!("{sql}\nwas refused as {other:?}, not as a plan error"), - } - } // USE VECTOR in a SELECT that does not order by a distance. for sql in [ "SELECT id FROM docs ORDER BY id USE VECTOR EXACT LIMIT 3", @@ -569,47 +558,13 @@ fn vector_query_errors_are_typed() { ), other => panic!("{sql}\ngot {other:?}"), } - // A distance anywhere but as the one ORDER BY key of a search, ascending, and in that - // search's select list. + // A distance is not carried into a write; every other use is an answer (`vector_search.sql`). for sql in [ - // In a WHERE. - "SELECT id FROM docs WHERE v <=> $q < 0.5", - "SELECT id FROM docs WHERE v <=> $q < 0.5 ORDER BY id LIMIT 3", - "SELECT id FROM docs WHERE v <=> $q < 0.5 ORDER BY v <=> $q LIMIT 3", "DELETE FROM docs WHERE v <=> $q < 0.5", - // In a select list with no ORDER BY on it. - "SELECT id, v <=> $q AS distance FROM docs", - "SELECT id, v <=> $q AS distance FROM docs ORDER BY id LIMIT 3", - // With DESC. - "SELECT id FROM docs ORDER BY v <=> $q DESC LIMIT 3", - "SELECT id, v <=> $q AS distance FROM docs ORDER BY distance DESC LIMIT 3", - // Beside a second ORDER BY item. - "SELECT id FROM docs ORDER BY v <=> $q, id LIMIT 3", - "SELECT id FROM docs ORDER BY id, v <=> $q LIMIT 3", - // With a left side that is not a column. - "SELECT id FROM docs ORDER BY $q <=> v LIMIT 3", - // In a write. "UPDATE docs SET r = v <=> $q WHERE id = 1", - "INSERT INTO docs (id, ctx, r) VALUES (99, 'a', $v <=> $q)", ] { plan_error(sql, &["<=>"]); } - // A second distance that is not the ORDER BY's own: of another column, or to another - // vector. The refusal names `<=>` and the column, as `column `: the letter alone is - // in nearly every sentence. - plan_error( - "SELECT id, w <=> $q AS other FROM docs ORDER BY v <=> $q LIMIT 3", - &["<=>", "column w"], - ); - plan_error( - "SELECT id, v <=> $p AS other FROM docs ORDER BY v <=> $q LIMIT 3", - &["<=>", "column v"], - ); - plan_error( - "SELECT id, v <=> $q AS distance, 1 - (w <=> $q) AS other FROM docs \ - ORDER BY distance LIMIT 3", - &["<=>", "column w"], - ); // There is no score column: on a table with no such column it is a name like any other. for sql in [ @@ -637,27 +592,16 @@ fn vector_query_errors_are_typed() { #[test] fn what_the_parser_reads_and_this_version_does_not_run_is_refused_when_planned() { + // The scripts prove the kind of each refusal; this proves its sentence, which names the form + // so that a person knows what to write instead, and that it is the same sentence through + // the writer, a transaction and a reader. let folder = support::folder("refused-when-planned"); let db = support::open(&folder); support::run( &db, - "CREATE TABLE pairs (id INTEGER PRIMARY KEY, a INTEGER, b INTEGER, v VECTOR(3), \ - w VECTOR(3))", + "CREATE TABLE pairs (id INTEGER PRIMARY KEY, a INTEGER, b INTEGER, v VECTOR(3))", ); - support::run( - &db, - "INSERT INTO pairs (id, a, b, v, w) VALUES (1, 1, 2, [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]), \ - (2, 3, 4, [0.0, 1.0, 0.0], [1.0, 0.0, 0.0])", - ); - let reader = ReadSession::open(&folder).expect("open the store for reading"); - let state = |db: &Database| { - let rows = support::rows(db, "SELECT id, a, b, v, w FROM pairs ORDER BY id"); - (rows, db.committed_watermark()) - }; - let before = state(&db); - - // The sentence a statement is refused in. It is a plan error, never a syntax error, and - // the same through the writer, a transaction and a reader. + let reader = support::open_reader(&folder, None); let refused_when_planned = |sql: &str| -> String { let tx = db.transaction().expect("begin"); let none = params! {}; @@ -678,50 +622,50 @@ fn what_the_parser_reads_and_this_version_does_not_run_is_refused_when_planned() let [sentence, ..] = sentences; sentence }; - - // A row value is read wherever an expression is, and refused by name anywhere but beside - // IN: compared with `=`, and in a select list. - for sql in [ - "SELECT id FROM pairs WHERE (a, b) = (1, 2)", - "SELECT (a, b) FROM pairs", + for (sql, form) in [ + ("SELECT (a, b) FROM pairs", "row value"), + ( + "SELECT a FROM pairs INTERSECT SELECT a FROM pairs", + "INTERSECT", + ), + ("SELECT a FROM pairs EXCEPT SELECT a FROM pairs", "EXCEPT"), + ( + "SELECT p.a FROM pairs p RIGHT JOIN pairs q ON p.a = q.a", + "RIGHT JOIN", + ), + ( + "SELECT p.a FROM pairs p FULL JOIN pairs q ON p.a = q.a", + "FULL JOIN", + ), ] { let sentence = refused_when_planned(sql); assert!( - sentence.to_lowercase().contains("row value"), - "{sql}\nwas refused without naming the row value: {sentence}" + sentence.to_lowercase().contains(&form.to_lowercase()), + "{sql}\nwas refused without naming {form}: {sentence}" ); } - // Anything is read on the right of `<=>`, and anything but a vector literal, its quoted - // text or a bound name is refused naming `<=>`: a column, and ROW_VECTOR(...), whose - // refusal names the function too. - let sql = "SELECT id FROM pairs ORDER BY v <=> w LIMIT 3"; - let sentence = refused_when_planned(sql); - assert!( - sentence.contains("<=>"), - "{sql}\nwas refused without naming <=>: {sentence}" - ); + for (sql, form) in [ + ("SELECT RANK() OVER (ORDER BY a) FROM pairs", "RANK"), + ("SELECT SUM(a) OVER (ORDER BY a) FROM pairs", "SUM"), + ( + "SELECT ROW_NUMBER() OVER (PARTITION BY a) FROM pairs", + "ORDER BY", + ), + ] { + match support::refusal(&db, sql) { + Error::WindowFunctionNotSupported { form: found } => assert!( + found.contains(form), + "{sql}\nwas refused without naming {form}: {found}" + ), + other => panic!("{sql}\nwas refused as {other:?}"), + } + } let sql = "SELECT id FROM pairs ORDER BY v <=> ROW_VECTOR('pairs', 'v', 1) LIMIT 3"; let sentence = refused_when_planned(sql); assert!( names_row_vector_beside_a_distance(&sentence), "{sql}\nwas refused without naming both ROW_VECTOR and <=>: {sentence}" ); - // A search with no LIMIT is refused as every statement of a later version is, by its - // name. - let sql = "SELECT id FROM pairs ORDER BY v <=> [1.0, 0.0, 0.0]"; - let sentence = refused_when_planned(sql); - assert!( - sentence.contains("vector search without LIMIT") && sentence.ends_with(LATER_VERSION), - "{sql}\nwas refused in the sentence: {sentence}" - ); - - // Each of them left the store as it was, and the column still answers. - assert!(state(&db) == before); - let stored = support::stored(&db, "SELECT id, a, b, v FROM pairs"); - let query = [1.0_f32, 0.0, 0.0]; - let wanted = stored.nearest(|_| true, &query, 2); - let sql = support::nearest_sql("pairs", "v", None, 2); - support::assert_nearest(&db, &sql, &query, &wanted, "after every refusal"); } /// The words of a declaration's line for one column: what stands between spaces, commas and @@ -998,7 +942,7 @@ fn vector_column_declarations_are_checked_stored_and_printed_back() { printed, "after reopen" ); - let reader = ReadSession::open(&folder).expect("open the store for reading"); + let reader = support::open_reader(&folder, None); assert_eq!( reader.declaration("t").expect("a reader's declaration"), printed @@ -1045,70 +989,6 @@ fn refused_at_every_door(db: &Database, reader: &ReadSession, sql: &str, query: from_writer } -#[test] -fn a_second_sort_key_after_a_distance_is_refused_as_a_later_form_whose_order_by_is_there() { - let folder = support::folder("second-sort-key"); - let db = support::open(&folder); - declare(&db, "docs", ""); - fill(&db, "docs", 1..=5); - let reader = ReadSession::open(&folder).expect("open the store for reading"); - let query = support::vector(93_000, DIMENSION); - let before = ( - support::rows(&db, "SELECT id, ctx, tag, v FROM docs ORDER BY id"), - db.committed_watermark(), - ); - - // What a statement is told whose distance is in no ORDER BY at all: there the ORDER BY is - // what is missing, and the sentence may say so. - let no_order_by = "SELECT id, v <=> $q AS distance FROM docs LIMIT 3"; - let missing = match refused_at_every_door(&db, &reader, no_order_by, &query) { - Error::PlanError(text) => text, - other => panic!("{no_order_by}\nwas refused as {other:?}"), - }; - - // A search with a second sort key after its distance has its ORDER BY. It is a form of a - // later version: refused when planned, as every such form is, naming `<=>`, and not in - // the sentence of a statement that lacks the ORDER BY. That holds with USE VECTOR too, - // which is not told that it "requires ORDER BY ... <=>" by a statement that wrote one. - let mut wrong = Vec::new(); - for sql in [ - "SELECT id FROM docs ORDER BY v <=> $q, id LIMIT 3", - "SELECT id, v <=> $q AS distance FROM docs ORDER BY distance, id LIMIT 3", - "SELECT id FROM docs ORDER BY v <=> $q, id USE VECTOR EXACT LIMIT 3", - ] { - match refused_at_every_door(&db, &reader, sql, &query) { - Error::PlanError(text) => { - if !(text.contains("<=>") && text.ends_with(LATER_VERSION)) { - wrong.push(format!( - "{sql}\nwas not refused as a form of a later version that names <=>: {text}" - )); - } - if text == missing { - wrong.push(format!( - "{sql}\nwas told what a statement with no ORDER BY on its distance is \ - told: {text}" - )); - } - } - other => wrong.push(format!( - "{sql}\nwas refused as {other:?} ({other}), not as a plan error" - )), - } - } - assert!(wrong.is_empty(), "{}", wrong.join("\n\n")); - - // Each of them left the store as it was, and the search without the second key answers. - let after = ( - support::rows(&db, "SELECT id, ctx, tag, v FROM docs ORDER BY id"), - db.committed_watermark(), - ); - assert!(after == before, "a refused statement changed the store"); - let stored = support::stored(&db, "SELECT id, ctx, tag, v FROM docs"); - let wanted = stored.nearest(|_| true, &query, 3); - let sql = support::nearest_sql("docs", "v", None, 3); - support::assert_nearest(&db, &sql, &query, &wanted, "after every refusal"); -} - #[test] fn a_distance_on_a_column_of_another_table_is_a_column_that_is_not_found() { let folder = support::folder("distance-wrongly-qualified"); @@ -1117,7 +997,7 @@ fn a_distance_on_a_column_of_another_table_is_a_column_that_is_not_found() { declare(&db, "other", ""); fill(&db, "docs", 1..=5); fill(&db, "other", 1..=5); - let reader = ReadSession::open(&folder).expect("open the store for reading"); + let reader = support::open_reader(&folder, None); let query = support::vector(94_000, DIMENSION); // Under the name of a table that is declared and is not the statement's, and under a name @@ -1182,7 +1062,7 @@ fn a_distance_on_a_table_that_does_not_exist_is_a_table_that_is_not_found() { let db = support::open(&folder); declare(&db, "other", ""); fill(&db, "other", 1..=5); - let reader = ReadSession::open(&folder).expect("open the store for reading"); + let reader = support::open_reader(&folder, None); let query = support::vector(94_100, DIMENSION); // What any statement on a table that is not there is told. @@ -1267,6 +1147,136 @@ fn a_distance_in_the_where_of_a_write_is_refused_on_a_table_with_no_row() { ); } +/// Runs a statement with `$q` and `$p` bound, on the writer. +fn rows_of(db: &Database, sql: &str, q: &[f32], p: &[f32]) -> Vec> { + let bound = params! { "q" => q.to_vec(), "p" => p.to_vec() }; + match db.execute(sql, &bound) { + Ok(result) => result.rows().to_vec(), + Err(error) => panic!("{sql}\nwas refused: {error:?}"), + } +} + +#[test] +fn a_distance_is_a_value_of_the_row_on_every_route() { + let db = support::open(&support::folder("distance-on-every-route")); + declare(&db, "docs", ""); + fill(&db, "docs", 1..=60); + let (q, p) = ( + support::vector(1, DIMENSION), + support::vector(37, DIMENSION), + ); + // Each statement runs with the distance as its first sort key (a search) and written so that + // no search can take it: the same rows in the same order, the same distances. + for template in [ + "SELECT id, v <=> $q AS distance FROM docs ORDER BY {o} LIMIT 7", + "SELECT id FROM docs WHERE tag < 20 ORDER BY {o} LIMIT 5 OFFSET 2", + "SELECT id, v <=> $p AS other FROM docs WHERE v <=> $p < 0.9 ORDER BY {o}, id DESC LIMIT 5", + ] { + let by_search = rows_of(&db, &template.replace("{o}", "v <=> $q"), &q, &p); + let by_scan = rows_of(&db, &template.replace("{o}", "(v <=> $q) + 0"), &q, &p); + assert!(!by_search.is_empty(), "{template}\nfound nothing"); + assert!( + by_search == by_scan, + "{template}\nthe search gave {by_search:?} and the ordinary route {by_scan:?}" + ); + } +} + +#[test] +fn a_filtered_search_reads_its_index_range_and_a_ranked_one_asks_every_vector() { + let db = support::open(&support::folder("counted-small-set-and-rank")); + declare(&db, "docs", ""); + declare(&db, "bare", ""); + support::run(&db, "CREATE INDEX docs_tag ON docs (tag)"); + fill(&db, "docs", 1..=200); + fill(&db, "bare", 1..=200); + let query = support::vector(5, DIMENSION); + let ask = |sql: String| { + db.execute(&sql, ¶ms! { "q" => query.clone() }) + .expect(&sql) + }; + // Four rows of each tag: with an index over the filtered column only those four are + // compared, without one every row is read. + let by_tag = |table: &str| { + ask(format!( + "SELECT id FROM {table} WHERE tag = 7 ORDER BY v <=> $q LIMIT 3" + )) + }; + let (indexed, bare) = (by_tag("docs"), by_tag("bare")); + assert_eq!(indexed.rows(), bare.rows(), "the index changes no answer"); + assert_eq!(indexed.distance_evaluations(), 4, "the rows of the range"); + assert!( + indexed.rows_examined() < bare.rows_examined(), + "the table was read" + ); + let range = + ask("SELECT id FROM docs WHERE tag >= 7 AND tag < 8 ORDER BY v <=> $q LIMIT 3".into()); + assert_eq!(range.distance_evaluations(), 4, "the rows of a range"); + // Ungrouped rows weigh 1 in 16, so 12 rows are few: under INDEXED four rows are compared. + let by_index = ask( + "SELECT id FROM docs WHERE tag = 7 ORDER BY v <=> $q USE VECTOR INDEXED LIMIT 3".into(), + ); + assert_eq!(by_index.distance_evaluations(), 4, "the rows of the tag"); + // Ten tags are 40 of 200 rows: not few, so the index buys nothing and costs nothing; four + // rows of a range are few. + let many = |table: &str| { + ask(format!( + "SELECT id FROM {table} WHERE tag IN (10, 11, 12, 13, 14, 15, 16, 17, 18, 19) \ + ORDER BY v <=> $q LIMIT 3" + )) + }; + let (indexed, bare) = (many("docs"), many("bare")); + assert_eq!(indexed.rows(), bare.rows(), "the index changes no answer"); + assert_eq!( + indexed.distance_evaluations(), + bare.distance_evaluations(), + "many rows are not walked" + ); + assert_eq!(indexed.rows_examined(), bare.rows_examined(), "nor read"); + // A rank policy: EXACT asks every allowed vector, and each of the 40 candidates is one + // lookup of its joined row (counted as a row examined). + support::run( + &db, + "CREATE TABLE results (id INTEGER PRIMARY KEY, task_id INTEGER NOT NULL)", + ); + support::run(&db, "CREATE INDEX results_task ON results (task_id)"); + let policy = "JOIN results ON task_id, FORMULA '{vector_score}', SORT_KEY worth"; + support::run( + &db, + &format!( + "CREATE TABLE tasks (id INTEGER PRIMARY KEY, v VECTOR({DIMENSION}) RANK_POLICY ({policy}))" + ), + ); + for n in 1..=40_i64 { + let values = params! { "v" => support::vector(n, DIMENSION) }; + db.execute( + &format!("INSERT INTO tasks (id, v) VALUES ({n}, $v)"), + &values, + ) + .expect("task"); + support::run( + &db, + &format!("INSERT INTO results (id, task_id) VALUES ({n}, {n})"), + ); + } + let ask_tasks = |rank: &str| { + ask(format!( + "SELECT id FROM tasks ORDER BY v <=> $q USE VECTOR EXACT {rank} LIMIT 3" + )) + }; + let (plain, ranked) = (ask_tasks(""), ask_tasks("USE RANK worth")); + assert_eq!( + ranked.distance_evaluations(), + 40, + "EXACT asks every allowed vector" + ); + assert_eq!( + ranked.rows_examined(), + plain.rows_examined() + 40, + "one lookup per candidate" + ); +} + /// A table `t` whose one VECTOR column `v` is declared with this text, as a statement. fn with_vector(declared: &str) -> String { format!("CREATE TABLE t (id INTEGER PRIMARY KEY, ctx TEXT NOT NULL, v {declared})") @@ -1287,13 +1297,13 @@ fn the_index_clauses_are_read_checked_and_printed_back() { ), ( "b", - "VECTOR(4) WITH (quantization = 'F32') AUTO_INDEX_AT 5000", - &["b", "VECTOR", "4", "AUTO_INDEX_AT", "5000"], + "VECTOR(4) WITH (quantization = 'F32') INDEXING_THRESHOLD 5000", + &["b", "VECTOR", "4", "INDEXING_THRESHOLD", "5000"], ), ( "c", "VECTOR(4) PARTITION_KEY (ctx) SEARCH_MODE INDEXED \ - AUTO_INDEX_AT 18446744073709551615 CONSOLIDATION NONE", + INDEXING_THRESHOLD 18446744073709551615 COMPACTION NONE", &[ "c", "VECTOR", @@ -1304,20 +1314,20 @@ fn the_index_clauses_are_read_checked_and_printed_back() { "256", "SEARCH_MODE", "INDEXED", - "AUTO_INDEX_AT", + "INDEXING_THRESHOLD", "18446744073709551615", - "CONSOLIDATION", + "COMPACTION", "NONE", ], ), ( "d", - "VECTOR(4) consolidation (tombstone_percent = 100)", + "VECTOR(4) compaction (tombstone_percent = 100)", &[ "d", "VECTOR", "4", - "CONSOLIDATION", + "COMPACTION", "TOMBSTONE_PERCENT", "=", "100", @@ -1325,12 +1335,12 @@ fn the_index_clauses_are_read_checked_and_printed_back() { ), ( "e", - "VECTOR(4) CONSOLIDATION (CHANGE_PERCENT = 1, TOMBSTONE_PERCENT = 100)", + "VECTOR(4) COMPACTION (CHANGE_PERCENT = 1, TOMBSTONE_PERCENT = 100)", &[ "e", "VECTOR", "4", - "CONSOLIDATION", + "COMPACTION", "CHANGE_PERCENT", "=", "1", @@ -1364,13 +1374,9 @@ fn the_index_clauses_are_read_checked_and_printed_back() { support::close(db); let db = support::open(&folder); assert_eq!(db.declaration("t").expect("the declaration"), printed); - let reader = ReadSession::open(&folder).expect("open the store for reading"); + let reader = support::open_reader(&folder, None); assert_eq!(reader.declaration("t").expect("a reader's"), printed); - let again = support::open(&support::folder("index-clauses-again")); - for statement in printed.split_inclusive(";\n") { - support::run(&again, statement); - } - assert_eq!(again.declaration("t").expect("the declaration"), printed); + support::assert_roundtrips("index-clauses", &db, &["t"]); } #[test] @@ -1394,39 +1400,39 @@ fn the_index_clauses_are_refused_by_kind() { "quantization has an invalid vector policy value", ), ( - "VECTOR(4) AUTO_INDEX_AT 0", - Issue::AutoIndexAtNotPositive, - "AUTO_INDEX_AT must be a positive integer", + "VECTOR(4) INDEXING_THRESHOLD 0", + Issue::IndexingThresholdNotPositive, + "INDEXING_THRESHOLD must be a positive integer", ), ( - "VECTOR(4) AUTO_INDEX_AT -1", - Issue::AutoIndexAtNotPositive, - "AUTO_INDEX_AT must be a positive integer", + "VECTOR(4) INDEXING_THRESHOLD -1", + Issue::IndexingThresholdNotPositive, + "INDEXING_THRESHOLD must be a positive integer", ), ( - "VECTOR(4) AUTO_INDEX_AT 18446744073709551616", - Issue::AutoIndexAtOutOfRange, - "AUTO_INDEX_AT is outside the persisted numeric range", + "VECTOR(4) INDEXING_THRESHOLD 18446744073709551616", + Issue::IndexingThresholdOutOfRange, + "INDEXING_THRESHOLD is outside the persisted numeric range", ), ( - "VECTOR(4) CONSOLIDATION (CHANGE_PERCENT = 0)", - Issue::ConsolidationPercentOutOfRange, - "vector consolidation percentages must be integers from 1 through 100", + "VECTOR(4) COMPACTION (CHANGE_PERCENT = 0)", + Issue::CompactionPercentOutOfRange, + "vector compaction percentages must be integers from 1 through 100", ), ( - "VECTOR(4) CONSOLIDATION (CHANGE_PERCENT = 101)", - Issue::ConsolidationPercentOutOfRange, - "vector consolidation percentages must be integers from 1 through 100", + "VECTOR(4) COMPACTION (CHANGE_PERCENT = 101)", + Issue::CompactionPercentOutOfRange, + "vector compaction percentages must be integers from 1 through 100", ), ( - "VECTOR(4) CONSOLIDATION (TOMBSTONE_PERCENT = -5)", - Issue::ConsolidationPercentOutOfRange, - "vector consolidation percentages must be integers from 1 through 100", + "VECTOR(4) COMPACTION (TOMBSTONE_PERCENT = -5)", + Issue::CompactionPercentOutOfRange, + "vector compaction percentages must be integers from 1 through 100", ), ( - "VECTOR(4) CONSOLIDATION (CHANGE_PERCENT = 20, TOMBSTONE_PERCENT = 0)", - Issue::ConsolidationPercentOutOfRange, - "vector consolidation percentages must be integers from 1 through 100", + "VECTOR(4) COMPACTION (CHANGE_PERCENT = 20, TOMBSTONE_PERCENT = 0)", + Issue::CompactionPercentOutOfRange, + "vector compaction percentages must be integers from 1 through 100", ), ]; for (declared, wanted, sentence) in refused { @@ -1447,7 +1453,7 @@ fn the_index_clauses_are_refused_by_kind() { "{name} (...) is not part of this library: the index sizes its own groups and measures \ how far a search scans; for the true nearest rows write USE VECTOR EXACT or \ SEARCH_MODE EXACT, and to move the size from which AUTO uses the index write \ - AUTO_INDEX_AT" + INDEXING_THRESHOLD" ) }; for (declared, sentence) in [ @@ -1472,65 +1478,6 @@ fn the_index_clauses_are_refused_by_kind() { other => panic!("{sql}\nwas not refused by name: {other:?}"), } } - // A CONSOLIDATION list that is empty, names a member twice or names another member, and - // a clause out of its place, are syntax errors. - for declared in [ - "VECTOR(4) CONSOLIDATION ()", - "VECTOR(4) CONSOLIDATION (CHANGE_PERCENT = 20, CHANGE_PERCENT = 30)", - "VECTOR(4) CONSOLIDATION (LISTS = 20)", - "VECTOR(4) AUTO_INDEX_AT 1000 SEARCH_MODE EXACT", - "VECTOR(4) AUTO_INDEX_AT 1000 WITH (quantization = 'SQ8')", - ] { - let sql = with_vector(declared); - match support::refusal(&db, &sql) { - Error::ParseError(_) => {} - other => panic!("{sql}\nwas refused as {other:?}"), - } - } assert!(db.table_names().is_empty(), "a refused statement declared"); assert_eq!(db.committed_watermark(), fresh); } - -#[test] -fn the_inspection_statements_are_read() { - let folder = support::folder("inspection-statements"); - let db = support::open(&folder); - declare(&db, "docs", ""); - let reader = ReadSession::open(&folder).expect("open the store for reading"); - // Every form, in any letter case, with the rows it returns from a store of one column - // with no key and no vector: one index and its one partition. - let forms = [ - ("SHOW VECTOR_INDEXES", 1), - ("show vector_indexes", 1), - ("SHOW VECTOR_PARTITIONS", 1), - ("SHOW VECTOR_PARTITIONS FOR docs.v", 1), - ("show vector_partitions for docs.v limit 5", 1), - ("SHOW VECTOR_PARTITIONS LIMIT 0", 0), - ("SHOW VECTOR_PARTITIONS LIMIT 1 OFFSET 0", 1), - ("SHOW VECTOR_PARTITIONS FOR docs.v LIMIT 1 OFFSET 1", 0), - ]; - let before = db.committed_watermark(); - let tx = db.transaction().expect("begin"); - for (sql, rows) in forms { - assert_eq!(support::rows(&db, sql).len(), rows, "{sql}"); - assert_eq!( - support::rows(&tx, sql).len(), - rows, - "{sql}, in a transaction" - ); - assert_eq!(support::rows(&reader, sql).len(), rows, "{sql}, a reader"); - } - tx.rollback(); - assert_eq!(db.committed_watermark(), before); - // OFFSET stands only after LIMIT, and FOR names a table and a column. - for sql in [ - "SHOW VECTOR_PARTITIONS OFFSET 1", - "SHOW VECTOR_PARTITIONS FOR docs", - "SHOW VECTOR_INDEXES FOR docs.v", - ] { - match support::refusal(&db, sql) { - Error::ParseError(_) => {} - other => panic!("{sql}\nwas refused as {other:?}"), - } - } -} diff --git a/v2/contextdb/tests/vectors_upkeep.rs b/v2/contextdb/tests/vectors_upkeep.rs index 2de8f158a..65c98d3a4 100644 --- a/v2/contextdb/tests/vectors_upkeep.rs +++ b/v2/contextdb/tests/vectors_upkeep.rs @@ -9,8 +9,7 @@ use std::fs; use std::sync::atomic::Ordering; use contextdb::{ - Database, DatabaseOpenOptions, MaintenanceReport, QueryResult, ReadSession, ReadSessionOptions, - Value, params, + Database, DatabaseOpenOptions, MaintenanceReport, QueryResult, ReadSession, Value, params, }; use support::{Child, Run}; @@ -36,7 +35,7 @@ fn sealing_advances_only_when_asked_and_in_bounded_cycles() { support::declare_docs( &db, DIMENSION, - "PARTITION_KEY (ctx) AUTO_INDEX_AT 1000000000", + "PARTITION_KEY (ctx) INDEXING_THRESHOLD 1000000000", ); // Five thousand vectors: three thousand under a, the partition made first, and two // thousand under b. @@ -364,11 +363,7 @@ fn looping(role: &support::Role) { /// announces the answer's line and `reads `, the storage reads the search made. Then it /// searches once more and announces that answer's line. fn stopped(role: &support::Role) { - let (door, searching, reads) = support::pausing_at_read(role.number("pause_at")); - let mut options = ReadSessionOptions::default(); - options.storage = Some(door); - let reader = - ReadSession::open_with_options(&role.folder, options).expect("open the store for reading"); + let (reader, searching, reads) = support::reader_pausing(role); let (sql, query) = (search_of_ten(), searched_for()); searching.store(true, Ordering::SeqCst); @@ -393,7 +388,7 @@ fn a_small_fixed_store_stays_within_its_recorded_size() { let db = support::open(&folder); support::run( &db, - "CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT NOT NULL, embedding VECTOR(384) AUTO_INDEX_AT 1000000000)", + "CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT NOT NULL, embedding VECTOR(384) INDEXING_THRESHOLD 1000000000)", ); // Nothing in the content, its order or the store depends on a clock, a random number or a // thread, so the file has the same length on every machine and every run. @@ -433,7 +428,7 @@ fn a_small_fixed_store_stays_within_its_recorded_size() { /// The dimension of the tests of a grouping, and the clause under which a partition of 2,000 /// rows is cut into groups. const GROUPED: usize = 16; -const AT_1000: &str = "AUTO_INDEX_AT 1000"; +const AT_1000: &str = "INDEXING_THRESHOLD 1000"; fn gathered(n: i64) -> Vec { support::gathered(n, GROUPED) @@ -468,7 +463,7 @@ fn a_grouping_is_built_in_bounded_cycles_and_switched_in_one() { let db = support::open(&folder); // 2,000 rows are this column's size, and half of the 4,000 vectors a partition of it may // have outside a grouping and still be searched INDEXED: every search below is served. - support::declare_docs(&db, GROUPED, "AUTO_INDEX_AT 2000"); + support::declare_docs(&db, GROUPED, "INDEXING_THRESHOLD 2000"); support::load_docs(&db, 1..=2000, "a", gathered); let query = gathered(60_000); let late = support::vector(60_001, GROUPED); @@ -589,7 +584,7 @@ fn vectors_sealed_while_a_first_build_starts_are_found_after_the_switch() { let folder = support::folder("sealed-while-first-build-starts"); let db = support::open(&folder); // The grouping is never built again, so the vectors sealed after it stay in its tail. - support::declare_docs(&db, WIDE, "AUTO_INDEX_AT 1000 CONSOLIDATION NONE"); + support::declare_docs(&db, WIDE, "INDEXING_THRESHOLD 1000 COMPACTION NONE"); support::load_docs(&db, 1..=2000, "a", wide); // The first cycle seals and begins the partition's first build. The 3,500 rows written // then are sealed by the second, before the build's first round: a whole block of them @@ -621,7 +616,7 @@ fn vectors_sealed_while_a_first_build_starts_are_found_after_the_switch() { #[test] fn a_grouping_holds_every_live_vector_once_and_no_stale_slot() { - let clauses = "PARTITION_KEY (ctx) AUTO_INDEX_AT 1000"; + let clauses = "PARTITION_KEY (ctx) INDEXING_THRESHOLD 1000"; let (_, db) = support::built("grouping-no-stale", GROUPED, clauses, 1000); support::load_docs(&db, 1001..=2000, "b", gathered); support::upkeep(&db); @@ -668,7 +663,7 @@ fn a_partition_is_grouped_again_only_when_its_changes_reach_the_declared_share() ("regroup-default", "", 400_i64), ( "regroup-declared", - " CONSOLIDATION (CHANGE_PERCENT = 50)", + " COMPACTION (CHANGE_PERCENT = 50)", 1000, ), ] { @@ -695,8 +690,8 @@ fn a_partition_is_grouped_again_only_when_its_changes_reach_the_declared_share() support::cycle(&db); assert_eq!(state(&db), named("building", "tombstones")); - // Under CONSOLIDATION NONE the first grouping stays, whatever changes. - let clauses = format!("{AT_1000} CONSOLIDATION NONE"); + // Under COMPACTION NONE the first grouping stays, whatever changes. + let clauses = format!("{AT_1000} COMPACTION NONE"); let (_, db) = support::built("regroup-none", GROUPED, &clauses, 2000); support::load_docs(&db, 2001..=3000, "a", gathered); support::run(&db, "DELETE FROM docs WHERE id <= 500"); @@ -713,7 +708,7 @@ fn a_cycle_under_a_tight_limit_records_the_stall_and_the_old_grouping_serves() { // the limit leaves 98,304 over what an open sets aside. const WIDE: usize = 512; const LIMIT: usize = (9 << 20) + (96 << 10); - let (folder, db) = support::built("stalled-build", WIDE, "AUTO_INDEX_AT 200", 400); + let (folder, db) = support::built("stalled-build", WIDE, "INDEXING_THRESHOLD 200", 400); support::load_docs(&db, 401..=480, "a", |n| support::gathered(n, WIDE)); // This cycle seals the 80 and begins the regrouping they make due. assert_eq!(support::cycle(&db).maintenance_vectors_done, 80); diff --git a/v2/contextdb/tests/visibility.rs b/v2/contextdb/tests/visibility.rs index 6d3c78906..dc32ccf16 100644 --- a/v2/contextdb/tests/visibility.rs +++ b/v2/contextdb/tests/visibility.rs @@ -5,42 +5,14 @@ mod support; -use std::collections::{BTreeSet, HashMap}; +use std::collections::HashMap; -use contextdb::{ - ContextId, Database, DatabaseOpenOptions, Error, Principal, ScopeLabel, Uuid, Value, params, -}; +use contextdb::{Database, Error, Principal, Uuid, Value, params}; -use support::Run; +use support::{Run, acl, context, context_set, ids, in_contexts, label_set}; // ---- who is asking ---- -/// Context number `n`. -fn context(n: u128) -> Uuid { - Uuid::from_u128(0x00C0_0000 + n) -} - -/// Access-control id number `n`. -fn acl(n: u128) -> Uuid { - Uuid::from_u128(0x00AC_0000 + n) -} - -fn context_set(numbers: &[u128]) -> BTreeSet { - numbers - .iter() - .map(|n| ContextId::new(context(*n))) - .collect() -} - -fn label_set(names: &[&str]) -> BTreeSet { - names.iter().map(|name| ScopeLabel::new(*name)).collect() -} - -/// A handle narrowed to the Contexts with these numbers. -fn in_contexts(db: &Database, numbers: &[u128]) -> Database { - db.scoped_with_contexts(context_set(numbers)) -} - /// A handle narrowed to these scope labels. fn with_labels(db: &Database, names: &[&str]) -> Database { db.scoped_with_constraints(None, Some(label_set(names)), None) @@ -61,23 +33,6 @@ fn human(name: &str) -> Principal { // ---- what a statement answered ---- -/// The first column of every row a statement returns, which must be an INTEGER. -fn ids(on: &impl Run, sql: &str) -> Vec { - ids_with(on, sql, ¶ms! {}) -} - -fn ids_with(on: &impl Run, sql: &str, values: &HashMap) -> Vec { - let result = match on.run(sql, values) { - Ok(result) => result, - Err(error) => panic!("{sql}\nwas refused: {error:?}"), - }; - let first = |row: &Vec| match row.first() { - Some(Value::Int64(id)) => *id, - other => panic!("{sql}\nreturned {other:?} where an INTEGER was wanted"), - }; - result.rows().iter().map(first).collect() -} - /// The ids `SELECT id FROM
` returns. fn seen(on: &impl Run, table: &str, tail: &str) -> Vec { ids(on, &format!("SELECT id FROM {table} {tail}")) @@ -756,7 +711,7 @@ fn a_hidden_row_named_whole_is_refused_and_a_list_read_leaves_it_out(gate: Gate) "SELECT payload FROM ledger WHERE slug = 'shut-two'", "SELECT payload FROM ledger WHERE a = 1 AND b = 2", "SELECT payload FROM ledger WHERE b = 2 AND a = 2", - "SELECT id, slug, a, b, payload FROM ledger WHERE id = 4", + "SELECT payload FROM ledger WHERE id = (SELECT 2)", "SELECT id FROM ledger WHERE slug = 'shut-four'", ] { refused(&handle, sql, rule, "ledger"); @@ -1370,12 +1325,48 @@ fn a_search_returns_the_nearest_rows_the_handle_may_see_and_no_hidden_row() { } } + let tags = "CREATE TABLE tags (id INTEGER PRIMARY KEY, c UUID NOT NULL CONTEXT_ID, label TEXT \ + SCOPE_LABEL_READ ('a', 'b') WRITE ('a', 'b'), v VECTOR(1) PARTITION_KEY (c))"; + support::run(&db, tags); + let c = context(1); + let row = format!("INSERT INTO tags VALUES (1, '{c}', 'b', [1.0])"); + support::run(&db, &row); + let by_label = with_labels(&in_contexts(&db, &[1]), &["a"]); + let sql = support::nearest_sql("tags", "v", None, 2); + let found = support::search(&by_label, &sql, &[1.0]).expect("a search"); + assert_eq!(found.rows().len(), 0, "the nearest row is under label b"); + let said = by_label.explain(&sql).expect("explained"); + assert!(!said.contains(&c.to_string()), "no partition told"); + let keys = "CREATE TABLE keys (id INTEGER PRIMARY KEY, c UUID NOT NULL CONTEXT_ID, acl_id UUID \ + ACL REFERENCES acl_grants(acl_id), v VECTOR(1) PARTITION_KEY (c))"; + support::run(&db, keys); + let row = format!("INSERT INTO keys VALUES (1, '{c}', '{}', [1.0])", acl(1)); + support::run(&db, &row); + let said = reader_in_one + .explain(&sql.replace("tags", "keys")) + .expect("explained"); + assert!( + !said.contains(&c.to_string()), + "an access list may hide rows" + ); // With no principal that holds grants the search is refused like any read of the table. let sql = support::nearest_sql("passages", "v", None, 5); - match support::search(&in_contexts(&db, &[1]), &sql, &query) { - Err(Error::PrincipalRequired { table }) => assert_eq!(table, "passages"), - other => panic!("{sql}\nthrough a handle with no principal gave {other:?}"), + for asked in [support::nearest_sql("passages", "v", None, 0), sql.clone()] { + match support::search(&in_contexts(&db, &[1]), &asked, &query) { + Err(Error::PrincipalRequired { table }) => assert_eq!(table, "passages"), + other => panic!("{asked}\nthrough a handle with no principal gave {other:?}"), + } + } + // Explaining it is refused alike, and a principal that holds grants is told the filter path. + for said in [&sql, "INSERT INTO passages (id) VALUES (1)"] { + let r = in_contexts(&db, &[1]).explain(said); + assert!(matches!(r, Err(Error::PrincipalRequired { .. })), "{r:?}"); } + let filtered = support::nearest_sql("passages", "v", Some("id > 10"), 5); + let text = reader_in_one + .explain(&filtered) + .expect("a principal explains"); + assert!(text.contains("filter_path:"), "{text}"); } // ---- a handle made from a narrowed handle ---- @@ -1476,9 +1467,7 @@ fn twenty_four_thousand_access_ids_are_read_under_a_limit_with_no_room_to_rememb // 64 KiB and a row eight times over, and do not hold an entry for each id: 24,000 ids of // 16 bytes alone are 384,000 bytes, and the 12,000 that are granted are 192,000. let limit = 9 * MIB + 128 * KIB; - let mut options = DatabaseOpenOptions::default(); - options.memory_limit = Some(limit); - let db = support::open_with(&folder, options).expect("open the store under the limit"); + let db = support::open_limited(&folder, limit); let reader = named(&db, agent("reader")); let in_use = db.memory_used(); let granted = ROWS / 2; @@ -1598,3 +1587,30 @@ fn a_narrowed_handle_is_refused_every_declaration_and_setting_and_changes_nothin support::run(&db, sql); } } + +#[test] +fn a_ranked_search_treats_a_hidden_row_joined_by_a_unique_column_as_unmatched() { + let db = support::open(&support::folder("visibility-rank-unique")); + for sql in [ + "CREATE TABLE results (id INTEGER PRIMARY KEY, context_id UUID CONTEXT_ID, \ + task_id INTEGER UNIQUE, weight REAL)", + "CREATE TABLE tasks (id INTEGER PRIMARY KEY, v VECTOR(2) RANK_POLICY (JOIN results ON \ + task_id, FORMULA '{vector_score} * coalesce({weight}, 1.0)', SORT_KEY s))", + "INSERT INTO tasks (id, v) VALUES (1, [1.0, 0.0]), (2, [1.0, 1.0])", + ] { + support::run(&db, sql); + } + for (id, task, context_number, weight) in [(10_i64, 1_i64, 2, 0.1_f64), (11, 2, 1, 1.0)] { + let values = + params! {"id" => id, "task" => task, "c" => context(context_number), "w" => weight}; + let sql = + "INSERT INTO results (id, context_id, task_id, weight) VALUES ($id, $c, $task, $w)"; + db.execute(sql, &values).expect("insert result"); + } + let sql = "SELECT id FROM tasks ORDER BY v <=> [1.0, 0.0] USE RANK s LIMIT 2"; + assert_eq!( + ids(&in_contexts(&db, &[1]), sql), + vec![1, 2], + "a result hidden from the reader is no answer and no refusal: its task ranks as unmatched" + ); +} diff --git a/v2/contextdb/tests/visibility_grants.rs b/v2/contextdb/tests/visibility_grants.rs index fdfebe9d2..fd81ac8ac 100644 --- a/v2/contextdb/tests/visibility_grants.rs +++ b/v2/contextdb/tests/visibility_grants.rs @@ -5,35 +5,14 @@ mod support; -use std::collections::{BTreeSet, HashMap}; +use std::collections::HashMap; -use contextdb::{ContextId, Database, Error, Principal, ScopeLabel, Uuid, Value, params}; +use contextdb::{Database, Error, Principal, Value, params}; -use support::Run; +use support::{Run, acl, context, context_set, label_set}; // ---- who is asking ---- -/// Context number `n`. -fn context(n: u128) -> Uuid { - Uuid::from_u128(0x00C0_0000 + n) -} - -/// Access-control id number `n`. -fn acl(n: u128) -> Uuid { - Uuid::from_u128(0x00AC_0000 + n) -} - -fn context_set(numbers: &[u128]) -> BTreeSet { - numbers - .iter() - .map(|n| ContextId::new(context(*n))) - .collect() -} - -fn label_set(names: &[&str]) -> BTreeSet { - names.iter().map(|name| ScopeLabel::new(*name)).collect() -} - /// A handle that names this agent and nothing else. fn agent(db: &Database, name: &str) -> Database { db.scoped_with_constraints(None, None, Some(Principal::Agent(name.to_owned()))) diff --git a/v2/redb/tests/contextdb_changes.rs b/v2/redb/tests/contextdb_changes.rs index bcec71ca1..e0031d102 100644 --- a/v2/redb/tests/contextdb_changes.rs +++ b/v2/redb/tests/contextdb_changes.rs @@ -171,34 +171,6 @@ fn rows_at(rows: RangeInclusive, version: u64) -> Vec<(u64, Vec)> { rows.map(|row| (row, value(row, version))).collect() } -#[test] -fn a_file_a_writer_holds_opens_for_reading_at_the_newest_commit() { - let path = folder("a-file-a-writer-holds-opens-for-reading").join("data"); - let writer = writer(&path); - commit_rows(&writer, 1..=3, 1); - - let first = reader(&path); - let earlier = first.begin_read().unwrap(); - assert_eq!(rows_of(&earlier), rows_at(1..=3, 1)); - let earlier = earlier.commit_id(); - - // The writer goes on committing beside the reader, and is never made to wait or to fail. - commit_rows(&writer, 4..=5, 1); - commit_rows(&writer, 1..=1, 2); - let mut newest = rows_at(1..=1, 2); - newest.extend(rows_at(2..=5, 1)); - - // The same reader, asked again, reads the commit that is newest now, and says it is a - // later one. - let later = first.begin_read().unwrap(); - assert_eq!(rows_of(&later), newest); - assert!(later.commit_id() > earlier); - - // So does a reader that opens now. - let second = reader(&path); - assert_eq!(rows_of(&second.begin_read().unwrap()), newest); -} - /// The id and the rows of the commit a reader is given now, or why it was given none. fn newest(reader: &ReadOnlyDatabase) -> Result<(u64, Vec<(u64, Vec)>), redb::Error> { let read = reader.begin_read()?;