Skip to content

Map MySQL geometry types to ClickHouse geometric types - #108944

Merged
alexey-milovidov merged 19 commits into
masterfrom
feat/mysql-geometry-types
Jul 17, 2026
Merged

alexey-milovidov merged 19 commits into
masterfrom
feat/mysql-geometry-types

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

The MySQL integrations (the MySQL database engine, table engine and table function) previously mapped only POINT to the ClickHouse Point type and converted every other MySQL 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's spatial column types to the corresponding ClickHouse geometric types:

MySQL ClickHouse
POINT Point (always, regardless of the flag)
LINESTRING LineString
POLYGON Polygon
MULTILINESTRING MultiLineString
MULTIPOLYGON MultiPolygon
GEOMETRY (generic) Geometry (the umbrella Variant)
MULTIPOINT, GEOMETRYCOLLECTION String

A concrete spatial column type (LINESTRING, POLYGON, MULTILINESTRING, MULTIPOLYGON) is mapped to its ClickHouse counterpart, because MySQL enforces a single subtype per such column, so a read can never encounter a value of a different subtype.

The generic GEOMETRY column type is mapped to the umbrella Geometry type (a Variant over Point/LineString/Polygon/MultiLineString/MultiPolygon/Ring). Such a column can store values of any subtype, including ones that have no ClickHouse counterpart (MULTIPOINT, GEOMETRYCOLLECTION); this incompatibility is accepted: a value of a representable subtype reads back correctly, while a value of a subtype with no ClickHouse counterpart throws an exception at read time, because parseWKBFormat rejects the WKB type and the Geometry Variant has no alternative for it.

POINT keeps being converted to Point unconditionally for backward compatibility (it has been supported since version 24.1). Columns declared as MULTIPOINT or GEOMETRYCOLLECTION themselves have no ClickHouse counterpart and, as all unknown types, fall back to String. When the geometry flag is disabled, the previous behavior is restored (everything except POINT becomes String).

MySQLSource reads the geometric values (for the concrete spatial columns, and for columns declared as a geometric or Geometry type) 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.

Motivation. This was raised in the review of #107740 (discussion r3496279299): mapping all spatial values to Point is wrong. The concrete spatial types map to their exact ClickHouse counterparts; the generic GEOMETRY maps to the umbrella Geometry type, accepting that the rarely used MULTIPOINT and GEOMETRYCOLLECTION subtypes are not representable and throw at read time.

PostgreSQL uses different (non-WKB) text representations for its built-in geometric types and EWKB for PostGIS, and currently has no geometric type mapping at all, so it is left for a follow-up.

Changelog category (leave one):

  • Improvement

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

The MySQL database engine, table engine and table function now map MySQL's spatial column types (LINESTRING, POLYGON, MULTILINESTRING, MULTIPOLYGON, and the generic GEOMETRY) to the corresponding ClickHouse geometric types instead of String. This is controlled by the new geometry flag of the mysql_datatypes_support_level setting, enabled by default. POINT is still always converted to Point. The generic GEOMETRY column maps to the umbrella Geometry type; reading a value whose subtype has no ClickHouse counterpart (MULTIPOINT, GEOMETRYCOLLECTION) throws an exception at read time.

Version info

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

alexey-milovidov and others added 2 commits June 30, 2026 13:55
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
#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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cf90641]

Summary: ✅


AI Review

Summary

This PR adds default-on geometric type mapping for MySQL across the MySQL database engine, table engine, and table function, including WKB parsing for non-Point spatial values. The current head still has two compatibility problems on existing user-visible surfaces: persisted MySQL database engines created before 26.7 silently pick up the new geometry default after ATTACH, and query-backed geometry results regress existing POINT columns from Point to raw String.

Findings

❌ Blockers

  • [src/Storages/MySQL/MySQLSettings.cpp:33,81-84; src/Databases/MySQL/DatabaseMySQL.cpp:640-642] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/108944#discussion_r3567426170] Changing the engine-side default to decimal,datetime64,date2Date32,geometry while loadFromQueryContext is skipped when there is no query context means a persisted MySQL database engine created on 26.6 with no explicit SETTINGS mysql_datatypes_support_level re-attaches on 26.7 with the new default. That silently changes remote schema inference for existing objects and can turn a previously-readable generic GEOMETRY column into a read-time exception, while compatibility = '26.6' cannot repair the already-attached engine because DatabaseMySQL reads only the persisted MySQLSettings value. Suggested fix: persist the resolved mysql_datatypes_support_level on CREATE/ATTACH, or seed the attach-time default from the effective server setting when there is no query context.

⚠️ Majors

  • [src/DataTypes/convertMySQLDataType.cpp:259-267; src/Core/Settings.cpp:5335; docs/en/engines/database-engines/mysql.md:82] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/108944#discussion_r3523939950] Query-backed MySQL sources now downgrade every MYSQL_TYPE_GEOMETRY result to raw String, so mysql(..., query('SELECT point_col FROM t')) and ENGINE = MySQL(..., query('SELECT point_col FROM t')) no longer surface an existing POINT column as Point. That is a backward-incompatible change on a previously working path, and it also leaves the new setting/docs contract false for the query-backed form (POINT is not "always converted to Point"). Suggested fix: keep the old Point mapping behind compatibility, or explicitly document and gate the query-backed exception instead of silently changing the surface type.
