Repository navigation
fix(function): support DECIMAL arithmetic and comparison with BOOL operands - #31937
Conversation
…erands Arithmetic, comparison, and assignment mixing a DECIMAL and a BOOL operand failed at plan time with "bad value [DECIMAL64 BOOL]", while MySQL binds TRUE/FALSE as the exact integers 1/0 next to DECIMAL. - bind the DECIMAL x BOOL pairs for +, -, *, /, %, DIV and the comparisons and treat a BOOL operand as one exact integral digit with scale 0 in the arithmetic domain, the division/modulo result envelope, the comparison aligner, and the safe width/scale derivation - add the missing BOOL -> DECIMAL64/128/256 cast rows and route the explicit cast through the integer parse path, keeping the existing out-of-range clamp semantics - route BOOL assignment coercion through the same declared-precision range validation the integer family uses, so TRUE is admitted exactly when the integer 1 fits the DECIMAL(p,s) column, with identical error text and statement atomicity; SELECT-context zero-width casts stay unenforced Related to matrixorigin#31181
|
CI blocker (unrelated to this PR): |
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? |
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: b5b555f88a4d113ccdcc61e4646ecf106e47a36b
Assessment: approve
Reviewed the complete delta and affected binding, precision, cast and assignment paths. BOOL consistently uses exact 0/1 semantics while preserving NULL handling and assignment bounds. No actionable findings remain.
Model: gpt-6-astra / xhigh
Session: 01a1869d-820c-7212-9788-aecfb86a4141 · slot 0 · generation 2
Validation:
-
Frozen CI reports successful UT, SCA, proxy and pessimistic multi-CN BVT; latest contexts comprise 13 success, 14 skipped and 2 neutral.
-
Local static audit passed: frozen source/delta identity, whitespace, complete discussion coverage and 158 independent numeric/NULL expected-value checks. Receipt: checks/1793400482845162208-3.json; retained logs: review-audit.stdout.log and review-audit.stderr.log.
-
Saved review-plan.md, discussion-assessment.json and validation-ledger.json. The earlier DUMP-after-flush failure remains separately tracked in issue 31790; this PR does not claim to fix it.
Limitations:
-
No local Go or SQL execution was performed; execution evidence relies on supplied CI statuses and author reports, without raw CI logs.
-
Broader PR-body coverage claims absent from the checked-in SQL were not counted as validated scenarios.
|
@Mergifyio queue |
🚫 Left the queue1 min in the queue, with no time running CI. So far
Reason The pull request can't be updated
Hint You should update or rebase your pull request manually. If you do, this pull request will automatically be requeued once the queue conditions match again. Tick the box to put this pull request back in the merge queue (same as
Times in UTC · dashboard · how the merge queue works |
|
Merge-queue blocker (merge infrastructure, unrelated to this PR's code): Mergify dequeued this PR from the GitHub response recorded by Mergify:
Verified cause:
Required action (repository administrator): an org owner accepts Mergify's pending permissions at https://dashboard.mergify.com/orgs/matrixorigin/repositories, then requeue with Current state: open, approved (mo-bot review on |
…meric branches (#32162) ## What type of PR is this? - [ ] API-change - [x] BUG - [ ] Improvement - [ ] Documentation - [ ] Feature - [ ] Test and CI - [ ] Code Refactoring ## Which issue(s) this PR fixes: Related to #31200 ## What this PR does / why we need it: ### Problem `CASE`, `IF`, `IFNULL` and `COALESCE` silently folded numeric value branches to `0`/`1` when another branch was `BOOL`: ``` select coalesce(2, true), ifnull(5, true), if(1, 2.5e0, true), case when 1 then 9 else true end; -- before: 1 1 1 1 after (MySQL 8): 2 5 2.5 9 ``` Root cause: `BOOL` has no implicit numeric cast in `fixedCanImplicitCastRule`, so the only common type every value branch could reach in `caseCheck`/`iffCheck`/`coalesceCheck` was `BOOL`, and the numeric branches were cast to `BOOL`. `IFNULL` is lowered to `CASE`, so all four constructs shared the defect. ### Change - `pkg/sql/plan/function/operatorSet.go` (`caseCheck`/`iffCheck` + shared wrapper): BOOL value branches are normalized to a numeric domain before common-type resolution — BIGINT, or DECIMAL(1,0) when a DECIMAL branch participates (TRUE/FALSE need only one integral digit). The result keeps the numeric type and TRUE/FALSE evaluate as 1/0, matching MySQL. A mixture the numeric domains cannot resolve (e.g. plan-internal DECIMAL(76,76) + BOOL) now returns a resolution error instead of silently folding to BOOL. Non-numeric mixtures (BIT, strings, dates) keep the original resolution path, and BOOL-only branches keep BOOL semantics. - `pkg/sql/plan/function/func_binary.go` (`coalesceCheck`): delegates to the same wrapper. - The BOOL→DECIMAL runtime conversion this resolution relies on (value conversion plus declared-precision validation for assignment casts: TRUE needs one integral digit, so a target with width ≤ scale, e.g. DECIMAL(1,1), rejects it with `invalid input: 1 beyond the range, can't be converted to Decimal64(1,1).`; FALSE/NULL always convert; explicit `CAST(bool AS DECIMAL(M,N))` keeps its clamp behavior, `CAST(true AS DECIMAL(1,1))` = 0.9) is already on `main` via #31937 and #30639. This PR's diff therefore no longer touches `pkg/sql/plan/function/func_cast.go`; the UT/BVT below keep covering that contract end to end. ### Tests - New UT `pkg/sql/plan/function/bool_numeric_branch_test.go`: common-type resolution for all four constructs (INT/DOUBLE/DECIMAL × BOOL, both branch orders, BOOL-only and condition-position controls, BIT/VARCHAR/DATE non-numeric controls), high-scale DECIMAL (65,57)/(65,58)/(76,75), unresolvable (76,76) must error, and BOOL→DECIMAL cast/assignment values and range errors. The new tests fail on the pre-fix code (13 subtests) and pass after. - New BVT `test/distributed/cases/function/func_bool_numeric_branches.{sql,result}`: literals and nullable columns across all four constructs, both branch orders, high-scale DECIMAL up to the publicly reachable precision 65, and assignment/clamp/error coverage (TRUE into DECIMAL(1,1) rejected via INSERT-SELECT and INSERT-VALUES, FALSE/NULL accepted, explicit CAST clamps to 0.9, failed inserts leave the table unchanged). mo-tester: 47/47 100%. - Updated goldens `func_coalesce_1.result` (BOOL+INT columns now resolve to INT) and `union_and_union_all.result` (int-typed rows under the same shared resolution); values unchanged where the old result was already correct. mo-tester: union_and_union_all 234/234 100%; the edited func_coalesce_1 goldens pass. - Commands: `.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=1800s ./pkg/sql/plan/function ./pkg/sql/plan` → `ok` both packages; `GOWORK=off go vet -mod=readonly ./pkg/sql/plan/function` → clean; `golangci-lint run -c .golangci.yml --new-from-rev <merge-base> ./pkg/sql/plan/function` → 0 issues; live-node SQL verification of the issue's exact queries. - After the 2026-11-04 rebase onto `main` (52cbba7): semantic conflict resolution in `operatorSet.go`/`func_binary.go` (the wrapper now composes with the low-precision-float widening from #29554 and the ENUM/JSON condition handling from #31492); `func_cast.go` conflicts resolved by taking `main`'s already-merged BOOL→DECIMAL support, making the file identical to `main`; the new UT's `TestBoolToDecimalCast` renamed to `TestBoolToDecimalCastAndClamp` (name already used by #31937's `decimal_bool_operand_test.go`). Re-validated: `mo-cgo-test -count=1 -v -run 'TestBoolNumericValueBranchesResolveToNumeric|TestBoolDecimalHighScaleValueBranches|TestBoolDecimalUnresolvableDoesNotFoldToBool|TestBoolNonNumericValueBranchesUnchanged|TestBoolToDecimalCastAndClamp|TestBoolToDecimalAssignmentRangeCheck|TestBoolToDecimalAssignmentValues' ./pkg/sql/plan/function` → 7/7 pass; full `pkg/sql/plan/function` package suite → `ok` 33s; `go vet` with the repository CGo environment → clean; `golangci-lint --new-from-rev 52cbba7` → 0 issues. - After CI on the rebased head, `TestDependentNativeStages` in `pkg/sql/compile` (from #31275) failed in UT Coverage: its `range_row_operand_{skipped,selected_one,uncorrelated,deep_guard}` oracles still assumed `CASE WHEN <bool> THEN <bool row comparison> ELSE 0 END` resolves to BOOL. Under this PR's intended semantics the result is numeric, so the expected values are now `1`/`0` (matching MySQL). Only the four expectation strings changed; `range_row_operand_inner_case`/`range_row_operand_coalesce` stay BOOL and keep `true`/`false`. Local: `mo-cgo-test -count=1 -run 'TestDependentNativeStages' ./pkg/sql/compile` → `ok`. ### Residual risk / notes - In one local single-node + JDBC environment, `func_coalesce_1` shows 22 additional failures that are display-width metadata drift only (e.g. `[12,-1,0]` vs `[12,25,0]`); the identical failure set occurs with the unmodified base build in that environment, every value row is byte-identical, and the affected statements include pure `select * from t1` scans this change cannot influence. CI-generated goldens should not be affected. - The unresolvable-mixture error path (needs > 66 total digits) is unreachable from public SQL because the parser caps `DECIMAL(M)` at M ≤ 65; it is covered by UT only. The public boundary (scales 57/58/65) is covered by BVT. Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
What type of PR is this?
Which issue(s) this PR fixes:
Related to #31181
What this PR does / why we need it:
Issue #31181: arithmetic, comparison, and assignment mixing a DECIMAL and a BOOL operand failed at plan time with
invalid argument operator <op>, bad value [DECIMAL64 BOOL](and the [DECIMAL128 BOOL] / [BOOL DECIMAL64] variants), while MySQL binds TRUE/FALSE as the exact integers 1/0 next to a DECIMAL.Root causes:
Changes:
type_check.go: bind the DECIMAL x BOOL pairs for +, -, *, /, %, DIV and the comparisons in both operand orders; treat BOOL as one exact integral digit, scale 0, in the safe width/scale derivation.list_operator.go: same one-digit treatment in the arithmetic domain and the comparison aligner, so maximum-width operands widen to DECIMAL256 exactly as with an integer operand.decimal_division.go/decimal_integer_division.go/decimal_mod.go: BOOL contributes (1,0) to the /, DIV and % result-type envelopes in both operand orders.func_cast.go: add the BOOL -> DECIMAL64/128/256 cast rows and route the explicit cast through the integer parse path, keeping the existing out-of-range clamp semantics; route the implicit assignment coercion through the same declared-precision range validators the integer family uses, so TRUE is admitted exactly when the integer 1 fits the DECIMAL(p,s) column, with identical error text and statement atomicity. Synthesized SELECT-context casts (zero declared width) stay unenforced, matching integers.Tests (issue-to-proof mapping):
pkg/sql/plan/function/decimal_bool_operand_test.go(new UT): operator/cast binding targets for DECIMAL64/128/256, widening at the DECIMAL(38,38) and DECIMAL256 boundaries against the INT64 control, and a 15-case assignment-width matrix proving TRUE/1 equality, FALSE/NULL acceptance, and rejection across DECIMAL64(1,1), DECIMAL128(19,19), and DECIMAL256(40,40). Command:go test ./pkg/sql/plan/function -run 'DecimalBool|BoolToDecimal|_SetSafeDecimalWidthAndScaleFromSource'. Evidence: the new UT fails on the pre-fix parent (RED) and passes after the fix (GREEN); the full package suite passes.test/distributed/cases/operator/decimal_bool_arithmetic.sql(new BVT): the exact issue reproduction, the full operator matrix, NULL propagation, FALSE zero-divisors, transactions, nonliteral BOOL operands (column, comparison result, EXISTS), assignment admission/rejection/atomicity across all three storage carriers and every write path (VALUES, multi-row, INSERT SELECT, UPDATE, ON DUPLICATE KEY UPDATE), explicit-cast clamp, DECIMAL(60,30), and capped division scale.subquery-with-exists.resultandview-subquery-with-exists.resultare regenerated for the fixed behavior. Evidence: generated results audited line by line against the intended semantics;decimal_bool_arithmetic90/90,subquery-with-exists235 passed / 0 failed / 14 skipped,view-subquery-with-exists340/0/20.All results equal the corresponding DECIMAL-with-integer-1/0 expressions in value, result class, and scale per MySQL semantics; a BOOL operand contributes exactly one integral digit to the derived precision, where an INT64-typed literal contributes 19.
Residual risks / limits: