Skip to content

Support passing a query to the mysql, postgresql and sqlite table functions and engines - #107740

Merged
alexey-milovidov merged 13 commits into
masterfrom
external-db-query-passing
Jul 1, 2026
Merged

alexey-milovidov merged 13 commits into
masterfrom
external-db-query-passing

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 17, 2026 •

Copy link
Copy Markdown
Member

Generalizes the idea of #79652 (which added query passing for the mysql table function and engine) to all native SQL external-database integrations: mysql, postgresql, and sqlite, both as table functions and as table engines.

Instead of a remote table name, the table argument can now be a SELECT query that is passed to the external database as is, written either as a subquery (SELECT ...) or wrapped into query('SELECT ...'):

SELECT * FROM mysql('host:3306', 'db', query('SELECT a, b FROM t1 JOIN t2 USING (id) WHERE a > 0'), 'user', 'pw');
SELECT * FROM postgresql('host:5432', 'db', (SELECT a, b FROM t1 WHERE a > 0), 'user', 'pw');
SELECT * FROM sqlite('db.sqlite', query('SELECT a, b FROM t'));

CREATE TABLE x ENGINE = MySQL('host:3306', 'db', query('SELECT ...'), 'user', 'pw');

This is useful to push down joins, aggregations and arbitrary processing to the external database. The structure of such a table is inferred from the query result; the table is read-only and INSERT into it throws INCORRECT_QUERY.

Implementation

  • A shared TableNameOrQuery abstraction holds either a table name or a query, with a common argument parser and read-projection builder reused by all three integrations.
  • mysql: a new convertMySQLDataType(MYSQL_FIELD &) overload and mysqlxx::ResultBase::getField; the structure is inferred by running the query with LIMIT 0.
  • postgresql: the structure is inferred from the result column type OIDs of SELECT * FROM (<query>) AS __subquery LIMIT 0, executed in a read-only transaction so it also works against read-only replicas.
  • sqlite: the structure is inferred from the prepared statement's column metadata.

odbc/jdbc are intentionally not covered (their schema inference is performed by the external bridge process and would require bridge-protocol changes), and neither is mongodb (it is not SQL-based).

Tests: a stateless test for sqlite and integration tests for mysql and postgresql. Documentation updated for the three table functions.

Changelog category (leave one):

  • New Feature

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

Added support for the mysql, postgresql, and sqlite table functions and table engines to accept a user's query (instead of a table name) and pass it to the external database as is, written either as a subquery (SELECT ...) or as query('SELECT ...'). The structure of the resulting table is inferred from the query result, and such a table is read-only. Closes #46758.

Version info

  • Merged into: 26.7.1.320 (included in 26.7 and later)

alexey-milovidov and others added 2 commits June 17, 2026 02:52
…e integrations

Generalizes the idea of #79652
(which added it for `mysql`) to all native SQL external-database integrations:
`mysql`, `postgresql` and `sqlite`, both as table functions and as table engines.

Instead of a remote table name, the table argument can now be a `SELECT` query
that is passed to the external database as is, written either as a subquery
`(SELECT ...)` or wrapped into `query('SELECT ...')`:

    SELECT * FROM mysql('host:3306', 'db', query('SELECT a, b FROM t WHERE a > 0'), 'user', 'pw');
    SELECT * FROM postgresql('host:5432', 'db', (SELECT a, b FROM t WHERE a > 0), 'user', 'pw');
    SELECT * FROM sqlite('db.sqlite', query('SELECT a, b FROM t'));

This is useful to push down joins, aggregations and arbitrary processing to the
external database. The structure of such a table is inferred from the query result;
the table is read-only and `INSERT` into it throws `INCORRECT_QUERY`.

Implementation:
- New shared `TableNameOrQuery` abstraction (`src/Storages/TableNameOrQuery.h/.cpp`)
  holding either a table name or a query, plus the argument parser
  `tryGetExternalDatabaseQuery` and the read-projection builder
  `buildQueryForExternalDatabaseSubquery`.
- MySQL: new `convertMySQLDataType(MYSQL_FIELD &)` overload and `mysqlxx::ResultBase::getField`;
  the structure is inferred by running the query with `LIMIT 0`.
- PostgreSQL: `convertPostgreSQLDataType` is exposed; the structure is inferred from
  the result column OIDs of `SELECT * FROM (<query>) AS __subquery LIMIT 0` executed in a
  read-only transaction (works against read-only replicas as well).