Tests
  • ⚠️ Add a focused regression test for a query-backed POINT column in both mysql(..., query('...')) and ENGINE = MySQL(..., query('...')). Current coverage only exercises query-backed LINESTRING, so the Point -> String compatibility break remains invisible to the new test matrix.
Final Verdict

Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jun 30, 2026
Comment thread src/DataTypes/convertMySQLDataType.cpp Resolved
A MySQL column declared with the generic `GEOMETRY` type can store values
of any subtype, including `MULTIPOINT` and `GEOMETRYCOLLECTION`, which have
no ClickHouse counterpart. `parseWKBFormat` only accepts the WKB type ids
`1`, `2`, `3`, `5`, `6`, and the umbrella `Geometry` type is a `Variant`
over `Point`, `LineString`, `Polygon`, `MultiLineString`, `MultiPolygon`,
`Ring` only - it cannot represent those subtypes. So mapping a generic
`GEOMETRY` column to `Geometry` (which was enabled by default) made
previously-readable rows throw `BAD_ARGUMENTS` at `SELECT` time, and
contradicted this PR's own stated intent that `MULTIPOINT` and
`GEOMETRYCOLLECTION` fall back to `String`.

Keep the generic `GEOMETRY` column type mapped to `String` (its raw WKB,
the previous behavior). The concrete spatial column types (`LINESTRING`,
`POLYGON`, `MULTILINESTRING`, `MULTIPOLYGON`) are still mapped to the
corresponding ClickHouse geometric types under the `geometry` flag,
because MySQL enforces a single subtype per such column, so the read can
never encounter an unrepresentable value. A user who knows a generic
`GEOMETRY` column only holds representable subtypes can still read it as
`Geometry` by declaring the column type explicitly (e.g. via the MySQL
table engine); that read path is unchanged.

The integration test now asserts the generic `geometry` column (including
a row holding a `MULTIPOINT`) is read as `String` without error, which is
the regression the review asked to cover.

Addresses the review finding on src/DataTypes/convertMySQLDataType.cpp.

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

Copy link
Copy Markdown
Member Author

Status update (continue-pr): addressed the blocking AI Review finding.

The AI Review requested changes on the generic GEOMETRY mapping (one unresolved thread, now resolved). I confirmed it is a real, default-on regression: a MySQL column declared with the generic GEOMETRY type can hold values of any subtype, including MULTIPOINT (WKB id 4) and GEOMETRYCOLLECTION (id 7); parseWKBFormat only accepts ids 1/2/3/5/6 and the Geometry Variant has no alternative for those, so mapping it to Geometry made previously-readable rows throw BAD_ARGUMENTS at SELECT time — and it contradicted this PR's own stated "fall back to String" intent.

Fix (f515b85):

  • Generic GEOMETRY column type now stays mapped to String (raw WKB — the previous, safe behavior).
  • The concrete spatial types (LINESTRING/POLYGON/MULTILINESTRING/MULTIPOLYGON) are still mapped to ClickHouse geometric types under the geometry flag — these are safe because MySQL enforces one subtype per such column.
  • The explicit-Geometry-column read path (e.g. MySQL table engine) is unchanged, so a user who knows the data is representable can still opt in.
  • Updated docs, the setting description, the settings-changes-history note, and the integration test, which now adds a generic geometry column holding a MULTIPOINT and asserts it reads as String without error (the requested regression test).
  • Verified convertMySQLDataType.cpp compiles (-fsyntax-only, -Werror); Python ruff clean.

This reverses one design element of the PR (generic GEOMETRY → Geometry), so flagging it for your call — it is an isolated, easily-reverted commit if you prefer to keep the umbrella mapping and instead document the unsupported-subtype limitation.

The only CI failure was 03360_bool_remote (Unexpected packet from server (expected TablesStatusResponse, got ProfileInfo)) — the known distributed TablesStatus desync flake being fixed by #108854, unrelated to this change. The push triggered a fresh CI run on f515b851b34.

alexey-milovidov and others added 2 commits June 30, 2026 20:48
This addresses the review finding on the MySQL table engine and fixes the
`test_mysql_database_engine/test.py::test_backup_database` integration test.

Two related problems, both rooted in the same omission: when this PR added
`geometry` to the default of the `mysql_datatypes_support_level` server
setting, it left the engine-level `MySQLSettings` default unchanged at
`decimal,datetime64,date2Date32`.

1. The engine and server defaults no longer matched, so `loadFromQueryContext`
   considered the value "changed" for every freshly created MySQL database (and
   table) engine, persisting a redundant
   `SETTINGS mysql_datatypes_support_level = 'decimal,datetime64,date2Date32,geometry'`
   clause into the `CREATE` statement. That is what broke `test_backup_database`,
   which asserts the round-tripped `SHOW CREATE DATABASE` has no `SETTINGS`
   clause. Fixed by giving `MySQLSettings` the same default as the server
   setting, so the default case persists nothing again.

