Repository navigation
Support passing a query to the mysql, postgresql and sqlite table functions and engines - #107740
Conversation
…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]>
|
Workflow [PR], commit [9b2ca44] Summary: ✅
AI ReviewSummaryThis PR adds query-backed Findings
Tests
Final VerdictStatus: Minimum required action: fix MySQL query-backed spatial type inference for non-point geometry values and add the regression above. |
…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]>
|
Addressed the AI review (Request changes) on the new query-backed
Verified the generated SQL against PostgreSQL 15 ( Merged The remaining red checks are unrelated, pre-existing master-wide flakes with open tracking issues:
|
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]>
|
Addressed the two remaining AI review Majors on the query-backed schema inference:
The three affected translation units ( |
…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]>
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]>
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]>
|
Pushed AI review (Request changes) — all three Majors addressed (
Follow-up bug fix ( I built Remaining red checks (on the previous commit
Closes #46758. |
| break; | ||
|
|
||
| case enum_field_types::MYSQL_TYPE_GEOMETRY: | ||
| res = DataTypeFactory::instance().get("Point"); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
This is a task for another PR.
|
Triage of the current head ( AI Review (
|
|
CI re-check on `9b2ca442ced`: the sole non-green job is now a different AST-fuzzer flake than the prior reruns surfaced.
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>) |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
This is good!
| # 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}'), " |
There was a problem hiding this comment.
@groeneai is this testing missing permissions, empty result sets, type mismatches? Otherwise, create a pr for coverage?
|
@PedroTadim the merged
|
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]>
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]>
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]>
… 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]>
…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]>
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]>
…y-passing Support passing a query to the mysql, postgresql and sqlite table functions and engines
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]>
…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]>
Generalizes the idea of #79652 (which added query passing for the
mysqltable function and engine) to all native SQL external-database integrations:mysql,postgresql, andsqlite, both as table functions and as table engines.Instead of a remote table name, the table argument can now be a
SELECTquery that is passed to the external database as is, written either as a subquery(SELECT ...)or wrapped intoquery('SELECT ...'):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
INSERTinto it throwsINCORRECT_QUERY.Implementation
TableNameOrQueryabstraction holds either a table name or a query, with a common argument parser and read-projection builder reused by all three integrations.mysql: a newconvertMySQLDataType(MYSQL_FIELD &)overload andmysqlxx::ResultBase::getField; the structure is inferred by running the query withLIMIT 0.postgresql: the structure is inferred from the result column type OIDs ofSELECT * 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/jdbcare intentionally not covered (their schema inference is performed by the external bridge process and would require bridge-protocol changes), and neither ismongodb(it is not SQL-based).Tests: a stateless test for
sqliteand integration tests formysqlandpostgresql. Documentation updated for the three table functions.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added support for the
mysql,postgresql, andsqlitetable 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 asquery('SELECT ...'). The structure of the resulting table is inferred from the query result, and such a table is read-only. Closes #46758.Version info
26.7.1.320(included in26.7and later)