- SQLite: `convertSQLiteDataType` is exposed; the structure is inferred from the prepared
  statement's column metadata.

Tests: a stateless test for `sqlite` and integration tests for `mysql` and `postgresql`.
Docs updated for the three table functions.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- PostgreSQL: resolve the result column type names with
  `unnest(...) WITH ORDINALITY ... ORDER BY ord` and explicit column aliases,
  so the resolved types stay aligned with the result columns unambiguously.
- MySQL integration test: assert the number of projected columns by counting
  tab-separated fields of a row instead of the invalid `count(columns('.*'))`
  / `DESCRIBE`-as-subquery forms.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9b2ca44]

Summary: ✅


AI Review

Summary

This PR adds query-backed mysql, postgresql, and sqlite table functions and table engines, with schema inference, read-only enforcement, docs, and regression coverage. The prior review threads appear addressed in the current code, but MySQL query-result schema inference still maps all spatial result columns to Point, which breaks non-point spatial columns.

Findings

⚠️ Majors

  • [src/DataTypes/convertMySQLDataType.cpp:234] MYSQL_TYPE_GEOMETRY covers all MySQL spatial result values, not only POINT. The existing table-name path only maps COLUMN_TYPE = 'point' to ClickHouse Point and otherwise falls back to String, while this query-backed path infers Point for LINESTRING, POLYGON, or generic GEOMETRY. MySQLSource then rejects those rows with Only Point data type is supported, so mysql(..., query('SELECT linestring_col FROM t'), ...) fails even though the table-name path can read the same column as String.
    Suggested fix: keep MYSQL_TYPE_GEOMETRY as String unless the subtype is known to be POINT, or fetch enough source metadata to distinguish the subtype before mapping to Point.
Tests
  • ⚠️ Add a focused MySQL integration regression selecting a non-point spatial column, such as LINESTRING or POLYGON, through the query-backed mysql form and verify it does not infer Point and fail at read time.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: fix MySQL query-backed spatial type inference for non-point geometry values and add the regression above.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jun 17, 2026
Comment thread src/Storages/StoragePostgreSQL.cpp Resolved
Comment thread src/Storages/StoragePostgreSQL.cpp Resolved
alexey-milovidov and others added 2 commits June 19, 2026 11:01
…rence

The query-backed `PostgreSQL` schema inference (`doQueryResultStructure`)
resolved result column types from their OIDs only, via
`format_type(type_oid, NULL)`, and hard-coded every array result as
one-dimensional. This dropped two pieces of metadata that the plain
table-name path preserves through `format_type(atttypid, atttypmod)` and
`attndims`/`array_ndims`:

- Type modifiers: a `numeric(78, 0)` result column was resolved as plain
  `numeric` and fell back to a generic `Decimal128`, instead of being
  mapped to `Int256` as the table path does, so reads of supported wide
  numerics failed or exposed the wrong schema.
- Array dimensions: PostgreSQL array type OIDs do not encode dimensions, so
  an `integer[][]` result column was inferred as `Array(Int32)`, and
  `insertPostgreSQLValue` then threw `Got more dimensions than expected`
  while reading the first `{{...}}` value.

Carry the result type modifier (`column_type_modifier`, i.e. `PQfmod`) into
`format_type`, and probe the real array dimensions with `array_ndims` over
the actual query result (referencing columns positionally through an
explicit alias list to avoid relying on the result column names of an
arbitrary query). When the query returns no rows there is nothing to probe
and the dimensions stay at one (the result is empty anyway).

Extends the `postgresql` query-passing integration test to cover
query-backed reads of `numeric(78, 0)` and a multidimensional array,
verifying both the inferred types and the data.

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

Copy link
Copy Markdown
Member Author

Addressed the AI review (Request changes) on the new query-backed PostgreSQL schema inference in doQueryResultStructure:

  • Type modifiers preserved. The result column type modifier is now carried into format_type (column_type_modifier, i.e. PQfmod, → format_type(type_oid, type_mod)), matching the table path's format_type(atttypid, atttypmod). So numeric(78, 0) now resolves to numeric(78,0) and maps to Int256 instead of falling back to a generic Decimal128.
  • Array dimensions inferred. Since PostgreSQL array OIDs do not encode dimensions, the dimensions are now probed from the actual data with array_ndims over the query result (referencing columns positionally through an explicit alias list, so we do not rely on the result column names of an arbitrary query), mirroring the table path's array_ndims recheck. An integer[][] result is now inferred as Array(Array(Int32)) and no longer throws Got more dimensions than expected at read time. When the query returns no rows there is nothing to probe and the dimensions stay at one.
  • Tests. Extended the postgresql query-passing integration test to cover query-backed reads of numeric(78, 0) and a multidimensional array, asserting both the inferred types and the data.

Verified the generated SQL against PostgreSQL 15 (format_type(1700, 5111812) → numeric(78,0); the array_ndims probe over the wrapped subquery returns dims 1 and 2 for integer[]/integer[][]). StoragePostgreSQL.cpp compiles after merging master. Both review threads resolved.

Merged master (was 794 commits behind, clean merge, no conflicts).

The remaining red checks are unrelated, pre-existing master-wide flakes with open tracking issues:

Comment thread src/Storages/StorageMySQL.cpp Resolved
Comment thread src/Storages/StoragePostgreSQL.cpp Resolved
alexey-milovidov and others added 2 commits June 21, 2026 12:28
The query-backed MySQL schema inference (the `MYSQL_FIELD` overload of
`convertMySQLDataType` used by `doQueryResultStructure`) always wrapped
nullable MySQL fields into `Nullable`, ignoring the
`external_table_functions_use_nulls` setting. The table-name path applies
the setting before wrapping (see `FetchTablesColumnsList.cpp`), so a
query-backed `mysql(... query('SELECT nullable_col FROM t') ...)
SETTINGS external_table_functions_use_nulls = 0` exposed `Nullable(T)`
instead of `T`, diverging from both the table form and the documented
setting behavior.

Thread the setting into the `MYSQL_FIELD` conversion path and pass it from
`doQueryResultStructure`, and extend the MySQL query-passing integration
test with a regression assertion for both setting values.

Addresses the AI review for #107740

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… query

The query-backed PostgreSQL schema inference probes `array_ndims` over the
first row of the query result to learn an array's real number of
dimensions. When that first sampled value is `NULL` or an empty array,
`array_ndims` returns `NULL`, and the dimensions were silently left at one.
A non-empty result whose first row is empty but whose later rows contain a
multidimensional array (e.g. first row `'{}'::integer[][]`, second row
`'{{1,2},{3,4}}'`) was then inferred as `Array(Int32)` and failed at read
time with the confusing `Got more dimensions than expected`.

Throw a clear error during inference instead, matching the table-name
path's fail-early behavior in its `recheck_array` step. An empty result
(no rows) still keeps the dimensions at one, since there is nothing to read.

Extend the PostgreSQL query-passing integration test with this case.

Addresses the AI review for #107740

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

Copy link
Copy Markdown
Member Author

Addressed the two remaining AI review Majors on the query-backed schema inference:

  • MySQL — external_table_functions_use_nulls now honored (3546ef11375). The MYSQL_FIELD overload of convertMySQLDataType previously always wrapped nullable MySQL fields into Nullable, ignoring the setting, so the query form diverged from the table-name path. The overload now takes use_nulls (folded into is_nullable) and doQueryResultStructure passes settings[Setting::external_table_functions_use_nulls]. Regression assertion added to test_query_passing_table_function (Nullable(Int32) with the setting on, Int32 with it off).

  • PostgreSQL — fail early when array dimensions cannot be inferred (580d3de70a5). When the array_ndims probe over the first sampled row returns NULL (the value is NULL or an empty array) on a non-empty result, inference now throws a clear BAD_ARGUMENTS instead of silently inferring Array(Int32) and failing later at read time with Got more dimensions than expected. This matches the table path's recheck_array fail-early behavior; an empty result still keeps the dimensions at one. Regression case added to test_postgres_query_passing (first row '{}'::integer[][], second row '{{1,2},{3,4}}').

The three affected translation units (convertMySQLDataType.cpp, StorageMySQL.cpp, StoragePostgreSQL.cpp) compile cleanly with -Werror. Did not re-merge master: the branch is only ~2 days behind its merge-base and master changed none of the touched files. Both review threads resolved.

…gines

The table-function docs already describe passing a `SELECT` query instead of
a table name, but the table-engine reference pages still described the third
argument only as a remote table name and omitted the new behavior.

