Repository navigation
fix: reimplement MySQL type compatibility for 3.0-dev - #24204
Conversation
Record intent next to the three review points we deliberately deferred: - dup_entry_rewrite.go: multi-unique-index fallback to the raw __mo_index_idx_col message is a known trade-off; add a TODO for a value-type-matched future implementation. - mysql_special_types.go: isSetPlanType still piggy-backs on T_uint64 + non-empty Enumvalues. Note the migration path to a dedicated T_set OID; geometry subtypes share one OID and is called out separately. - set.go: setDescriptorCache is unbounded on purpose because SET definitions are few and per-column; document this so future readers don't mistake it for an oversight. No behavioral change. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…range check
The "single-parse at target precision" simplification in the previous round
was incorrect. The old pattern —
result, _ := strconv.ParseFloat(xStr, 32) // magnitude validation
result, _ = strconv.ParseFloat(xStr, 64) // feed full precision below
— was deliberate: floatNumToFixFloat does a Width/Scale boundary check that
must see the original decimal literal, not a float32-quantized value.
Parsing 999.995 at float32 gives ~999.9949951171875. floatNumToFixFloat then
computes v = 999 + Round(0.9949951171875 * 100) / 100 = 999.99, which is
≤ max_value 999.99, so the insert silently succeeds. With the float64 parse
reinstated, v = 1000.00 > 999.99 and the cast reports out-of-range as MySQL
does.
This fixes the float.test BVT regressions that expected
"Data truncation: data out of range: data type float, value '999.995'" on
INSERT decimal(30,3) 999.995 INTO float(5,2).
Replaces the old unit test (which locked in the wrong contract) with a
boundary-range test on both decimal128 and decimal256 paths.
…Entry Single-column UNIQUE hidden index tables use __mo_index_idx_col as their PK column name; the regex matched that and rewrote engine-level dup errors with the user-visible column name. Composite UNIQUE, though, stores the hidden index as a compound PK whose column is __mo_cpkey_col (not __mo_index_idx_col), so composite dup errors leaked the internal name. __mo_cpkey_col is also used by regular user tables with composite PKs, so we can't unconditionally rewrite it — a PK duplicate on a user table would otherwise be mislabelled as a unique-index hit. Only rewrite when the plan also contains a hidden-index-table target node (prefix __mo_index_). Tests cover both the composite-hidden-UNIQUE rewrite path and the user-table composite-PK path that must stay unchanged.
moarray.Cast used O(in[i]) for every element, so a narrowing cast like vecf64 -> vecf32 on a finite value outside float32's range became +/-Inf without any error. Guard against that: if the source element is finite but the converted result is Inf, return an out-of-range error matching the behaviour of scalar float casts. Explicit +/-Inf on the input still passes through.
…e comments The old formatStr unconditionally doubled backticks and then had a has-outer-quotes heuristic to decide whether to escape single quotes too. Both behaviours were wrong for free-form SQL text: - A DEFAULT expression like concat(`col`, 'x') is not wrapped in a backtick identifier, so doubling its interior backticks corrupted the SQL (concat(``col``, 'x')). - Column/table COMMENT strings were concatenated raw into 'X' literals, so a comment with a single quote produced parse-invalid output (COMMENT 'he's ok'). Replace formatStr with two targeted helpers: formatIdent(s) — for contents of `...` (doubles backticks). formatStrLit(s) — returns '...'-quoted literal with ''-escaped quotes. All backtick-wrapped name contexts now use formatIdent. Column, table, and index COMMENT contexts now use formatStrLit (and the old ad-hoc \' escaping for index comments is dropped). DEFAULT expression OriginString is emitted verbatim; the parser already validated it.
… ->bit
overflowForNumericToNumeric only enforced the positive bound on float
narrowing and float->integer casts, so:
- float64 -> float32 with value -1e300 became -Inf instead of erroring,
- float -> intN/uintN with a large-negative or NaN source produced a
platform-dependent magic int (Go's float->int conversion of an out-of-
range or NaN value is implementation-defined),
The numericToBit path was even looser: uint64(math.Round(v)) was applied
unconditionally to float sources, so NaN silently became 0, -1.0 became
0xffffffffffffffff, and +Inf overflowed into an arbitrary bit pattern.
Refactor the float -> integer branches through a single
checkFloatForInteger helper that rejects NaN, +/-Inf, and values rounding
outside the target range (both sides). Mirror the fix for the
float64 -> float32 branch. Add NaN/Inf/negative/above-uint64 guards in
numericToBit's float branch.
Tests exercise negative overflow, NaN, +/-Inf, and negative-to-BIT.
…idden path For CREATE UNIQUE INDEX on an existing table, the DML plan writes directly into the hidden index table with Fuzzymessage = nil. newFuzzyCheck took that branch and left displayAttr at the hidden table's PK column name — __mo_index_idx_col for a single-column UNIQUE, __mo_cpkey_col for a composite one. firstlyCheck and backgroundSQLCheck both call NewDuplicateEntry(entry, f.displayAttr) directly, bypassing the RewriteHiddenIndexDupEntry rewrite layer, so those internal names leaked straight to the user. We do not have the user-declared unique-index name at this point (the plan hid it because we are inserting into the hidden table alone), so pick a neutral placeholder: "unique index". Users still see a clear constraint- violation message; no internal catalog column name is exposed. Tests cover both single-column and composite hidden-only fallback paths.
The EXTERNAL TABLE branch built its INFILE{} key/value pairs and the
FIELDS/LINES clauses with raw fmt.Sprintf("...'%s'..."), so any user-
supplied value containing a single quote (CompressType, Format, JsonData,
FIELDS TERMINATED BY, ENCLOSED BY, ESCAPED BY, LINES STARTING BY, LINES
TERMINATED BY) produced unparseable SHOW CREATE output.
Route every one of those values through formatStrLit so single quotes are
doubled per the MySQL string-literal rule, and fix an incidental bug where
LINES TERMINATED BY printed the whole tree.Terminated struct instead of
its .Value. The byte-level NUL/backslash handling in the existing escape
closure is unchanged.
Column and table comments are stored in pre-doubled MySQL string-literal form. AttributeComment and TableOptionComment productions in mysql_sql.y both pass the parsed STRING through util.DealCommentString, which already duplicates every embedded single quote. The earlier formatStrLit wrap then doubled them again, so a comment like "%$^&*()_+@!'" (one quote) came out of SHOW CREATE as COMMENT '"%$^&*()_+@!''''' (five trailing quotes) instead of the expected COMMENT '"%$^&*()_+@!''' (three trailing quotes). This regressed test/distributed/cases/comment/comment.sql and test/distributed/cases/dml/show/show.test in BVT. Revert the two comment sites to raw 'col.Comment' / 'kv.Value' concatenation, which is correct given the pre-escape invariant. Index comments stay on formatStrLit (the parser does not DealCommentString them).
The coverage job failed at 74.625%, just below the 75% threshold, with
the biggest deficits in pkg/sql/plan/function/func_cast.go (59.3%),
pkg/sql/plan/function/arithmetic.go (75%), and
pkg/sql/plan/build_util.go (74%). The gaps were all in newly-added code
that had happy-path tests but no error-branch coverage.
Add targeted tests:
- TestDecimal256ToOthersDispatcher drives every arm of the
decimal256ToOthers switch (including the unsupported-target default),
the null-input path through each helper, the ParseInt/ParseUint
out-of-range branches, and the Width-bound rejection inside
decimal256ToStr. This lights up the 1669-1716 dispatcher table plus
the unreachable-by-happy-path error arms in each helper.
- TestSetDefaultAndOnUpdateErrorBranches covers the SET branches in
buildDefaultExpr / buildOnUpdate that reject non-foldable values and
values not in the SET members.
- TestGetTypeFromAstRejectsEmptySet triggers the NormalizeSetValues
"empty" error path in getTypeFromAst.
- divFn float32 overflow case added to
TestFloatArithmeticOverflowThroughFunctions (was missing).
- TestArrayArithmeticInfScanRejected drives the per-element IsInf
scan in plusFnArray/minusFnArray/multiFnArray/divFnArray.
No production code changes.
float64 cannot represent math.MaxInt64 (2^63 - 1) or math.MaxUint64 (2^64 - 1) exactly — they round up to 2^63 and 2^64 respectively. The earlier bounds check used `rounded > float64(MaxInt64)` which treated the un-representable 2^63 as in-range; T2(float64) of that value is implementation-defined and Go's int64 conversion produces MinInt64. The same shape of hole existed for float -> uint64 and for the float branch in numericToBit. Replace the upper-bound test on int64 / uint64 / bit(n)-via-uint64 with a strict "rounded >= first-unrepresentable-float" check (math.Pow(2, 63) / math.Pow(2, 64)). Narrower integer targets (int8/16/32, uint8/16/32) keep the plain > compare since their maxima are exactly representable. Regression test exercises the 2^63 / 2^64 boundary and the nearest exactly-representable float below each (2^63 - 1024 / 2^64 - 2048), asserting that the boundary itself is rejected while the representable predecessor still passes.
…allback constructFuzzyFilter initialised displayPkName to the target's Pkey.PkeyColName and only overrode it when n.Fuzzymessage was populated. The CREATE UNIQUE INDEX on an existing table path constructs a fuzzy filter directly against the hidden index table with Fuzzymessage == nil, so pkName stays as __mo_index_idx_col (single column) or __mo_cpkey_col (composite) and gets surfaced by fuzzyfilter.test / testAndAdd into NewDuplicateEntry. This mirrors the newFuzzyCheck hidden-only fix — when the target table is hidden and no Fuzzymessage is attached, label the key as "unique index" instead of the internal catalog column.
formatStrLit only doubled single quotes, and the ENUM/SET member
formatter EscapeFormat did not include '\' in its replace map. The MySQL
scanner treats \<x> as an escape sequence — \b becomes 0x08, \n becomes
newline, \t becomes tab, and a trailing \ collapses into the next byte.
Emitting a raw backslash back into SHOW CREATE output therefore broke
round-trip: a SET('a\b') column serialised as SET('a\b') re-parsed as
SET('a' + 0x08 + 'b'), silently changing the declared member, and the
same held for EXTERNAL TABLE option values routed through formatStrLit.
Escape backslashes first, then single quotes, in formatStrLit (order
matters — the reverse would re-escape the \\ inserted by the quote
step). Add '\\' -> "\\\\" to replaceMap so EscapeFormat covers ENUM/SET
members the same way.
Column/table COMMENT still uses plain '...' concatenation because its
value is stored in pre-escaped form by util.DealCommentString; reworking
that pre-escape contract is out of scope here.
1. Binary->narrow int cast: add bitSize range check after parsing to prevent silent truncation/wrap-around for int8/16/32 and uint8/16/32. 2. decimal128->decimal128 fast path: SetType on result vector instead of mutating the source vector's type. 3. array ScalarOp: reject NaN results (0*Inf) alongside existing Inf check. 4. SHOW CREATE comment: escape backslashes so round-trip through the MySQL scanner preserves literal backslash characters. 5. ON UPDATE OriginString: use WithSingleQuoteString() (matching Default) so string literals in expressions retain their quotes. 6. ENUM metadata: add EncodeEnumValues/DecodeEnumValues with JSON fallback for members containing commas, preventing lossy split on read-back. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
1. arrayToArray: validate source dimension against target Width before appending, rejecting mismatched array casts instead of silently producing values inconsistent with the declared column type. 2. strToStr: remove the destLen>=255 skip for TEXT sources — explicit CAST(text AS CHAR/VARCHAR(N)) must always enforce the length limit. 3. SHOW CREATE EXTERNAL TABLE: remove pre-escaping of backslash in the escape() helper for ENCLOSED BY / ESCAPED BY — formatStrLit already handles backslash escaping, so pre-escaping caused double-escape. 4. formatStrLit: handle \n, \r, \0 control characters so that CRLF line terminators round-trip distinctly from LF, and NUL bytes serialize correctly. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
1. arrayToArray: skip dimension check when target Width equals MaxArrayDimension (65535), which is the default for unsized array types — prevents false "dimension mismatch" errors on casts like VECF32(3) -> VECF64. 2. isSameColumnType: fix unconditional `return true` that ignored Width/Scale differences, causing DEFAULT/ON UPDATE expressions to skip necessary casts between same-OID types with different modifiers (e.g. DECIMAL(10,2) vs DECIMAL(18,4)). 3. Fix CI: update Test_strToStr_TextToCharVarchar expectations to match the corrected behavior (TEXT->CHAR/VARCHAR always enforces length). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
SHOW CREATE TABLE now correctly escapes backslashes in comments so that round-tripping through the parser preserves the original value. Update the expected result for `inspection_exceptions` COMMENT which contains literal backslashes. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
SHOW CREATE TABLE / VIEW splice the generated DDL text into `SELECT "..." AS \`Create Table\`` so the result set can be streamed back to the client. The outer MySQL scanner then reparses that double-quoted literal, folding `\\` -> `\` and `\"` -> `"`. The previous escape used a heuristic "double `"` unless preceded by `\`" that predated the col-comment / formatStrLit backslash-escape fix. After commits 9b63779 and 3f567a8, ddlStr carries **literal** backslashes rather than scanner escape sequences, so the heuristic misfires: `\"` was read as "already escaped" and the `"` was *not* doubled, handing an unescaped quote to the outer scanner. Effect in BVT: `show create table t_iot_equipment_inspection_stand` on the row whose COMMENT contains `\"` died with a syntax error pointing at ` AS \`Create Table\`"` because the embedded quote terminated the outer string early. Replace the heuristic with a verbatim two-pass escape (backslashes first, then quotes) and route SHOW CREATE VIEW through the same helper so view SQL with embedded backslashes likewise round-trips. Add a parser-driven round-trip unit test covering plain text, mixed backslash/quote payloads, and the exact BVT fragment. Also fix comment.result row 167 expected value: SHOW CREATE emits `["..."]` for a COMMENT whose source had no backslashes (parser stored value has no `\`). Commit 8967769 had copied the backslash- containing expected from the neighboring block; restore the original `["..."]` form so the expected matches what the server actually produces. Co-Authored-By: Claude Opus 4.7 <[email protected]>
# Conflicts: # pkg/sql/parsers/dialect/mysql/mysql_sql.go
- SET DEFAULT/ON UPDATE: funcCastForSetType now handles float and decimal literals (reject fractional/NaN/Inf/negative, accept whole non-negative via ParseSetValue) and rejects any unsupported literal instead of silently passing through. - array arithmetic: plus/minus/multi/divFnArray now reject NaN in addition to Inf; types.stringToT refuses NaN/Inf so StringToArray cannot admit non-finite elements. - blobToArray: honor types.MaxArrayDimension sentinel for unsized ARRAY<T> targets, matching strToArray. - SHOW CREATE DATABASE/TABLE/VIEW: escape the object-name slot of the outer SELECT "..." wrapper so names containing \\ or " cannot break the literal. - composite primary key: override fuzzyCheck.displayAttr to "(col1,col2,...)" when Pkey.PkeyColName is __mo_cpkey_col so DuplicateEntry errors never surface the internal column name. Co-Authored-By: Claude Opus 4.7 <[email protected]>
Round 4 fix surfaces the user-declared column list in DuplicateEntry errors on composite PK inserts, replacing the internal __mo_cpkey_col catalog column name. Update the five BVT result files whose expected output still referenced the old internal name. Co-Authored-By: Claude Opus 4.7 <[email protected]>
The optimistic-mode DuplicateEntry errors are surfaced at commit time from the transaction conflict-detection path, not from fuzzyCheck, so round 4's displayAttr fix does not affect those outputs and their original '__mo_cpkey_col' expectation is correct. Keep only the pessimistic_transaction/fulltext.result change, which does flow through fuzzyCheck.firstlyCheck. Co-Authored-By: Claude Opus 4.7 <[email protected]>
XuPeng-SH
left a comment
There was a problem hiding this comment.
Review: fix: reimplement MySQL type compatibility for 3.0-dev
This is a large PR (9871 additions, 47 commits) covering YEAR type, DECIMAL256, SET normalization, GEOMETRY mapping, float overflow hardening, duplicate-entry error rewriting, and SHOW CREATE escaping. Reviewed the critical correctness areas in depth.
Overall: LGTM
The implementation is solid across all major areas:
YEAR type — Century window logic correct (1-69→2000-2069, 70-99→1970-1999). Leading-sign and 3-digit literals properly rejected. ParseMoYear handles edge cases well.
SET type — Comma-in-member rejection, JSON-fallback encoding for ambiguous members, bitmap validation all correct. setDescriptorCache is appropriately unbounded (few SET columns per schema).
DECIMAL256 — Exponent overflow guard is mathematically correct (scalecount > MaxInt32/10 check). Bare exponent (1e, 1e+) correctly rejected. Double-e and uppercase E handled.
Float→integer cast — checkFloatForInteger correctly uses math.Pow(2, 63) as the exclusive upper bound for int64, avoiding the float64 imprecision at MaxInt64. Narrower types use standard comparisons (their maxima are exactly representable).
Duplicate-entry rewrite — len(uniques) != 1 guard prevents misattribution with multiple unique indexes. hasHiddenIndexTarget check correctly avoids rewriting user-table composite PK errors.
formatStrLit — Correctly handles \ → \\, ' → '', plus \n, \r, \0 control chars. No double-escaping risk thanks to proper separation from pre-escaped comment paths.
Minor issue (non-blocking)
floatToYear uses the old imprecise boundary check pattern:
rounded < math.MinInt64 || rounded > math.MaxInt64This has the same float64 precision issue that checkFloatForInteger was introduced to fix — float64(math.MaxInt64) == 2^63, so rounded > 2^63 allows rounded == 2^63 to pass through, making int64(2^63) undefined behavior. Impact is masked by downstream ParseMoYearFromInt validation (years must be 0 or 1901-2155), so no silent data corruption occurs. Consider using checkFloatForInteger or rounded >= math.Pow(2, 63) for consistency.
Note
The YEAR "0" / "00" → 0000 behavior diverges from MySQL's "0" → 2000 rule. The code comments acknowledge this as intentional legacy MatrixOne behavior.
Merge Queue Status
This pull request spent 20 seconds in the queue, including 4 seconds running CI. Required conditions to merge
|
What type of PR is this?
Which issue(s) this PR fixes:
issue #24184
What this PR does / why we need it:
This PR reimplements the MySQL type compatibility updates needed by
3.0-devfor issue #24184 without cherry-picking the previous backport commits.It adds or wires:
e+NN, planner literal typing, and string / NULL cast execution paths.exp()and float addition.Validation:
makemake static-checkgo test ./pkg/container/types -count=1go test ./pkg/sql/plan -count=1go test ./pkg/sql/plan/function -count=1go test ./pkg/sql/parsers/dialect/mysql -count=1go test ./pkg/compare ./pkg/sort -count=1go test ./pkg/frontend -run 'Test.*Year|Test.*Geometry|Test.*Set|TestMysqlProtocol|Test_format|Test_getDataFromPipeline' -count=1go test ./pkg/vm/engine/tae/index -run 'Test.*ZM|Test.*Zone' -count=1