2. `StorageMySQL::getTableStructureFromData` read the type-mapping level from the
   global query context instead of the engine settings, so an explicit
   per-engine opt-out such as
   `CREATE TABLE t ENGINE = MySQL(...) SETTINGS mysql_datatypes_support_level = 'decimal,datetime64,date2Date32'`
   (with omitted columns) was silently ignored: schema inference still mapped
   `LINESTRING` to `LineString`, so the documented "disable `geometry` to restore
   `String`" behavior was false for the persistent table engine.

   Fixed by threading the effective type-support level into
   `getTableStructureFromData`. The table engine now passes its own engine
   setting; for that value to also reflect a query-context `SET`, the table
   engine bridges the context value into the engine settings via
   `loadFromQueryContext`, the same way the MySQL database engine already does.
   The table function keeps reading the query context, since it has no
   persistent engine settings.

The integration test now also covers the per-engine opt-out: a schema-inferred
`MySQL` table engine with `SETTINGS mysql_datatypes_support_level` disabling
`geometry` reads `LINESTRING` as `String`, and the default-on case reads it as
`LineString`.

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

Copy link
Copy Markdown
Member Author

Status update (continue-pr): fixed the failing integration test and addressed the blocking AI Review finding. Pushed f515b851b34..7ef7d7ac244 (one fix commit + a fresh merge of master).

Both problems shared one root cause: this PR added geometry to the default of the mysql_datatypes_support_level server setting but left the engine-level MySQLSettings default at decimal,datetime64,date2Date32.

  1. CI failure test_mysql_database_engine/test.py::test_backup_database — with the defaults mismatched, MySQLSettings::loadFromQueryContext considered the value "changed" for every freshly created MySQL database engine and persisted a redundant SETTINGS mysql_datatypes_support_level = 'decimal,datetime64,date2Date32,geometry' clause into the CREATE statement, which the test asserts is absent. Fixed by giving MySQLSettings the same default as the server setting, so the default case persists nothing again.

  2. AI Review ⚠️ Major (table-engine opt-out) — StorageMySQL::getTableStructureFromData read the type-mapping level from the global query context instead of the engine settings, so CREATE TABLE t ENGINE = MySQL(...) SETTINGS mysql_datatypes_support_level = 'decimal,datetime64,date2Date32' (with omitted columns) was silently ignored — schema inference still mapped LINESTRING to LineString. Fixed by threading the effective type-support level into getTableStructureFromData: the table engine passes its own engine setting and bridges the query-context value into it via loadFromQueryContext (mirroring the MySQL database engine); the table function keeps reading the query context.

Added a regression test covering the per-engine opt-out (LINESTRING reads as String when geometry is disabled via table-engine SETTINGS; reads as LineString by default).

Design note for your call: item 2 mirrors the database engine by calling loadFromQueryContext in registerStorageMySQL, which also freezes a non-default mysql_datatypes_support_level into the table's CREATE (only when it differs from the default — the default case persists nothing). This makes the table engine consistent with the database engine and also makes a query-context SET take effect for table-engine schema inference (previously the table engine read the global context and ignored session SET). If you prefer the table engine to stay strictly per-SETTINGS (no SET bridging / no freezing), I can drop the loadFromQueryContext line and keep only the getTableStructureFromData threading — that still fixes the AI finding.

Verified: -fsyntax-only -Werror on all changed/related MySQL translation units, ruff clean on the test. 02995_new_settings_history is unaffected (the server-default change is recorded in SettingsChangesHistory.cpp under 26.7; the engine MySQLSettings default has no history mechanism). Fresh CI is running on 7ef7d7ac244.

The earlier commit that threaded the type-mapping level into
`StorageMySQL::getTableStructureFromData` and the `StorageMySQL`
constructor changed the constructor's fallback schema inference to read
the engine `MySQLSettings` instead of the query context. The `mysql(...)`
table function creates its `StorageMySQL` with a default `MySQLSettings{}`,
so when it inferred the structure itself the default-on `geometry` (and
`decimal`/`datetime64`) flags were always applied, silently ignoring both
the per-call `SETTINGS` and the query-level `mysql_datatypes_support_level`.

This made
`SELECT toTypeName(ls) FROM mysql(...) SETTINGS mysql_datatypes_support_level = 'decimal,datetime64,date2Date32'`
infer a MySQL `LINESTRING` as `LineString` instead of `String`, and
regressed the existing `test_mysql_types` table-function assertions (e.g.
a MySQL `DATETIME(6)` read back as `DateTime64(6)` instead of `DateTime`).

`TableFunctionMySQL::parseArguments` now computes the effective
`mysql_datatypes_support_level` (the query-context value, overridden by a
function-local `SETTINGS` clause or named collection) and both
`getActualTableStructure` and `executeImpl` use it, so the table function
honors the configured level regardless of which path performs the
inference. This also addresses the review point that the per-call
`SETTINGS` opt-out was silently ignored.

Adds regression tests for the per-call `SETTINGS` opt-out and for the
per-call override of a query-level value.

CI report: #108944

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

Copy link
Copy Markdown
Member Author

Status update (continue-pr): fixed the integration-test regression and the blocking AI Review finding. Pushed 7ef7d7ac244..6d70f47544d.

Root cause (one bug behind all the failures). The commit that threaded the type-mapping level into StorageMySQL::getTableStructureFromData and the StorageMySQL constructor changed the constructor's fallback schema inference to read the engine MySQLSettings instead of the query context. The mysql(...) table function creates its StorageMySQL with a default MySQLSettings{}, so when it inferred the structure itself the default-on geometry (and decimal/datetime64) flags were always applied — silently ignoring both the per-call SETTINGS and the query-level mysql_datatypes_support_level.