Document the query-backed syntax (a subquery or `query(...)`), the structure
inferred from the query result, and the read-only behavior (`INSERT` throws
`INCORRECT_QUERY`) on the `MySQL`, `PostgreSQL`, and `SQLite` table-engine
pages, mirroring the corresponding table-function docs.

Addresses the documentation finding from the AI review of #107740.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Storages/StoragePostgreSQL.cpp Resolved
The previous commit documented passing a `SELECT` query instead of a table name
on the `MySQL`, `PostgreSQL`, and `SQLite` table-engine reference pages
(`docs/en/engines/table-engines/integrations/*.md`), but the source-level
`Documentation` blocks embedded in `StorageMySQL`, `StoragePostgreSQL`, and
`StorageSQLite` (used by the storage factory for generated/help documentation)
still described the `table` argument only as a remote table name.

Mirror the same additions into the embedded `Documentation` blocks: the `table`
argument can be a `SELECT` query written as a subquery or wrapped into `query(...)`,
the structure is inferred from the query result, and such a table is read-only
(`INSERT` is not allowed). This restores parity between the two documentation
surfaces.

Addresses the documentation finding from the AI review of #107740.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Storages/TableNameOrQuery.cpp Resolved
alexey-milovidov and others added 4 commits June 26, 2026 13:27
Three user-visible contract gaps flagged in the AI review of query passing
to the `mysql`, `postgresql` and `sqlite` integrations are fixed:

1. `external_table_strict_query`. The query-backed read path passes the
   user's query to the external database verbatim and cannot push any outer
   predicate into it, so an outer filter was silently applied locally even
   under `external_table_strict_query = 1`. A new
   `rejectOuterFilterForQueryBackedExternalSourceIfStrict` reconstructs the
   outer query the same way `transformQueryForExternalDatabase` does and
   throws `INCORRECT_QUERY` when strict mode is on and the outer query has a
   filter on the source. Wired into the read path of all three storages.

2. PostgreSQL subquery dialect formatting. The `(SELECT ...)` form was
   serialized in the ClickHouse dialect (backtick identifiers, ClickHouse
   string escaping) before being sent to the external database, so an
   identifier requiring quoting was emitted with backticks that PostgreSQL
   rejects. `tryGetExternalDatabaseQuery` now formats the subquery with the
   external database's identifier-quoting and string-literal-escaping style
   (`WhenNecessary` keeps simple identifiers unquoted as before). The
   `query('...')` form is still passed through verbatim, and the docs now
   note that the subquery form must be valid ClickHouse SQL.

3. Read-only table-function inserts. `INSERT INTO TABLE FUNCTION
   mysql/postgresql/sqlite(..., query(...))` constructed the storage with
   empty cached columns, running remote schema inference (an expensive or
   volatile `SELECT`) before `write` rejected the insert. The three table
   functions now reject query-backed inserts with `INCORRECT_QUERY` in
   `getActualTableStructure` and `executeImpl`, before any external contact.

Tests: stateless `04341_sqlite_query_passing` covers strict-query rejection,
subquery identifier quoting and the early table-function insert rejection;
the `mysql` and `postgresql` integration tests gain strict-query and
table-function insert regressions, and `postgresql` also covers a quoted
identifier in the subquery form.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The previous commit rejected query-backed inserts into the `mysql`,
`postgresql` and `sqlite` table functions in both `executeImpl` and
`getActualTableStructure`, guarded by `is_insert_query`. That broke
`DESCRIBE TABLE`: `InterpreterDescribeQuery` calls
`getActualTableStructureWithAccess` with `is_insert_query = true`
unconditionally, so `DESCRIBE TABLE mysql(..., query('...'), ...)` (and
the `postgresql`/`sqlite` equivalents) was rejected with `INCORRECT_QUERY`
instead of returning the inferred structure.

`INSERT INTO TABLE FUNCTION` reaches the table function through
`ITableFunction::execute` with empty cached columns, which dispatches
directly to `executeImpl` and never calls `getActualTableStructure`. So
the `executeImpl` guard alone rejects the insert before any external
contact (the original motivation of the review fix), and the
`getActualTableStructure` guard is both redundant and harmful. Remove it,
restoring `getActualTableStructure` to the read-only form it had when the
feature was introduced.

