Skip to content

fix(sql): support DECIMAL to BOOL cast for boolean contexts - #30923

Merged
XuPeng-SH merged 2 commits into
matrixorigin:mainfrom
MatrixAdventurer:fix/decimal-to-bool-cast
Oct 25, 2026
Merged

XuPeng-SH merged 2 commits into
matrixorigin:mainfrom
MatrixAdventurer:fix/decimal-to-bool-cast

Conversation

@MatrixAdventurer

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG

Which issue(s) this PR fixes:

Fixes #30922

What this PR does / why we need it:

Summary

DECIMAL operands in a boolean context (AND, OR, NOT, XOR, IS [NOT] TRUE/FALSE, CASE WHEN, WHERE) were rejected with invalid argument operator cast, bad value [DECIMAL64 BOOL]. The cause: supportedTypeCast had no T_bool target for any DECIMAL width, and decimal*ToOthers had no BOOL branch, so the planner refused the implicit BOOL cast that these operators insert.

This PR:

  • adds T_bool to the cast targets of T_decimal64, T_decimal128 and T_decimal256
  • adds a generic decimalToBool: non-zero is TRUE, zero is FALSE, NULL stays NULL (MySQL semantics). Zero is all-zero bits for every DECIMAL width, so the check is exact for negative and fractional values.
  • wires the new BOOL branch into the three decimal*ToOthers switches

No planner change was needed. Once the cast is registered, the existing implicit-cast path handles all of these operators.

Evidence (single-node, same SQL; main 2b388dd vs this branch)

SQL main this PR
select 0.5 and 1 ERROR 20203 [DECIMAL64 BOOL] 1
select not 0.5 / not 0.0 ERROR 0 / 1
select 0.5 xor 0 ERROR 1
select case when 0.5 then 'y' else 'n' end ERROR y
select 1 from dual where 0.5 ERROR 1 row
select cast(0.5 as decimal(38,10)) and 1 ERROR [DECIMAL128 BOOL] 1
select a from t where a (decimal(10,3): 0.5, 0, -2.25, NULL, 0.001) ERROR -2.250, 0.001, 0.500
count(*) where b (decimal(38,20)) ERROR [DECIMAL128 BOOL] 2

Tests:

  • New UT TestCastDecimalToBool covers decimal64(10,3), decimal128(38,20) and decimal256(65,30) with 0.5, 0, -2.25, NULL, 0.001 and -0.001. It fails on main and passes here. go test ./pkg/sql/plan/function/ ./pkg/sql/plan/ passes.
  • New BVT operator/decimal_bool_context.sql (24 statements). It gets 24/24 here (run 3 times); on main the 16 statements that hit the error fail.
  • BVT dirs, main vs this PR:
    • operator: 1 vs 17 failures. The one shared failure is like_operator.sql row 230, which fails the same way on main.
    • function: 2 vs 2 failures, both foreign_exttab (local environment).
    • subquery: 0 vs 0 failures. This includes the 1.1 * exists(...) pin, which still reports operator *.

Merge Danger

Low. The change only adds a cast that used to error. Existing casts are untouched. Explicit CAST(decimal AS BOOL) now works too, with the same non-zero semantics as the int and float casts.

本操作由 LW 授权的 Grok Bot 智能体执行。

@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 →

@XuPeng-SH

XuPeng-SH commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: e69ef6fe48a2a5f58ce51968e1464e16071fd13a

Review completed. Read the assessment.

@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.

mo-bot review · mo-bot-local · review

Commit: e69ef6fe48a2a5f58ce51968e1464e16071fd13a

Assessment: approve

Reviewed the complete four-file delta and affected callers. The existing cast registry and one shared conversion correctly implement nonzero DECIMAL truthiness across all widths without rounding, while preserving NULLs. Planner coercion, masked evaluation, cleanup and compatibility remain coherent. Tests provide useful internal and SQL coverage. No actionable findings remain.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1

