Skip to content

Add SQLite input/output format - #104510

Merged
alexey-milovidov merged 245 commits into
ClickHouse:masterfrom
niyue:feat/sqlite-format
Oct 1, 2026
Merged

alexey-milovidov merged 245 commits into
ClickHouse:masterfrom
niyue:feat/sqlite-format

Conversation

@niyue

@niyue niyue commented May 10, 2026 •

Copy link
Copy Markdown
Contributor

Adds SQLite input/output format support, including schema inference, direct local-file access, and fail-closed predicate pushdown for the SQLite table engine and table function.

Closes: #33763

Changelog category (leave one):

  • New Feature

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

  • Added support for reading and writing data in the SQLite format.

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

Version info

  • Merged into: 26.10.1.1133-master (included in 26.10 and later)

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [60f71b8]

Summary: ✅


AI Review

Summary

This PR adds SQLite input/output format support and tightens the SQLite engine and table-function behavior around query-backed reads, generated columns, and pushdown. The remaining issue is in the source Documentation block for query-backed schema inference: it still documents the pre-fix NULL and empty-result behavior, so the current PR head would publish a contract that contradicts the code and the new regression test.

Findings

💡 Nits

  • [src/Storages/StorageSQLite.cpp:808] The query-backed inference paragraph still says that a first-row NULL or an empty result gives String, but declaredTypeAgreesWithStorageClass and 05238_sqlite_query_schema_null_first_row now keep the declared numeric type in both cases. Because this Documentation block is the source of truth for the autogenerated SQLite engine page, the stale sentence also still propagates into docs/reference/engines/table-engines/integrations/sqlite.mdx and docs/reference/functions/table-functions/sqlite.mdx. Update this paragraph so it matches the actual NULL and empty-result contract before regenerating the docs.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: Fix the query-backed inference paragraph in src/Storages/StorageSQLite.cpp so it says a first-row NULL and an empty result keep the declared type, then regenerate the affected sqlite.mdx pages.

LLVM Coverage Report

Measured on commit 60f71b8.