The stateless test `04341_sqlite_query_passing` exercises both paths: the
`DESCRIBE`-style schema inference (`DESCRIBE TABLE` and reads of a
query-backed source) and the early `INSERT INTO TABLE FUNCTION ... query(...)`
rejection against a non-existent table (which proves the insert is rejected
before SQLite is contacted).

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

Copy link
Copy Markdown
Member Author

Pushed cd8001089..9b2ca442ced.

AI review (Request changes) — all three Majors addressed (d607824aac0), threads resolved with inline replies:

  1. external_table_strict_query — the query-backed read path of all three storages now calls rejectOuterFilterForQueryBackedExternalSourceIfStrict, which reconstructs the outer query the way transformQueryForExternalDatabase does and throws INCORRECT_QUERY when strict mode is on and the outer query has a WHERE/PREWHERE on the source (which cannot be pushed into a verbatim user query).
  2. PostgreSQL subquery dialect formatting — tryGetExternalDatabaseQuery now serializes the (SELECT ...) form with the external database's IdentifierQuotingStyle/LiteralEscapingStyle (WhenNecessary rule), so quoted identifiers are emitted in the target dialect rather than ClickHouse backticks.
  3. Read-only table-function inserts — INSERT INTO TABLE FUNCTION mysql/postgresql/sqlite(..., query(...)) is rejected with INCORRECT_QUERY in executeImpl, before the storage is constructed and before any external contact.

Follow-up bug fix (9b2ca442ced): d607824aac0 had also added the insert guard to getActualTableStructure, but that regressed DESCRIBE TABLE: InterpreterDescribeQuery calls getActualTableStructure with is_insert_query = true unconditionally, so DESCRIBE TABLE mysql(..., query('...'), ...) was wrongly rejected with INCORRECT_QUERY. Since INSERT INTO TABLE FUNCTION reaches the function through ITableFunction::execute with empty cached columns and is dispatched straight to executeImpl (never getActualTableStructure), the executeImpl guard alone covers every insert path. 9b2ca442ced removes the redundant getActualTableStructure guard, restoring DESCRIBE.

I built clickhouse from d607824aac0 and ran 04341_sqlite_query_passing, which reproduced the DESCRIBE rejection (Cannot INSERT into the 'sqlite' table function); the fix reverts getActualTableStructure to the read-only form it had in the original feature commit, and the full stateless/integration suites re-run in CI on the new head.

Remaining red checks (on the previous commit cd8001089) are known master-wide flakes, unrelated to this change:

Closes #46758.

break;

case enum_field_types::MYSQL_TYPE_GEOMETRY:
res = DataTypeFactory::instance().get("Point");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

MYSQL_TYPE_GEOMETRY is not equivalent to a MySQL POINT: result-set metadata uses this enum for all spatial values, while the existing table-name path only maps COLUMN_TYPE = 'point' to ClickHouse Point and falls back to String for LINESTRING/POLYGON/generic GEOMETRY. With this mapping, mysql(..., query('SELECT linestring_col FROM t'), ...) infers Point, and MySQLSource then throws Only Point data type is supported as soon as it reads the non-point WKB value. Please keep MYSQL_TYPE_GEOMETRY as String unless the subtype can be proven to be POINT, or obtain the subtype from source metadata before mapping to Point; a small query-form regression with a non-point spatial column would cover this.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is a task for another PR.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Triage of the current head (9b2ca442ced) — no code change pushed; both red checks are unrelated flakes/crashes in code this PR does not touch (it only adds query passing to mysql/postgresql/sqlite). The branch is 231 commits behind, but its merge-base (0cca85ea1a5) is from 2026-06-29 21:39Z (< 1 day), so no re-merge — re-merging would not affect either red.

AI Review (⚠️ Request changes) — sole finding is a documented follow-up

The only finding is MYSQL_TYPE_GEOMETRY → Point in convertMySQLDataType.cpp (query-backed mysql infers Point for LINESTRING/POLYGON/generic GEOMETRY, which the table-name path maps to String). This is the same item as the one unresolved inline thread, where it is already marked "This is a task for another PR." Proper handling needs the spatial subtype, which is not carried in the MYSQL_FIELD result metadata; neither "always Point" nor "always String" matches the table-name path. Left as the documented follow-up.

