Skip to content

fix factorial(21) should not overflow when PostgreSQL returns a numeric answer#22306

Open
xiedeyantu wants to merge 1 commit into
apache:mainfrom
xiedeyantu:factorial
Open

fix factorial(21) should not overflow when PostgreSQL returns a numeric answer#22306
xiedeyantu wants to merge 1 commit into
apache:mainfrom
xiedeyantu:factorial

Conversation

@xiedeyantu
Copy link
Copy Markdown
Member

Which issue does this PR close?

Rationale for this change

factorial was previously implemented using an Int64 lookup table, which caused factorial(21) to fail with an overflow error. This differs from PostgreSQL, which returns an exact numeric result for this input.

This change improves PostgreSQL compatibility by allowing factorial to return exact results beyond the i64 boundary, while still preserving overflow behavior once the supported decimal range is exceeded.

What changes are included in this PR?

  • Change factorial to return Decimal256(76, 0) instead of Int64.
  • Preserve the existing lookup-table fast path for values up to 20!.
  • Extend factorial computation beyond the lookup-table range using checked i256 multiplication.
  • Keep overflow behavior for inputs whose factorial exceeds the supported Decimal256 range.
  • Add and update sqllogictest coverage for the new result and return type.

Are these changes tested?

Yes.

This PR updates sqllogictest coverage for factorial, including:

  • exact result validation for factorial(21)
  • return type validation for the new decimal result
  • updated expectations for existing scalar and columnar factorial queries

Validated with:

cargo test -p datafusion-sqllogictest --test sqllogictests scalar

Are there any user-facing changes?

Yes.

factorial(21) now returns 51090942171709440000 instead of raising an overflow error, and the return type of factorial is now Decimal256(76, 0) rather than Int64.

@github-actions github-actions Bot added sqllogictest SQL Logic Tests (.slt) functions Changes to functions implementation labels May 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

functions Changes to functions implementation sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

PostgreSQL compatibility: factorial(21) should not overflow when PostgreSQL returns a numeric answer

1 participant