Repository navigation
fix: preserve text type in conditional string casts - #25162
10 commits merged into
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
…ry check The generic CAST was made MySQL-compatible (truncates char/varchar instead of erroring on over-length), but two paths regressed: - INSERT ... VALUES rowset cells were cast with the generic `cast`, so an over-length value was silently truncated instead of erroring. Route the rowset value cast through `cast_strict` for char/varchar targets, so all DML assignments stay strict (matches base behavior). - The runtime BatchDataStringWidthCheck rejected over-length char/varchar on every insert/load path, breaking LOAD DATA (which used to truncate/accept). With assignment cast now strict everywhere, this check is redundant for INSERT/UPDATE and only regressed LOAD, so remove it. Explicit `CAST(text AS char(N))` keeps the new truncating behavior; update the text_1 result accordingly. Co-Authored-By: Claude Opus 4.8 <[email protected]>
XuPeng-SH
left a comment
There was a problem hiding this comment.
LGTM. I reviewed the type-inference changes for COALESCE/CASE/IF, the new strict assignment cast path, rowset/INSERT/UPDATE/ON DUP paths, prepared-parameter replacement, and the unhappy paths around oversized TEXT/VARCHAR assignments.
Locally verified:
- go test ./pkg/sql/plan/function -count=1
- go test ./pkg/sql/plan -count=1
- go test ./pkg/sql/colexec ./pkg/sql/colexec/insert ./pkg/sql/colexec/preinsert ./pkg/sql/colexec/multi_update -count=1
- git diff --check origin/3.0-dev...pr-25162-review
No blocking issues found. The PR is currently behind 3.0-dev, so please update/re-run CI before merge.
XuPeng-SH
left a comment
There was a problem hiding this comment.
I found a blocker on a second pass: the new lenient generic string cast leaks into CHAR/VARCHAR column default and ON UPDATE validation.
The PR makes strToStr truncate when strictStringWidth == false. That is fine for ordinary explicit CAST, but buildDefaultExpr and buildOnUpdate validate column defaults through makePlan2CastExpr, which always builds the generic cast, not cast_strict. As a result, oversized real column defaults are now silently truncated instead of rejected.
Minimal reproduction at planner/unit level:
proc := testutil.NewProcess(t)
typ := plan.Type{Id: int32(types.T_varchar), Width: 3}
col := tree.NewColumnTableDef(
tree.NewUnresolvedColName("a"), nil,
[]tree.ColumnAttribute{&tree.AttributeDefault{Expr: tree.NewNumVal("abcdef", "abcdef", false, tree.P_char)}},
)
defaultValue, err := buildDefaultExpr(col, typ, proc)
// PR result: err == nil, defaultValue.Expr literal is "abc"
// Expected: oversized DEFAULT for varchar(3) is rejected, as before this PR.I also verified buildOnUpdate has the same issue: varchar(3) ON UPDATE 'abcdef' is accepted via a stored generic cast, and evaluating it no longer errors because generic string cast now truncates.
Suggested fix:
- Do not route real column DEFAULT / ON UPDATE validation through the lenient generic cast for
CHAR/VARCHARtargets. - Add a strict cast variant for this helper, e.g.
makePlan2AssignmentCastExprormakePlan2CastExprWithName, mirroringforceAssignmentCastExpr, and use it frombuildDefaultExprandbuildOnUpdateforT_char/T_varchartargets. - Keep explicit SQL
CAST(... AS CHAR/VARCHAR(N))and LOAD paths on genericcastif truncation there is intentional. - Add focused tests for
buildDefaultExprandbuildOnUpdaterejecting oversizedCHAR/VARCHAR(N)values, plus a positive test for explicitCAST('abcdef' AS VARCHAR(3))if that truncation is intended.
Secondary test issue: the new prepare unit tests are partly vacuous. runOneStmt(..., "prepare ...") returns the outer DCL PREPARE plan, while helpers like planHasTextToCharOrVarcharCast return false immediately when p.GetQuery() == nil. Please unwrap p.GetDcl().GetPrepare().GetPlan() in those helpers so prepare-specific assertions actually inspect the inner prepared query. Consider also scanning RowsetData / OnUpdateExprs for prepared INSERT/ON DUP cases.
Review found the lenient generic string cast leaking into real-column validation: buildDefaultExpr and buildOnUpdate route through makePlan2CastExpr (generic `cast`), so an oversized CHAR/VARCHAR(N) DEFAULT / ON UPDATE was silently truncated instead of rejected. - Add makePlan2AssignmentCastExpr, mirroring forceAssignmentCastExpr: CHAR/VARCHAR targets use `cast_strict`, everything else stays on the generic lenient `cast`. Explicit SQL CAST keeps generic truncation. - buildDefaultExpr / buildOnUpdate now use it, rejecting oversized values. - Tests: reject oversized CHAR/VARCHAR DEFAULT and ON UPDATE; accept a fitting DEFAULT; assert the helper picks cast_strict only for char/varchar. Also fix the previously-vacuous prepare assertion helpers: a PREPARE plan is a DCL node whose GetQuery() is nil, so the helpers returned false immediately. Unwrap GetDcl().GetPrepare().GetPlan() and also scan RowsetData / OnUpdateExprs so prepared INSERT/UPDATE/ON DUP assignments are actually inspected. Co-Authored-By: Claude Opus 4.8 <[email protected]>
XuPeng-SH
left a comment
There was a problem hiding this comment.
LGTM after re-reviewing the latest head (ba438817).
I specifically re-checked the previous request-changes items:
buildDefaultExpr/buildOnUpdatenow callmakePlan2AssignmentCastExpr, so CHAR/VARCHAR DEFAULT and ON UPDATE validation usescast_strictand oversized values are rejected instead of truncated.- The added tests cover oversized DEFAULT / ON UPDATE rejection for both CHAR and VARCHAR, plus the positive fitting DEFAULT case.
- The prepare-plan assertions now unwrap the inner prepared plan and scan additional expression locations (
RowsetData,OnDuplicateExpr,DedupJoinCtx,OnUpdateExprs), so they are no longer vacuous.
I also re-checked the broader write-boundary paths: UPDATE, INSERT projection, INSERT SELECT, INSERT ... ON DUPLICATE KEY UPDATE, rowset type reset / plan visitor, and forceCastExpr2 now keep CHAR/VARCHAR assignment casts strict while explicit/generic CAST remains lenient for the intended MySQL-compatible truncation behavior.
Local checks run:
go test ./pkg/sql/plan/function -count=1go test ./pkg/sql/plan -count=1go test ./pkg/sql/colexec ./pkg/sql/colexec/insert ./pkg/sql/colexec/preinsert ./pkg/sql/colexec/multi_update -count=1- targeted DEFAULT / ON UPDATE / prepare / assignment cast tests
go test ./pkg/sql/plan/function -run Test_funids -count=1git diff --check origin/3.0-dev...pr-25162-review- non-destructive merge-tree check against current
origin/3.0-dev(no conflicts)
No blocking issues found. CI is still pending and the PR is marked behind 3.0-dev, so please wait for CI/update before merge.
XuPeng-SH
left a comment
There was a problem hiding this comment.
Double-check found a blocking write-boundary hole that I missed in the previous pass, so I need to change my review to request changes.
LOAD DATA still bypasses strict CHAR/VARCHAR assignment validation. In the default LOAD path, bindExternalScan builds insertColToExpr from the external scan with the target table column type already attached (Typ: tableDef.Cols[tbColIdx].Typ for column-list LOAD at pkg/sql/plan/bind_load.go:82-92, and Typ: col.Typ for normal LOAD at pkg/sql/plan/bind_load.go:110-124). Later, insert planning calls forceAssignmentCastExpr (pkg/sql/plan/build_constraint_util.go:524-545), but forceCastExprWithName returns early when source and target types are equal (pkg/sql/plan/build_constraint_util.go:990-996). Because the external scan expression has already been labelled as varchar(N) / char(N), the new cast_strict is never inserted for LOAD.
The execution layer does not compensate for that. The strict line validator skips CHAR/VARCHAR width checks (pkg/sql/colexec/external/external.go:503-654), getColData directly appends raw bytes for parallel LOAD (pkg/sql/colexec/external/external.go:1293-1299), and the non-parallel CHAR/VARCHAR branch also directly appends bytes (pkg/sql/colexec/external/external.go:1530-1534). vector.AppendBytes is just an append helper and does not enforce the type width. I verified this locally with temporary probes: a LOAD plan contains no cast_strict, and getColData accepts/stores "abcd" into a varchar(3) vector for both ParallelLoad=false and ParallelLoad=true.
This leaves a real DML assignment path inconsistent with the PR goal: INSERT / UPDATE / DEFAULT / ON UPDATE now reject oversized CHAR/VARCHAR assignments, but LOAD DATA can still accept over-width values. A representative unhappy path is loading a row containing abcd into varchar(3)/char(3), including the parallel LOAD DATA ... parallel 'true' strict 'true' path.
Suggested fix:
- Add strict width validation for LOAD before bytes are appended, preferably in
getColDatafortypes.T_charandtypes.T_varchar, using rune count semantics consistent withstrToStr/cast_strict, and return the same data-too-long style error used by strict assignment casts. This should cover both parallel and non-parallel LOAD. - Also update the old
buildLoadfallback path if it remains reachable:makeCastExprcurrently uses genericmakePlan2CastExpr(pkg/sql/plan/build_load.go:543-557), so any fallback projection cast to CHAR/VARCHAR should use assignment-strict semantics too. - Add regression coverage:
- external unit coverage for
getColDatarejecting over-widthchar(N)/varchar(N)in bothParallelLoad=falseandParallelLoad=true; - BVT/SQL coverage for
LOAD DATAintovarchar(3)/char(3)rejectingabcd, including a parallel/no-compress case; - a positive case where a fitting value still loads successfully.
- external unit coverage for
After this is fixed I can re-run the same write-boundary sweep and re-approve.
LOAD DATA bypassed strict CHAR/VARCHAR width validation because the external scan labels columns with the target type, causing forceAssignmentCastExpr to early-return on t1.Eq(t2). Now that INSERT/ UPDATE/DEFAULT/ON UPDATE reject over-width values, LOAD must too for MySQL compatibility (non-LOCAL load in strict sql_mode defaults to error 1406 "Data too long"). - getColData (external.go): add rune-count width check for T_char and T_varchar, gated on checkLineStrict(param) (= !Local && StrictSqlMode), covering both ParallelLoad=false and ParallelLoad=true. LOCAL loads and non-strict sql_mode keep the lenient truncate/accept behavior. - makeCastExpr (build_load.go, old fallback path): use the strict assignment cast for CHAR/VARCHAR targets. - Tests: external UT covering parallel/serial, char/varchar, strict/ non-strict/local, multibyte over-width (-10 subcases); BVT SQL + result for over-width rejection (serial + parallel) and fitting success. - Update load_data.result for now-strict parallel-load t9 and 0303/htqrs sections (over-width varchar(100)/varchar(1) → "Data too long"). Co-Authored-By: Claude Opus 4.8 <[email protected]>
XuPeng-SH
left a comment
There was a problem hiding this comment.
LGTM after re-reviewing the latest head (e465a95006347ed36c3539e62f866e1f733846ff).
I re-checked the previous LOAD DATA blocker from first principles:
getColDatanow rejects over-widthCHAR/VARCHARvalues in strict SQL mode before appending bytes, using rune-count semantics consistent withcast_strict.- The check covers both serial and
ParallelLoad=truepaths because it runs before the parallel short-circuit. - LOCAL / non-strict SQL mode stays on the existing lenient path.
- The old
buildLoadfallback now usesmakePlan2AssignmentCastExpr, so fallback projection casts to real CHAR/VARCHAR columns are strict too. - The external operator path propagates
StrictSqlMode, and remote execution restoresExternfromCreateSqlbeforecheckLineStrictcan run.
I also re-swept the broader write-boundary behavior: INSERT rowset, INSERT SELECT, ON DUP UPDATE, UPDATE/multi-update, DEFAULT / ON UPDATE, prepared plan unwrapping/visiting, explicit generic CAST staying lenient, and CASE/IFF/COALESCE TEXT type preservation. I did not find a remaining blocking issue.
Local checks run:
go test ./pkg/sql/colexec/external -run 'Test_getColData_StringWidthStrict|Test_getColData_VecDimensionCheck|Test_isLegalLine_Timestamp' -count=1go test ./pkg/sql/plan/function -run 'Test_strToStr_Text.*|Test_strToStr_TextLengthCheck|Test_CaseCheck_TextStringBranchesStayText|Test_IffCheck_TextStringBranchesStayText|Test_CoalesceCheck_TextStringBranchesStayText|Test_funids' -count=1go test ./pkg/sql/plan -run 'TestBuildDefaultAndOnUpdateRejectOversizedCharVarchar|TestBuildDefaultExprFitsVarchar|TestMakePlan2AssignmentCastExprUsesStrictForCharVarchar|TestPrepareUpdateTextConcatCoalesceKeepsTextAssignmentCast|TestInsertSelectVarcharFromTextUsesStrictAssignmentCast|TestOnDuplicateUpdateVarcharFromTextUsesStrictAssignmentCast|TestUpdateTextConcatCoalesceKeepsTextAssignmentCast|TestUpdateTextCaseKeepsTextAssignmentCast|TestUpdateTextIfKeepsTextAssignmentCast|TestUpdateVarcharFromTextKeepsVarcharWidthCast' -count=1go test ./pkg/sql/plan/function -count=1go test ./pkg/sql/plan -count=1go test ./pkg/sql/colexec ./pkg/sql/colexec/insert ./pkg/sql/colexec/preinsert ./pkg/sql/colexec/multi_update -count=1go test ./pkg/sql/compile -run 'TestCompileExternScanParallelWrite|TestCompileExternScanParallelReadWrite|TestCompileExternScanParallel|TestConstructExternal|TestConvertToPipelineInstruction|TestConvertScope' -count=1 -vgit diff --check origin/3.0-dev...HEAD- non-destructive merge-tree check against current
origin/3.0-dev(no conflicts)
I also ran go test ./pkg/sql/colexec/external -count=1; it failed only in existing TestReadDirSymlink due Darwin /var vs /private/var temp-path normalization, unrelated to this PR. CI is still pending and the PR is still marked behind 3.0-dev, so please wait for CI/update before merge.
What type of PR is this?
Which issue(s) this PR fixes:
issue #23176
What this PR does / why we need it:
This PR fixes TEXT updates through conditional string result expressions while keeping MySQL-compatible ordinary string cast behavior.
COALESCE,CASE, andIF/IFFpreviously could select a narrowerCHAR/VARCHARresult type whenTEXTwas mixed with short string branches such as''. That inserted aTEXT -> CHAR/VARCHARcast before assignment, so longTEXTvalues could fail or be narrowed before being assigned back to a realTEXTcolumn.The fix keeps
TEXT + CHAR/VARCHAR/NULLresult branches on theTEXTtype for these conditional expressions. Ordinary/explicitCAST(TEXT AS CHAR/VARCHAR(N))now follows MySQL-compatible truncation semantics, while realCHAR/VARCHAR(N)DML assignment paths use internalcast_strictso oversized writes are still rejected before truncation.The strict assignment path is applied to UPDATE, INSERT projection, INSERT ... ON DUPLICATE KEY UPDATE, and update/rowset type reset paths. The BVT also covers INSERT SELECT and ON DUPLICATE KEY UPDATE oversized TEXT writes into
VARCHAR(255).Validation:
go test ./pkg/sql/plan/function -count=1go test ./pkg/sql/plan -count=1go test ./pkg/sql/colexec ./pkg/sql/colexec/insert ./pkg/sql/colexec/preinsert ./pkg/sql/colexec/multi_update -count=1make build./run.sh -p /Users/LoveYY/Develop/matrixorigin/matrixone/.worktrees/revert-text-cast/test/distributed/cases/dml/update/update_text_coalesce_cast.sql -m run -g -r 100(32/32 passed, 100%)git diff --check