Red checks — both unrelated, both transient (failed jobs re-run)

  1. Stateless tests (arm_binary, parallel) → 02835_parallel_replicas_over_distributed — Code: 102 … Unexpected packet from server … (expected TablesStatusResponse, got ProfileInfo) raised inside Connection::getTablesStatus during connection establishment. A flaky parallel-replicas/connection test, unrelated to external-database query passing. CIDB: failed only on 2026-06-30, across three unrelated PRs (105945, 108884, 107740); 0 failures on master in the last 30 days.

  2. Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6) → test_storage_s3_queue/test_parallel_inserts.py::test_parallel_inserts_with_failures[1] — server SIGABRT in ObjectStorageQueueSource::FileIterator::next() (ObjectStorageQueueSource.cpp:408), an out-of-bounds std::vector::operator[] on file_metadatas. Unrelated to this PR (it does not touch ObjectStorageQueue). CIDB: failed in PR 107566 (2026-06-18, ×4) and here (2026-06-30); 0 failures on master in the last 30 days.

Root cause of (2): in FileIterator::next, when the ZooKeeper tryMulti to set files as processing fails, the else branch does file_metadatas.clear(). The subsequent compaction block if (num_successful_objects != new_batch.size()) then still executes file_metadatas[i] = file_metadatas[batch_i] (and file_metadatas.resize(...)) on the now-empty file_metadatas, so when any file in the batch was non-processable (num_successful_objects < new_batch.size()) the subscript goes out of bounds. The trailing chassert(file_metadatas.empty() || new_batch.size() == file_metadatas.size()) confirms the empty file_metadatas case is expected and the compaction loop should guard against it.