This broke exactly the table-function code path (getActualTableStructure/executeImpl), which is why every failure was at the mysql(...) assertion and the database/table-engine paths stayed green:

  • test_storage_mysql/test.py::test_mysql_geometry (new): SELECT toTypeName(ls) FROM mysql(...) SETTINGS mysql_datatypes_support_level = 'decimal,datetime64,date2Date32' returned LineString instead of String (confirmed in the server log — inference ran with the default level).
  • test_mysql_database_engine/test_mysql57_database_engine ::test_mysql_types[...] (datetime_6_2/3, decimal_18_6_1/2, common_types_21/23): the table function sub-assertion (line 939/961) regressed, e.g. a MySQL DATETIME(6) read back as DateTime64(6) instead of DateTime. I verified via play.clickhouse.com that these type-mismatch AssertionErrors appear only on this PR — the same tests' failures on other PRs over the last 40 days are infra/cluster crashes, a different failure mode.

Fix. TableFunctionMySQL::parseArguments now computes the effective mysql_datatypes_support_level — the query-context value, overridden by a function-local SETTINGS clause or named collection — and both getActualTableStructure and executeImpl use it, so the table function honors the configured level regardless of which path performs the inference. This is also the AI Review's Minimum required action (the per-call SETTINGS opt-out was silently ignored); resolved the corresponding thread.

Tests. Added regression assertions to test_mysql_geometry for mysql(..., SETTINGS mysql_datatypes_support_level = '...') honoring the per-call opt-out, and for the per-call SETTINGS overriding a query-level value.