Validation:

  • Reused frozen-head successful UT, UT coverage, static-analysis and both BVT-group checks. Audited runner selection: the function package is included, and decimal_bool_context.sql belongs to BVT group 1.

  • Reviewed constants, nullable vectors, empty inputs, selection compaction, append-error propagation, explicit casts and assignment/DDL consumers.

  • Local audit passed formatting, git diff --check, all 24 SQL/golden statement pairs and source fingerprints. Reconciled checks/1792942592751500434-4.json with review-audit.log and review-audit.json under the assigned diagnostic directory.

  • Performance analysis found bounded per-row comparisons and no new synchronization, I/O or retained state. No concrete regression risk warranted benchmarking.

Limitations:

  • CI evidence consists of the coordinator's frozen terminal statuses and audited runner definitions; raw CI logs were not supplied. No local Go or SQL tests were rerun.

  • The linked issue's standalone text and receipts for the author's baseline comparisons and repeated BVT runs were unavailable; those claims were not independently verified.

@mergify mergify Bot added the queued label Oct 25, 2026
@mergify

mergify Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-25 15:38 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-10-25 16:36 UTC · at ff083068394907e813103d4c20c6c23ea1c0f576

This pull request spent 58 minutes 7 seconds in the queue, with no time running CI.

Reason

Pull request #30923 has been dequeued

Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.

The author needs to enable "Allow edits from maintainers" on this pull request.

Hint

You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Waiting for any of
  • check-neutral = CI Required
  • check-skipped = CI Required
  • check-success = CI Required
All conditions

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

@XuPeng-SH
XuPeng-SH merged commit c887523 into matrixorigin:main Oct 25, 2026
28 of 29 checks passed
@mergify mergify Bot added dequeued and removed queued labels Oct 25, 2026
XuPeng-SH added a commit that referenced this pull request Oct 31, 2026
…erands (#31937)

## 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 #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:

- The fixed overload tables for +, -, *, /, %, DIV and the comparisons
bind no DECIMAL x BOOL pair in either operand order.
- The BOOL -> DECIMAL64/128/256 cast rows and the explicit-cast routing
are missing, so even CAST(TRUE AS DECIMAL) and the implicit coercions
fail.
- Type derivation is BOOL-blind: the arithmetic domain, the
division/modulo result envelope, the comparison aligner, and the safe
width/scale derivation handled integers but not a one-digit 0/1 operand,
which would strand or mis-derive wide operands once binding existed.
- The implicit BOOL -> DECIMAL assignment coercion never validated the
declared column precision, so TRUE/1.0 could be stored into DECIMAL(1,1)
while the integer 1 was rejected under the assignment-range contract of
#30639.

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.result` and
`view-subquery-with-exists.result` are regenerated for the fixed
behavior. Evidence: generated results audited line by line against the
intended semantics; `decimal_bool_arithmetic` 90/90,
`subquery-with-exists` 235 passed / 0 failed / 14 skipped,
`view-subquery-with-exists` 340/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:

- Protocol Length/precision of +, -, *, % results with a BOOL operand
reflects the one-digit contribution and therefore can differ from an
INT64-literal expression; result class, scale, and value are identical.
Division presentations coincide.
- BOOL / DECIMAL256 (reversed order) stays unbound, exactly as INT64 /
DECIMAL256 already is on main.
- SUM/AVG over BOOL remain governed by the separate ENABLE_BOOL_SUMAVG
sql_mode; the DECIMAL -> BOOL direction shipped separately (#30923).
- Only the distributed-BVT files listed above were run locally; the
broader suite runs in CI.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: XuPeng-SH <[email protected]>

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

dequeued kind/bug Something isn't working size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: DECIMAL values in a boolean context (AND/OR/NOT/XOR/CASE WHEN/WHERE) fail with 'bad value [DECIMAL64 BOOL]'

3 participants