Metric Baseline Current Δ
Lines 87.90% 87.90% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 1537/1699 (90.46%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label May 10, 2026
@niyue
niyue force-pushed the feat/sqlite-format branch from ab4f0a7 to 747b96d Compare May 10, 2026 12:33
Comment thread docs/en/interfaces/formats/SQLite.md Resolved
@niyue
niyue force-pushed the feat/sqlite-format branch from a80bdb7 to 8d470d6 Compare May 10, 2026 14:10
@niyue
niyue force-pushed the feat/sqlite-format branch from 6f68849 to 2f152db Compare May 11, 2026 02:28
@alexey-milovidov

Copy link
Copy Markdown
Member

The FileCacheTest.SLRUFreeSpaceKeepingProtectedOnly failure on this PR is a known flaky test that was fixed in #104418. Could you please update the branch with the latest master to pick up the fix?

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed bbe24f93c233..9be96d0a5517: merge of master (817 commits) to resolve the conflict GitHub reported.

The one conflict, in src/Storages/StorageSQLite.cpp, came from master's a795783 (SQL injection through identifiers in SQLiteSink). That commit changed the two identifiers of the sink's INSERT statement to doubleQuoteStringSQLite. This branch had already rewritten the same statement into a prepared INSERT ... VALUES (?, ...) that quotes both identifiers with quoteSQLiteIdentifier (backquotes, an embedded backquote doubled). Both escapings are correct for SQLite. I kept the branch side, so the merged file is byte-identical to the branch's version. Master's new 05055_sqlite_insert_identifier_escaping should still pass on the prepared path: the generated-column probe binds the table name as a parameter and returns quietly for a missing table, and the INSERT failures still carry no such table, no column named and unrecognized token.

Checks: the merge changes the same 208 files as the branch. Its diff against master equals the branch's pre-merge diff except for the two removed lines of the conflict hunk, which now show master's text. None of master's new commits touches an API whose signature this branch changes. There is no local build of this head, so compiling is left to CI. The fork workflow run is approved and running.

CI on bbe24f93 was fully green (159 passed, 0 failed) and there are 0 unresolved review threads. The remaining AI Review Major (legacy-analyzer self-join) is answered in #104510 (comment) and its correction.

Comment thread src/Databases/SQLite/SQLiteUtils.cpp Resolved
Comment thread src/Storages/StorageSQLite.cpp Resolved
alexey-milovidov and others added 3 commits September 24, 2026 17:13
Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A query-backed `ENGINE = SQLite(path, query('...'))` source is read-only, so
materializing an empty database on `CREATE TABLE` with an explicit column list
only defers the failure to the first `SELECT`. Keep `allow_create` off for
`table_or_query.isQuery`, so the `CREATE` fails closed like the schema-inference
path, and extend `05137` with the explicit-schema query-backed case.

Addresses review: ClickHouse#104510 (comment)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Storages/StorageSQLite.cpp Resolved
Comment thread src/Storages/StorageSQLite.cpp Resolved
…ety only for filtered columns

Concurrent `INSERT`s into one `SQLite` database failed with `database is locked`: every sink has its own
connection and a deferred `BEGIN` only takes the writer lock on the first `sqlite3_step`, where SQLITE_BUSY
cannot be retried inside an explicit transaction. Chunk transactions now start with `BEGIN IMMEDIATE`, and
`BEGIN IMMEDIATE` / `COMMIT` are retried on SQLITE_BUSY with a bounded, cancellable wait
(`executeSQLiteRetryOnBusy`). Polling alone starves a writer while others commit back to back, so the
writers of this server are additionally queued on a per-database mutex keyed on `sqlite3_db_filename`.

The pushdown-safety gate probed every physical column (with a `pragma_table_list` lookup each) on every
table-backed read. It now checks only the columns referenced by the `WHERE` / `PREWHERE` of the query tree
(nothing for a filterless read), and `isStrictTable` is looked up once per read.

Tests: `05259_sqlite_storage_concurrent_inserts`, `05260_sqlite_pushdown_filter_referenced_columns`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…a paths

`openSQLiteDB` always used `SQLITE_OPEN_READWRITE`, so a plain `SELECT`, `DESCRIBE`
or `SHOW TABLES` through the `sqlite` table function, the `SQLite` table engine or
the `SQLite` database engine could modify the file: a read-write connection rolls
back and deletes a hot journal left by a crashed writer. Replace the `allow_create`
flag with `SQLiteOpenMode` (`ReadOnly`, `ReadWrite`, `ReadWriteCreate`) and use
`ReadOnly` for every connection that only reads data or metadata. Only
`StorageSQLite::write` opens the file read-write, and only a genuine `CREATE` with
an explicit column list (or `CREATE DATABASE`) may create it. A read over a hot
journal now fails with `attempt to write a readonly database` and leaves the file
untouched, like the `SQLite` input format.

Also add a test for `Bool` in `FORMAT SQLite`: it is already declared as `INTEGER`
(`Bool` is stored as `UInt8`, so `WhichDataType::isUInt` is true) and inferred
back as a number.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Addressed the AI review on 49e4caa5 in 57cdb7bea026:

  • Read paths now open the file read-only (Major 1, adopted). openSQLiteDB takes a SQLiteOpenMode. Scans, schema fetches, table discovery and the table function all use SQLITE_OPEN_READONLY. Only INSERT opens the file read-write, and only an explicit-schema CREATE TABLE or a CREATE DATABASE may create a missing file. Because of this, a SELECT over a hot journal from a crashed writer now fails instead of rolling the journal back. New test: 05261.
  • Bool in FORMAT SQLite (Major 2): the premise is wrong. Bool has TypeIndex::UInt8, so it is already declared as INTEGER and inferred back as Int64; I checked this with the built binary. I added the requested round-trip test, 05262.

All 93 *sqlite* stateless tests pass locally. Both threads have replies and are resolved, and main-repo run 36467609536 is approved.

…EGIN IMMEDIATE`

Mirror the transaction strategy of the `SQLite` storage sink in the direct
local-file `FORMAT SQLite` path: `BEGIN IMMEDIATE` and `COMMIT` go through
`executeSQLiteRetryOnBusy`, so another connection holding a lock on the
same database makes the export wait (bounded, cancellable) instead of
failing with `database is locked`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=104510&sha=57cdb7bea0267392d81b549665ebf98cc0d145a7&name_0=PR&name_1=Stateless%20tests%20(arm_binary%2C%20parallel) (05045_opentelemetry_parallel_replicas_coordinator_spans, CANNOT_READ_ALL_DATA while reading a MergeTree part through ReadPoolParallelReplicas, which this PR does not touch) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is already in progress: #116920. It is not merged yet, so this build did not have it.

I reproduced the failure on master 39646eef (x86-64 debug) with the failing run's table and query settings taken from its query_log, which make all_1_1_0 a Wide part in Packed storage with a sparse k. The test's select sum(k) under parallel replicas failed 98 of 440 runs with CANNOT_READ_ALL_DATA on the same file at mark 1024, 34 of them with exactly this message. With only the src/IO/ReadBufferFromFileView.cpp change from #116920 applied to the same master, it passed 240 of 240 runs on the same on-disk part and returned the correct sum.

The same read without parallel replicas passed 150 of 150. Each range the coordinator assigns reuses the part's stream and raises its read bound, and ReadBufferFromFileView did not re-derive its buffer end after such a raise, which is what #116920 fixes.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 1, 2026
Merged via the queue into ClickHouse:master with commit 3c271e9 Oct 1, 2026
150 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 1, 2026
clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Oct 2, 2026
The `Documentation` of the `SQLite` table engine and table function said that
a `NULL` first value and an empty result give `String`. That is only true for
a column without a declared type: `declaredTypeAgreesWithStorageClass` keeps a
declared numeric type in both cases, as pinned by
`05238_sqlite_query_schema_null_first_row`. Generated docs will be refreshed
by the autogeneration workflow.

Related: ClickHouse#104510

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
alexey-milovidov added a commit to JTCunning/ClickHouse that referenced this pull request Oct 4, 2026
After merging master:

- `tryReadFloatText` is gone from master (precise parsing is the default);
  use `tryReadFloatTextPrecise`.
- The legacy `docs/en` tree was removed and every format must carry
  structured documentation (`04514_every_format_must_have_documentation`).
  Move the page into `setDocumentation`, add
  `docs/reference/formats/OpenMetrics.mdx` with the autogenerated region,
  the `navigation.json` entry and the overview-table row, and rewrite the
  links to the `/reference/...` routes (as done for `SQLite` in ClickHouse#104510).
- The `TimeSeries` outer column `time_series` was renamed to `samples`
  (version 3), and the metrics target became metric families with a
  `metric_family` column. The format mirrors the engine's outer columns, so
  the points column is now `samples`; `time_series` is still accepted, as
  in `TimeSeries` tables of version 2 and earlier.
- `SELECT * FROM <TimeSeries table>` works on master now, so make
  `SELECT * ... FORMAT OpenMetrics` and `INSERT ... FORMAT OpenMetrics`
  round-trip: the writer takes the `__name__` tag as the sample name instead
  of emitting it as a label, accepts the metadata-only rows returned for
  each metric family, and accepts `LowCardinality` string columns. The
  skipped integration test for this is replaced by a stateless test, and the
  remaining integration test uses `timeSeriesMetricFamilies` and
  `metric_family`.

Review feedback from `clickhouse-gh`:

- Reject raw control characters in quoted label values on input; the writer
  cannot emit them.
- Validate metric family names in `# HELP`, `# TYPE` and `# UNIT`.
- Reject `# TYPE` tokens outside the OpenMetrics type vocabulary.
- Enforce the per-type sample-name suffix rule on output for `counter`,
  `histogram`, `gaugehistogram`, `summary` and `info` (sample name = family
  name + suffix), with one suffix table shared with the reader's family
  folding; require `le` on histogram buckets (on input too) and `quantile`
  on bare summary samples.
- Convert between `DateTime64` scales and milliseconds with overflow checks
  instead of unchecked multiplication.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator

Fix for 03634_autopr_output_bytes_estimation: #123807 (the query_12 over-estimate seen on master; #122367 already covered query_43).

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

Labels

can be tested Allows running workflows for external contributors comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). manual approve Manual approve required to run CI pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SQLite as input/output format.

5 participants