Verification. convertMySQLDataType.cpp already gates the mapping on type_support.isSet(GEOMETRY), so it was always receiving the wrong level — not mis-mapping. The changed translation unit compiles clean with the full production flags (-Weverything, ARM); ruff clean on the test. I could not run the integration tests locally (this build dir's mariadb-connector-c submodule is unpopulated, so CMake cannot reconfigure), so the fresh CI run on 6d70f47544d is the end-to-end check.

Comment thread src/Processors/Sources/MySQLSource.cpp Resolved
Addresses the AI Review "Request changes" finding on
`src/Processors/Sources/MySQLSource.cpp`: the new MySQL spatial read path
called `parseWKBFormat` with the default `0`, so a remote `LINESTRING`,
`POLYGON` or `MULTI*` value used only the hard-coded `100'000'000` element
cap instead of the configurable `max_wkb_geometry_elements` query setting
(which defaults to `1'000'000` specifically to bound WKB point/ring/polygon
counts before the parser reserves memory). `external_storage_max_read_bytes`
is checked only after a row has been parsed, so it could not prevent the
oversized allocation path.

Carry the (clamped) `max_wkb_geometry_elements` value in `StreamSettings`,
built from the query settings exactly as `readWkb` does, and thread it
through `insertValue`/`insertGeometryValue` into `parseWKBFormat`.

Added a focused regression test to `test_mysql_geometry` that reads a MySQL
`LINESTRING` of three points with `max_wkb_geometry_elements = 1` and asserts
the read is rejected with `TOO_LARGE_ARRAY_SIZE`, and reads back normally
with a sufficiently large limit.

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

Copy link
Copy Markdown
Member Author

Status update (continue-pr): addressed the blocking AI Review finding. Pushed 6d70f47544d..3410a1d35a8.

The AI Review requested changes because the new MySQL geometry read path called parseWKBFormat with the default 0, so a remote LINESTRING/POLYGON/MULTI* value used only the hard-coded 100'000'000 element cap instead of the configurable max_wkb_geometry_elements query setting (which defaults to 1'000'000 specifically to bound WKB point/ring/polygon counts before the parser reserves memory). external_storage_max_read_bytes is checked only after a row has been parsed, so it could not prevent the oversized allocation path.

Fix (3410a1d):

  • StreamSettings now carries the effective max_wkb_geometry_elements, computed from the query settings exactly as readWkb does (static_cast<UInt32>(std::min<UInt64>(settings[max_wkb_geometry_elements], MAX_WKB_GEOMETRY_ELEMENTS_HARD_LIMIT))). It is built from context_->getSettingsRef() in StorageMySQL::read, so a per-query SETTINGS max_wkb_geometry_elements = ... reaches the reader.
  • Threaded that value through insertValue/insertGeometryValue into parseWKBFormat.
  • Added a focused regression test to test_mysql_geometry: reading a MySQL LINESTRING of three points with max_wkb_geometry_elements = 1 is now rejected with TOO_LARGE_ARRAY_SIZE (before the fix it parsed the value), and reads back normally with a sufficiently large limit.

Note: the Point path parses the two coordinates directly (no element count), so it is unaffected. The other parseWKBFormat callers (Parquet, Arrow) still pass the default and are left out of scope for this MySQL PR.

Verification. MySQLSource.cpp compiles clean under the full production flags (-fsyntax-only, ARM, -Weverything/-Werror); ruff check clean on the test. The push triggered a fresh CI run on 3410a1d35a8.

…-types

# Conflicts:
#	src/Storages/StorageMySQL.cpp
#	src/Storages/StorageMySQL.h
#	src/TableFunctions/TableFunctionMySQL.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Status update (continue-pr): merged master, resolved a 3-file conflict. Pushed 3410a1d35a8..11b59a1a5b0.

The PR had gone CONFLICTING/DIRTY against master because master landed the TableNameOrQuery refactor and the new query-backed structure inference (doQueryResultStructure), which touched the same three files this PR modifies. GitHub now reports MERGEABLE again.

Conflicts resolved by combining both sides (no logic dropped):

  • StorageMySQL.h / StorageMySQL.cpp — getTableStructureFromData now takes master's const TableNameOrQuery & table_or_query and this PR's MultiEnum<MySQLDataTypesSupport> type_support. The constructor's fallback inference passes the renamed member remote_table_or_query with (*mysql_settings)[mysql_datatypes_support_level].
  • TableFunctionMySQL.cpp — getActualTableStructure uses configuration->table_or_query with the effective type_support; executeImpl keeps both master's query-backed-insert rejection and this PR's effective-MySQLSettings construction.

Verified: both changed TUs pass -fsyntax-only with the full production flags (declaration/definition/call-sites all consistent, 5-arg getTableStructureFromData, fetchTablesColumnsList still takes type_support); all geometry integration tests survived the test.py merge; 0 unresolved review threads; AI Review was ✅ Approve on the prior head and this merge changes no logic.

One design note for your call (left as master's behavior, not changed). master's new doQueryResultStructure (the schema-inference path taken when a MySQL source is defined over a query rather than a table name) maps types using the query-context mysql_datatypes_support_level, not the effective per-engine/per-call value threaded in by this PR. So for a query-backed MySQL storage or mysql(...) call, a per-engine/per-call SETTINGS mysql_datatypes_support_level = '...' geometry opt-out would not reach that inference. No test covers this intersection and it is master's unrelated new feature, so I did not speculatively change it. If you want the opt-out honored there too, threading type_support into doQueryResultStructure is a one-line follow-up.

Comment thread src/Storages/StorageMySQL.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Status update (continue-pr): merged master, resolved the CONFLICTING/DIRTY state. Pushed 11b59a1a5b0..8262da8fa51.

GitHub reported the PR as CONFLICTING (branch was 71 commits behind, merge-base at 07:59Z today), but the actual git merge origin/master was clean — the status was stale. The merge integrated only master's additive changes into the three high-churn settings files (Settings.cpp, SettingsEnums.cpp, SettingsChangesHistory.cpp); the MySQL translation units (StorageMySQL.cpp, MySQLSource.cpp, convertMySQLDataType.cpp, TableFunctionMySQL.cpp) are byte-identical to the already-CI-tested head 11b59a1a5b0.

Verified:

  • master did not independently change the mysql_datatypes_support_level default (it is still decimal,datetime64,date2Date32 there), so the merge correctly kept this PR's decimal,datetime64,date2Date32,geometry value — no silent revert.
  • The SettingsChangesHistory.cpp entry stayed under the 26.7 block; geometry enum and max_wkb_geometry_elements declarations intact; no conflict markers, no manual edits.

GitHub now reports MERGEABLE. Fresh CI is running on 8262da8fa51.

On the one remaining unresolved thread (StorageMySQL.cpp — query-backed doQueryResultStructure dropping the effective mysql_datatypes_support_level): left unchanged, per your prior call. This is master's pre-existing behavior, not a regression introduced here — the MYSQL_FIELD overload of convertMySQLDataType maps MYSQL_TYPE_GEOMETRY to Point identically on master and this branch, and this PR only adds the concrete-type mapping (linestring→LineString, etc.) to the string-typename overload used by table-name inference. Threading type_support into doQueryResultStructure is the one-line follow-up you noted; it is an enhancement to master's orthogonal query-backed-inference feature, so I did not make that scope decision on your behalf.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Status update (continue-pr): the two red CI checks are unrelated master-wide flakes; no code change.

Head 8262da8f is unchanged from the last merge. The fresh CI run has two failures, both confirmed pre-existing flakes with open tracking issues and zero MySQL frames in their stacks:

  • Stress test (amd_msan) → Hung check failed, possible deadlock found — Hung check failed, possible deadlock found #107941. Master-wide: 62 occurrences across 39 PRs today and 528 across 180 PRs yesterday (test_status IN ('FAIL','ERROR') on the checks table). The stack is an analyzer/AST-fuzzer deadlock with no MySQL storage involved.
  • AST fuzzer (arm_asan_ubsan) → Logical error: Block structure mismatch in A stream: different columns: (STID: 0993-27f0) — Logical error: Block structure mismatch in A stream: different columns: (STID: 0993-27f0) #108142 (exact STID match; the CI summary already links it). The failing query is a random fuzzer query hitting UnionStep::updateOutputHeader; the same signature appears on master and ~14 other unrelated PRs today alone.

Neither is reachable from a MySQL type-mapping change (the AST fuzzer never creates a MySQL storage, and the geometry code is on neither stack).

The single remaining unresolved review thread is the query-backed doQueryResultStructure inference (StorageMySQL.cpp:129). This is pre-existing master behavior — the query path and the MYSQL_FIELD GEOMETRY→Point mapping are byte-identical to master; this PR's convertMySQLDataType.cpp diff only touches the table-name overload, so the PR strictly improves that path and neither introduces nor worsens the query path. Threading type_support into doQueryResultStructure is reserved as a follow-up (thread dismissed in r3504570103).

So the PR is effectively green; it remains BLOCKED only on human approval and the still-running CH Inc sync/PR gates.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The AI Review requested changes on the generic GEOMETRY mapping (one unresolved thread, now resolved). I confirmed it is a real, default-on regression: a MySQL column declared with the generic GEOMETRY type can hold values of any subtype, including MULTIPOINT (WKB id 4) and GEOMETRYCOLLECTION (id 7); parseWKBFormat only accepts ids 1/2/3/5/6 and the Geometry Variant has no alternative for those, so mapping it to Geometry made previously-readable rows throw BAD_ARGUMENTS at SELECT time — and it contradicted this PR's own stated "fall back to String" intent.

The AI review was right, but we made a change in the wrong direction.
Here is what I want:

Map GEOMETRY to Geometry, and accept an incompatibility - that we can throw an exception if the data in MySQL contains rarely used MULTIPOINT or GEOMETRYCOLLECTION.

Per maintainer request, map a MySQL column declared with the generic
`GEOMETRY` type to the ClickHouse umbrella `Geometry` type (a `Variant`
over the concrete geometric types) instead of falling back to `String`.

A generic `GEOMETRY` column can hold a value of any subtype, including ones
that have no ClickHouse counterpart (`MULTIPOINT`, `GEOMETRYCOLLECTION`).
Reading such a value now throws an exception at read time (`parseWKBFormat`
rejects the WKB type). This incompatibility is intentionally accepted in
exchange for exposing the column as a proper geometric type: values of the
representable subtypes (`Point`, `LineString`, `Polygon`, `MultiLineString`,
`MultiPolygon`) are read through the matching `Geometry` variant.

The read path already handles the umbrella `Geometry` type: it is mapped to
`vtGeometry` in `ExternalResultDescription`, and `insertGeometryValue`
routes the parsed object to the matching variant discriminator. Only the
schema inference in the string-based `convertMySQLDataType` overload (the
table-name path) needed the mapping; columns declared as `MULTIPOINT` or
`GEOMETRYCOLLECTION` still fall back to `String` (the raw WKB).

Updated the `test_mysql_geometry` integration test: the generic `geometry`
columns are now inferred as `Geometry`; a `geometry` column holding a
`LINESTRING` reads back as a geometric value, and one holding a `MULTIPOINT`
is rejected with `Incorrect geometry type`. Updated the setting description,
the `MySQLDataTypesSupport` enum comment, and the MySQL engine docs.

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

Copy link
Copy Markdown
Member Author

Status update (continue-pr): mapped the generic MySQL GEOMETRY type to the umbrella Geometry type, per your request. Pushed 8262da8fa51..5873568d1e7.

Reverting the earlier "wrong direction" change: the string-based (table-name) convertMySQLDataType overload now maps a MySQL column declared with the generic GEOMETRY type to the ClickHouse umbrella Geometry type (a Variant over the concrete geometric types), gated on the geometry flag, instead of falling back to String. As you asked, the incompatibility is accepted: reading a value whose subtype has no ClickHouse counterpart (MULTIPOINT, GEOMETRYCOLLECTION) throws at read time (parseWKBFormat rejects the WKB type). Columns declared as MULTIPOINT/GEOMETRYCOLLECTION themselves still fall back to String.

The read side already supports this end-to-end: Geometry maps to vtGeometry in ExternalResultDescription, and insertGeometryValue routes each parsed WKB object to the matching Variant discriminator. Only the schema inference needed to change.

Updated test_mysql_geometry (the generic geometry columns now infer as Geometry; a geometry column holding a LINESTRING reads back as [(5,5),(6,6)], and one holding a MULTIPOINT is rejected with Incorrect geometry type), the setting description, the MySQLDataTypesSupport enum comment, and the MySQL engine docs. Verified -fsyntax-only (full ARM production flags) on convertMySQLDataType.cpp and ruff/py_compile on the test.

One decision left for you — the query-backed path (the remaining AI thread on src/Storages/StorageMySQL.cpp:129). The above applies to the table-name path only. For a query-backed source (mysql(..., query('SELECT ...'))), doQueryResultStructure uses the MYSQL_FIELD overload, where MySQL reports every spatial column as MYSQL_TYPE_GEOMETRY (it can't distinguish POINT from LINESTRING), and that overload still maps it to Point. Applying the same principle there (map MYSQL_TYPE_GEOMETRY → Geometry) would fix the current LINESTRING-via-query throw and only MULTIPOINT/GEOMETRYCOLLECTION would throw — but it would also change the surface type of a POINT column read via the query form from Point to Geometry. That AI thread also notes a separate point: the effective per-call/per-engine mysql_datatypes_support_level is not threaded into doQueryResultStructure (it re-reads the query context), which affects decimal/datetime64/date2Date32 too. Both are the follow-up you reserved; say the word and I'll thread type_support into doQueryResultStructure and map query-backed MYSQL_TYPE_GEOMETRY → Geometry in the same way.

Comment thread src/Core/SettingsChangesHistory.cpp Resolved
The `26.7` `SettingsChangesHistory` entry for `mysql_datatypes_support_level`
still described the intermediate behavior where the generic `GEOMETRY` type fell
back to `String`. Since commit `5873568d1e7` the generic `GEOMETRY` column maps to
the umbrella `Geometry` type, and reading a value whose subtype has no ClickHouse
counterpart (`MULTIPOINT`, `GEOMETRYCOLLECTION`) throws at read time. Update the
reason string to match the final behavior, matching the setting description in
`Settings.cpp` and the `MySQLDataTypesSupport` enum comment.

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

Copy link
Copy Markdown
Member Author

Status update (continue-pr): addressed the stale SettingsChangesHistory note and refreshed the PR description. Pushed 5873568d1e7..7e8427366fc.

  • SettingsChangesHistory.cpp (AI thread, now resolved): the 26.7 entry for mysql_datatypes_support_level still said the generic GEOMETRY type "still maps to String", which was the intermediate behavior before 5873568d1e7. Updated the reason string to the final behavior (generic GEOMETRY → umbrella Geometry; MULTIPOINT/GEOMETRYCOLLECTION values throw at read time), matching the setting description in Settings.cpp and the MySQLDataTypesSupport enum comment.
  • PR description / changelog entry: the body table and changelog entry still described the old "generic GEOMETRY stays String" contract. Updated both to match the committed behavior so the CHANGELOG entry is accurate.

Still reserved for you — the query-backed path (remaining AI thread on src/Storages/StorageMySQL.cpp:129). Unchanged from the prior note: for mysql(..., query('SELECT ...')), doQueryResultStructure uses the MYSQL_FIELD overload, where MySQL reports every spatial column as MYSQL_TYPE_GEOMETRY and that overload still maps it to Point (so a LINESTRING read via the query form is inferred as Point and throws), and the effective per-call/per-engine mysql_datatypes_support_level is not threaded into doQueryResultStructure. Mapping query-backed MYSQL_TYPE_GEOMETRY → Geometry would fix the LINESTRING throw but would also change a POINT column's surface type from Point to Geometry on that path. Say the word and I'll thread type_support into doQueryResultStructure and apply the same mapping.

CI is green so far (0 failures; coverage/stateless/integration jobs still running).

The merge of master at dcdabc1 kept the branch side of
src/Core/SettingsChangesHistory.cpp wholesale, retaining the history entry
for `input_format_parquet_dictionary_filter_push_down` although master had
removed both the entry and the setting itself when #106952 was reverted
by #110354. The orphan entry made `Settings::applyCompatibilitySetting`
throw `UNKNOWN_SETTING` for any query with a non-empty `compatibility`
setting, failing all 19 compatibility-family tests in Fast test:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108944&sha=dcdabc13df899dbef3fdb4c5cccbbd9fadaf1803&name_0=PR&name_1=Fast%20test

Verified locally: `clickhouse local --compatibility=24.6` no longer throws,
`compatibility='26.6'` correctly rolls `mysql_datatypes_support_level` back
to `decimal,datetime64,date2Date32`, and `02325_compatibility_setting_2`
passes against its reference.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Status update (continue-pr): fixed the Fast test red on the merged head — it was merge damage, not a code problem.

The 07-14 merge of master kept this branch's side of src/Core/SettingsChangesHistory.cpp wholesale, retaining the history entry for input_format_parquet_dictionary_filter_push_down even though master had removed both the entry and the setting when #106952 was reverted by #110354. The orphan entry made Settings::applyCompatibilitySetting throw UNKNOWN_SETTING for any query with a non-empty compatibility, which is exactly the 19 compatibility-family failures in Fast test.

Pushed 7054178 removing the orphan line. Verified locally with the rebuilt binary: --compatibility=24.6 no longer throws, compatibility='26.6' still rolls mysql_datatypes_support_level back to decimal,datetime64,date2Date32 (this PR's own history entry is intact), and 02325_compatibility_setting_2 passes against its reference. I audited the rest of the merge: the three-dot diff vs master is confined to this PR's MySQL files plus that one line, and the other #106952 remnants (dictionary_filter_limit_bytes scaffolding in the Parquet reader) match master exactly.

No open review items remain — all threads are resolved. Fresh CI is running on 7054178.

@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 80.10% 86.10% +6.00%
Functions 91.30% 91.80% +0.50%
Branches 72.10% 78.20% +6.10%

Changed lines: Changed C/C++ lines covered: 154/167 (92.22%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 17, 2026
Merged via the queue into master with commit bf6d837 Jul 17, 2026
180 checks passed
@alexey-milovidov
alexey-milovidov deleted the feat/mysql-geometry-types branch July 17, 2026 15:37
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 17, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @alexey-milovidov — while reviewing this PR I found the following:

Happy to discuss — close anything that's wrong or already addressed.

@clickgapai

Copy link
Copy Markdown
Contributor

Update on the earlier review: CI on the proof PR #110924 confirmed the suspected bug via Integration tests (amd_llvm_coverage, 2/8). Filed as a separate Issue so it isn't lost when the proof PR closes:

(Automated follow-up. The proof PR has been closed; please track the bug on the Issue.)

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The earlier commit that threaded the type-mapping level into
`StorageMySQL::getTableStructureFromData` and the `StorageMySQL`
constructor changed the constructor's fallback schema inference to read
the engine `MySQLSettings` instead of the query context. The `mysql(...)`
table function creates its `StorageMySQL` with a default `MySQLSettings{}`,
so when it inferred the structure itself the default-on `geometry` (and
`decimal`/`datetime64`) flags were always applied, silently ignoring both
the per-call `SETTINGS` and the query-level `mysql_datatypes_support_level`.

This made
`SELECT toTypeName(ls) FROM mysql(...) SETTINGS mysql_datatypes_support_level = 'decimal,datetime64,date2Date32'`
infer a MySQL `LINESTRING` as `LineString` instead of `String`, and
regressed the existing `test_mysql_types` table-function assertions (e.g.
a MySQL `DATETIME(6)` read back as `DateTime64(6)` instead of `DateTime`).

`TableFunctionMySQL::parseArguments` now computes the effective
`mysql_datatypes_support_level` (the query-context value, overridden by a
function-local `SETTINGS` clause or named collection) and both
`getActualTableStructure` and `executeImpl` use it, so the table function
honors the configured level regardless of which path performs the
inference. This also addresses the review point that the per-call
`SETTINGS` opt-out was silently ignored.

Adds regression tests for the per-call `SETTINGS` opt-out and for the
per-call override of a query-level value.

CI report: ClickHouse#108944

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
Addresses the AI Review "Request changes" verdict on
ClickHouse#108944 (first required
action): query-backed `MySQL` schema inference ignored the effective
`mysql_datatypes_support_level` and always guessed every
`MYSQL_TYPE_GEOMETRY` result as `Point`.

A MySQL source defined over a query rather than a table name
(`mysql(..., query('SELECT ls FROM t'))`, or the `query('...')`/subquery
forms of the `MySQL` table engine/function) infers its columns via
`doQueryResultStructure`, which read the type-mapping level straight from
the global query context. So a per-call, per-engine, or named-collection
override for `geometry`, `decimal`, `datetime64` or `date2Date32` was
silently dropped on this path, while it was honored on the table-name path.

`doQueryResultStructure` now receives the effective
`MultiEnum<MySQLDataTypesSupport>` (`type_support`) threaded down from
`StorageMySQL::getTableStructureFromData`, the same value the table-name
path already uses, so the query-backed path honors the configured level.

In addition, the `MYSQL_FIELD` overload of `convertMySQLDataType` no longer
maps `MYSQL_TYPE_GEOMETRY` to `Point`. A query result set reports
`MYSQL_TYPE_GEOMETRY` for a value of any spatial subtype (`POINT`,
`LINESTRING`, `POLYGON`, ...) without exposing which one it is, so the
concrete geometric type cannot be inferred here. Guessing `Point` made
reading any non-`Point` value throw `Only Point data type is supported` at
read time; the value now falls back to the raw WKB `String` instead. The
concrete-type mapping (`linestring` -> `LineString`, etc.) is applied only
where MySQL exposes the concrete column type - the table-name path, via the
string overload - so a user who knows the subtype can still declare the
column type explicitly.

Note: this changes the pre-existing behavior of reading a query-backed
`POINT` column, which previously inferred `Point` and now infers `String`
(raw WKB). This is an isolated, easily reverted change if the umbrella
`Point` guess is preferred.

Added a regression test to `test_mysql_geometry`: a query-backed
`LINESTRING` is inferred as `String` (not `Point`) and reads back without a
read-time exception.

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
…mapping

Addresses the AI Review "Request changes" verdict on
ClickHouse#108944 (second required
action): the new query-context bridge in `registerStorageMySQL` gave a
session `SET mysql_datatypes_support_level` higher precedence than the value
loaded from a named collection.

`registerStorageMySQL` (and the pre-existing `DatabaseMySQL` registration)
load named-collection settings first, then call
`MySQLSettings::loadFromQueryContext` to bridge the query-context value into
the engine settings, and only afterwards replay the explicit `SETTINGS` via
`loadFromQuery`. Because `loadFromQueryContext` overwrote the value whenever
the session value differed, a table such as
`ENGINE = MySQL(my_nc, table='geom')` created under a conflicting session
`SET mysql_datatypes_support_level = '...'` ignored `my_nc`'s opt-out during
schema inference and also persisted the session value into `SHOW CREATE`.

`loadFromQueryContext` now returns early when the value was already supplied
explicitly for this engine instance (`impl->isChanged(...)`, set by a named
collection or the engine's own `SETTINGS`). The query-context bridge only
fills in the value when the engine did not set it, so the intended
precedence holds: engine `SETTINGS` > named collection > session `SET` >
default. The default case (no explicit value, session equals the default)
still persists nothing.

Added a regression test to `test_mysql_geometry` using the new
`mysql_no_geo_types` named collection (which disables `geometry`): under a
session that enables `geometry`, a `LINESTRING` column is still inferred as
`String`, and `SHOW CREATE` does not freeze the session value.

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
…try-types

Map MySQL geometry types to ClickHouse geometric types

This branch was successfully deployed

1 active deployment
staging - docs — cf90641f Deployed Jul 17, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements 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.

3 participants