@groeneai, please investigate the s3_queue crash above and provide a fix in a separate PR (it is in the ObjectStorageQueue area, alongside #108676). If a fix is already in progress, please link it here. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107740&sha=9b2ca442ced2acecfefdd7307edee38be6a5dbf1&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%202%2F6%29

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI re-check on `9b2ca442ced`: the sole non-green job is now a different AST-fuzzer flake than the prior reruns surfaced.

  • `AST fuzzer (arm_asan_ubsan)` → `Logical error: Block structure mismatch in A stream: different columns: (STID: 0993-27f0)` in `UnionStep::updateOutputHeader` → `checkHeaders` via `executeASTFuzzerQueries` (`InterpreterSelectQueryAnalyzer::buildQueryPipeline`). This is the master-wide fuzzer flake tracked in Logical error: Block structure mismatch in A stream: different columns: (STID: 0993-27f0) #108142 (already auto-linked by the CI bot); CIDB shows it failing on `master` itself (`pull_request_number = 0`) and across dozens of unrelated PRs over the last 90 days. The stack is entirely in the query planner — there are no `mysql`/`postgresql`/`sqlite`/external-DB frames — so it is unrelated to this PR.

The previous reds (`02835_parallel_replicas_over_distributed`, the `test_storage_s3_queue` OOB fixed by #108977, the earlier `STID 2980-3913`=#100422 and `STID 3190-62c4`=#107561 stress flakes) all cleared.

Re-ran the failed job (`gh run rerun 28421280655 --failed`). The remaining review item (`MYSQL_TYPE_GEOMETRY` non-point spatial inference) is the documented follow-up in #108944.

#include "config.h"

#if USE_MYSQL
#if __has_include(<mysql.h>)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is weird. We never use system libraries. All our libraries should be available at the same locations. Let's find all similar places in the code and remove.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is good!

@alexey-milovidov alexey-milovidov self-assigned this Jul 1, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 1, 2026
Merged via the queue into master with commit 75b3065 Jul 1, 2026
679 of 684 checks passed
@alexey-milovidov
alexey-milovidov deleted the external-db-query-passing branch July 1, 2026 05:46
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 1, 2026
# Pin external_table_functions_use_nulls = 0 so the inferred types are not wrapped into Nullable,
# which keeps the type-name assertions focused on the typmod and dimension inference.
q_wide = (
f"postgresql('{host}', 'postgres', query('SELECT id, big, arr1, arr2 FROM {wide_name}'), "

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai is this testing missing permissions, empty result sets, type mismatches? Otherwise, create a pr for coverage?

@groeneai

Copy link
Copy Markdown
Collaborator

@PedroTadim the merged test_postgres_query_passing did not cover those, so I opened #110264 adding test_postgres_query_passing_edge_cases for all three:

  • missing permissions: the passed query runs on the PostgreSQL side under the supplied role, so a role without SELECT surfaces PostgreSQL's permission denied.
  • empty result sets: schema inference runs the query with LIMIT 0, so the structure is still resolved (checked via DESCRIBE) and count() is 0.
  • type mismatches: this one exposed a real server abort. Reading a text value into a declared Int32 made pqxx::from_string throw pqxx::conversion_error (a foreign std::exception), which escaped insertPostgreSQLValue and aborted the server (signal 6 / LOGICAL_ERROR) in debug/sanitizer builds. Fix server abort on PostgreSQL value type mismatch #110264 also converts that into a BAD_ARGUMENTS query error at the value-parsing boundary (shared by the query-passing and plain table-name paths).

huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Jul 17, 2026
Previously the MySQL integrations (the `MySQL` database engine, table
engine and table function) mapped only `POINT` to the ClickHouse `Point`
type and converted every other spatial type (`LINESTRING`, `POLYGON`,
`MULTILINESTRING`, `MULTIPOLYGON`, generic `GEOMETRY`) to `String`,
exposing the raw WKB bytes.

This adds a new `geometry` flag to the `mysql_datatypes_support_level`
setting, enabled by default, that maps MySQL spatial types to the
corresponding ClickHouse geometric types:

- `LINESTRING`     -> `LineString`
- `POLYGON`        -> `Polygon`
- `MULTILINESTRING`-> `MultiLineString`
- `MULTIPOLYGON`   -> `MultiPolygon`
- `GEOMETRY`       -> `Geometry` (a `Variant` over all the geometric types,
                      used when the concrete subtype is not known from the
                      column metadata)

`POINT` keeps being converted to `Point` unconditionally, for backward
compatibility (it has been supported since version 24.1). `MULTIPOINT`
and `GEOMETRYCOLLECTION` have no ClickHouse counterpart and, as all
unknown types, fall back to `String`.

`MySQLSource` reads these values by stripping the 4-byte SRID prefix and
parsing the standard WKB payload with `parseWKBFormat`, then inserting
the result into the concrete geometric column or into the `Geometry`
`Variant` by discriminator.

This was raised in the review of
ClickHouse#107740 (discussion
r3496279299): the query-passing path could only report the generic
`MYSQL_TYPE_GEOMETRY` and would otherwise have to guess `Point`. Mapping
to `Geometry` removes that guess. PostgreSQL uses different (non-WKB)
representations for its built-in geometric types and EWKB for PostGIS, so
it is left for a follow-up.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov added a commit that referenced this pull request Jul 23, 2026
Query forwarding to external databases (#107740) is based on Denis
Vidiaev's #79652, the GeoJSON output format (#108065) on Mark Needham's
#98124, and SZ3 (#108788) revives Konstantin Vedernikov's #83088.

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Query forwarding to external databases (ClickHouse#107740) is based on Denis
Vidiaev's ClickHouse#79652, the GeoJSON output format (ClickHouse#108065) on Mark Needham's
ClickHouse#98124, and SZ3 (ClickHouse#108788) revives Konstantin Vedernikov's ClickHouse#83088.

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The query-backed MySQL schema inference (the `MYSQL_FIELD` overload of
`convertMySQLDataType` used by `doQueryResultStructure`) always wrapped
nullable MySQL fields into `Nullable`, ignoring the
`external_table_functions_use_nulls` setting. The table-name path applies
the setting before wrapping (see `FetchTablesColumnsList.cpp`), so a
query-backed `mysql(... query('SELECT nullable_col FROM t') ...)
SETTINGS external_table_functions_use_nulls = 0` exposed `Nullable(T)`
instead of `T`, diverging from both the table form and the documented
setting behavior.

Thread the setting into the `MYSQL_FIELD` conversion path and pass it from
`doQueryResultStructure`, and extend the MySQL query-passing integration
test with a regression assertion for both setting values.

Addresses the AI review for ClickHouse#107740

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
… query

The query-backed PostgreSQL schema inference probes `array_ndims` over the
first row of the query result to learn an array's real number of
dimensions. When that first sampled value is `NULL` or an empty array,
`array_ndims` returns `NULL`, and the dimensions were silently left at one.
A non-empty result whose first row is empty but whose later rows contain a
multidimensional array (e.g. first row `'{}'::integer[][]`, second row
`'{{1,2},{3,4}}'`) was then inferred as `Array(Int32)` and failed at read
time with the confusing `Got more dimensions than expected`.

Throw a clear error during inference instead, matching the table-name
path's fail-early behavior in its `recheck_array` step. An empty result
(no rows) still keeps the dimensions at one, since there is nothing to read.

Extend the PostgreSQL query-passing integration test with this case.

Addresses the AI review for ClickHouse#107740

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…gines

The table-function docs already describe passing a `SELECT` query instead of
a table name, but the table-engine reference pages still described the third
argument only as a remote table name and omitted the new behavior.

Document the query-backed syntax (a subquery or `query(...)`), the structure
inferred from the query result, and the read-only behavior (`INSERT` throws
`INCORRECT_QUERY`) on the `MySQL`, `PostgreSQL`, and `SQLite` table-engine
pages, mirroring the corresponding table-function docs.

Addresses the documentation finding from the AI review of ClickHouse#107740.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The previous commit documented passing a `SELECT` query instead of a table name
on the `MySQL`, `PostgreSQL`, and `SQLite` table-engine reference pages
(`docs/en/engines/table-engines/integrations/*.md`), but the source-level
`Documentation` blocks embedded in `StorageMySQL`, `StoragePostgreSQL`, and
`StorageSQLite` (used by the storage factory for generated/help documentation)
still described the `table` argument only as a remote table name.

Mirror the same additions into the embedded `Documentation` blocks: the `table`
argument can be a `SELECT` query written as a subquery or wrapped into `query(...)`,
the structure is inferred from the query result, and such a table is read-only
(`INSERT` is not allowed). This restores parity between the two documentation
surfaces.

Addresses the documentation finding from the AI review of ClickHouse#107740.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…y-passing

Support passing a query to the mysql, postgresql and sqlite table functions and engines
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Previously the MySQL integrations (the `MySQL` database engine, table
engine and table function) mapped only `POINT` to the ClickHouse `Point`
type and converted every other spatial type (`LINESTRING`, `POLYGON`,
`MULTILINESTRING`, `MULTIPOLYGON`, generic `GEOMETRY`) to `String`,
exposing the raw WKB bytes.

This adds a new `geometry` flag to the `mysql_datatypes_support_level`
setting, enabled by default, that maps MySQL spatial types to the
corresponding ClickHouse geometric types:

- `LINESTRING`     -> `LineString`
- `POLYGON`        -> `Polygon`
- `MULTILINESTRING`-> `MultiLineString`
- `MULTIPOLYGON`   -> `MultiPolygon`
- `GEOMETRY`       -> `Geometry` (a `Variant` over all the geometric types,
                      used when the concrete subtype is not known from the
                      column metadata)

`POINT` keeps being converted to `Point` unconditionally, for backward
compatibility (it has been supported since version 24.1). `MULTIPOINT`
and `GEOMETRYCOLLECTION` have no ClickHouse counterpart and, as all
unknown types, fall back to `String`.

`MySQLSource` reads these values by stripping the 4-byte SRID prefix and
parsing the standard WKB payload with `parseWKBFormat`, then inserting
the result into the concrete geometric column or into the `Geometry`
`Variant` by discriminator.

This was raised in the review of
ClickHouse#107740 (discussion
r3496279299): the query-passing path could only report the generic
`MYSQL_TYPE_GEOMETRY` and would otherwise have to guess `Point`. Mapping
to `Geometry` removes that guess. PostgreSQL uses different (non-WKB)
representations for its built-in geometric types and EWKB for PostGIS, so
it is left for a follow-up.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Oct 2, 2026
…and mysql

ClickHouse#107740 added passing a query instead of a table name to the postgresql,
mysql and sqlite table functions and engines. Its documentation showed only
the positional `(SELECT ...)` and `query('...')` forms. Add to the
"Passing a query" section of each of the six reference pages:

- the feature exists since 26.7 (on 26.6 the `query` key is rejected as
  an unexpected key of the named collection);
- the query must not end with a semicolon, because it is sent wrapped as
  `SELECT ... FROM (<query>) AS __subquery`;
- postgresql and mysql: with a named collection the query goes into the
  `query` key, stored in the collection or given as a key-value argument,
  and cannot be combined with `table`;
- postgresql: the `schema` argument does not apply to a passed query.

The pages are generated from these description strings, so no file under
docs/ is edited.

Related: ClickHouse#121391
Related: ClickHouse#107740

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

Allow to explicitly pass query string to table functions for federated queries.

4 participants