Skip to content

fix: preserve text type in conditional string casts - #25162

Merged
10 commits merged into
matrixorigin:3.0-devfrom
ck89119:fix-text-cast-assignment-23176
Jun 27, 2026
Merged

10 commits merged into
matrixorigin:3.0-devfrom
ck89119:fix-text-cast-assignment-23176

Conversation

@ck89119

@ck89119 ck89119 commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

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, and IF/IFF previously could select a narrower CHAR/VARCHAR result type when TEXT was mixed with short string branches such as ''. That inserted a TEXT -> CHAR/VARCHAR cast before assignment, so long TEXT values could fail or be narrowed before being assigned back to a real TEXT column.

The fix keeps TEXT + CHAR/VARCHAR/NULL result branches on the TEXT type for these conditional expressions. Ordinary/explicit CAST(TEXT AS CHAR/VARCHAR(N)) now follows MySQL-compatible truncation semantics, while real CHAR/VARCHAR(N) DML assignment paths use internal cast_strict so 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=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
  • make 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

@ck89119
ck89119 requested a review from a user June 26, 2026 07:40
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

…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 XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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/VARCHAR targets.
  • Add a strict cast variant for this helper, e.g. makePlan2AssignmentCastExpr or makePlan2CastExprWithName, mirroring forceAssignmentCastExpr, and use it from buildDefaultExpr and buildOnUpdate for T_char/T_varchar targets.
  • Keep explicit SQL CAST(... AS CHAR/VARCHAR(N)) and LOAD paths on generic cast if truncation there is intentional.
  • Add focused tests for buildDefaultExpr and buildOnUpdate rejecting oversized CHAR/VARCHAR(N) values, plus a positive test for explicit CAST('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 XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM after re-reviewing the latest head (ba438817).

I specifically re-checked the previous request-changes items:

  • buildDefaultExpr / buildOnUpdate now call makePlan2AssignmentCastExpr, so CHAR/VARCHAR DEFAULT and ON UPDATE validation uses cast_strict and 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=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
  • targeted DEFAULT / ON UPDATE / prepare / assignment cast tests
  • go test ./pkg/sql/plan/function -run Test_funids -count=1
  • git 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 XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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:

  1. Add strict width validation for LOAD before bytes are appended, preferably in getColData for types.T_char and types.T_varchar, using rune count semantics consistent with strToStr/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.
  2. Also update the old buildLoad fallback path if it remains reachable: makeCastExpr currently uses generic makePlan2CastExpr (pkg/sql/plan/build_load.go:543-557), so any fallback projection cast to CHAR/VARCHAR should use assignment-strict semantics too.
  3. Add regression coverage:
    • external unit coverage for getColData rejecting over-width char(N)/varchar(N) in both ParallelLoad=false and ParallelLoad=true;
    • BVT/SQL coverage for LOAD DATA into varchar(3)/char(3) rejecting abcd, including a parallel/no-compress case;
    • a positive case where a fitting value still loads successfully.

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 XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM after re-reviewing the latest head (e465a95006347ed36c3539e62f866e1f733846ff).

I re-checked the previous LOAD DATA blocker from first principles:

  • getColData now rejects over-width CHAR/VARCHAR values in strict SQL mode before appending bytes, using rune-count semantics consistent with cast_strict.
  • The check covers both serial and ParallelLoad=true paths because it runs before the parallel short-circuit.
  • LOCAL / non-strict SQL mode stays on the existing lenient path.
  • The old buildLoad fallback now uses makePlan2AssignmentCastExpr, so fallback projection casts to real CHAR/VARCHAR columns are strict too.
  • The external operator path propagates StrictSqlMode, and remote execution restores Extern from CreateSql before checkLineStrict can 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=1
  • go test ./pkg/sql/plan/function -run 'Test_strToStr_Text.*|Test_strToStr_TextLengthCheck|Test_CaseCheck_TextStringBranchesStayText|Test_IffCheck_TextStringBranchesStayText|Test_CoalesceCheck_TextStringBranchesStayText|Test_funids' -count=1
  • go test ./pkg/sql/plan -run 'TestBuildDefaultAndOnUpdateRejectOversizedCharVarchar|TestBuildDefaultExprFitsVarchar|TestMakePlan2AssignmentCastExprUsesStrictForCharVarchar|TestPrepareUpdateTextConcatCoalesceKeepsTextAssignmentCast|TestInsertSelectVarcharFromTextUsesStrictAssignmentCast|TestOnDuplicateUpdateVarcharFromTextUsesStrictAssignmentCast|TestUpdateTextConcatCoalesceKeepsTextAssignmentCast|TestUpdateTextCaseKeepsTextAssignmentCast|TestUpdateTextIfKeepsTextAssignmentCast|TestUpdateVarcharFromTextKeepsVarcharWidthCast' -count=1
  • 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
  • go test ./pkg/sql/compile -run 'TestCompileExternScanParallelWrite|TestCompileExternScanParallelReadWrite|TestCompileExternScanParallel|TestConstructExternal|TestConvertToPipelineInstruction|TestConvertScope' -count=1 -v
  • git 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.

This pull request was closed.

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working kind/test-ci size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants