Repository navigation
Use FLOAT8_FITS_IN_INT64 in dsinterval_mul - #1211
Conversation
📝 WalkthroughWalkthroughReplaced direct integer-range checks in ChangesInterval Datatype Overflow Validation
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
contrib/ivorysql_ora/src/datatype/dsinterval.c (1)
2414-2419: Consider adding the same overflow check for consistency withdsinterval_mul.The
dsinterval_divfunction has similar code that assigns arint()result toresult->timewithout checking for NaN or int64 overflow. Division by a very small factor could produce values exceeding int64 range.♻️ Suggested change for consistency
/* cascade units down */ result->day += (int32) month_remainder_days; `#ifdef` HAVE_INT64_TIMESTAMP - result->time = rint(span->time / factor + sec_remainder * USECS_PER_SEC); + result_double = rint(span->time / factor + sec_remainder * USECS_PER_SEC); + if (isnan(result_double) || !FLOAT8_FITS_IN_INT64(result_double)) + ereport(ERROR, + (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE), + errmsg("interval out of range"))); + result->time = (int64) result_double; `#else`This would require declaring
result_doubleat the top ofdsinterval_div.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/datatype/dsinterval.c` around lines 2414 - 2419, dsinterval_div currently assigns rint(span->time / factor + sec_remainder * USECS_PER_SEC) directly to result->time under HAVE_INT64_TIMESTAMP without checking for NaN or int64 overflow; mirror the dsinterval_mul pattern by declaring a double (e.g., result_double) at the top of dsinterval_div, compute result_double = span->time / factor + sec_remainder * USECS_PER_SEC, then validate with isfinite(result_double) and that result_double is within PG_INT64_MIN..PG_INT64_MAX before assigning result->time = rint(result_double); if the value is non-finite or out of range, clamp result->time to PG_INT64_MIN or PG_INT64_MAX (matching dsinterval_mul behavior) to avoid undefined overflow.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@contrib/ivorysql_ora/src/datatype/dsinterval.c`:
- Around line 2414-2419: dsinterval_div currently assigns rint(span->time /
factor + sec_remainder * USECS_PER_SEC) directly to result->time under
HAVE_INT64_TIMESTAMP without checking for NaN or int64 overflow; mirror the
dsinterval_mul pattern by declaring a double (e.g., result_double) at the top of
dsinterval_div, compute result_double = span->time / factor + sec_remainder *
USECS_PER_SEC, then validate with isfinite(result_double) and that result_double
is within PG_INT64_MIN..PG_INT64_MAX before assigning result->time =
rint(result_double); if the value is non-finite or out of range, clamp
result->time to PG_INT64_MIN or PG_INT64_MAX (matching dsinterval_mul behavior)
to avoid undefined overflow.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 91ae9c9a-d22f-4112-81b5-561637abd5ef
📒 Files selected for processing (1)
contrib/ivorysql_ora/src/datatype/dsinterval.c
3abcbab to
9cca17c
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (1)
contrib/ivorysql_ora/src/datatype/dsinterval.c (1)
2273-2274: Apply the same NaN-safety improvements toyminterval_mul,mul_d_yminterval, andyminterval_div.Both
yminterval_mulandmul_d_ymintervaluse the bounds-check patternif (result_double > INT_MAX || result_double < INT_MIN)without NaN validation, which is vulnerable to the same overflow bypass issue. Additionally,yminterval_divperforms a direct cast(int32) (span->month / factor)without any overflow or NaN protection.For consistency with
dsinterval_muland to maintain robustness, update these functions to checkisnan(result_double) || !FLOAT8_FITS_IN_INT32(result_double)before casting to int32.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/datatype/dsinterval.c` around lines 2273 - 2274, Replace the existing fragile bounds checks in yminterval_mul, mul_d_yminterval, and yminterval_div with the same NaN-safe pattern used in dsinterval_mul: compute result_double, then validate with isnan(result_double) || !FLOAT8_FITS_IN_INT32(result_double) before casting to int32 (or returning); in particular, change any checks like (result_double > INT_MAX || result_double < INT_MIN) to the combined isnan + FLOAT8_FITS_IN_INT32 check, and for yminterval_div add this validation before the direct cast (int32)(span->month / factor).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@contrib/ivorysql_ora/src/datatype/dsinterval.c`:
- Around line 2273-2274: Replace the existing fragile bounds checks in
yminterval_mul, mul_d_yminterval, and yminterval_div with the same NaN-safe
pattern used in dsinterval_mul: compute result_double, then validate with
isnan(result_double) || !FLOAT8_FITS_IN_INT32(result_double) before casting to
int32 (or returning); in particular, change any checks like (result_double >
INT_MAX || result_double < INT_MIN) to the combined isnan + FLOAT8_FITS_IN_INT32
check, and for yminterval_div add this validation before the direct cast
(int32)(span->month / factor).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 4f2e1ac3-e266-4a35-bbda-8056f769cd1c
📒 Files selected for processing (3)
contrib/ivorysql_ora/expected/ora_datetime.outcontrib/ivorysql_ora/sql/ora_datetime.sqlcontrib/ivorysql_ora/src/datatype/dsinterval.c
9cca17c to
971560b
Compare
|
@coderabbitai full review |
✅ Actions performedFull review triggered. |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
contrib/ivorysql_ora/src/datatype/dsinterval.c (2)
2390-2428:⚠️ Potential issue | 🔴 CriticalAdd NaN and range checks for month/day divisions in
dsinterval_div()before the(int32)casts.Lines 2404–2405 cast division results directly to
int32without first checking for NaN or range overflow. This leaves the function vulnerable to undefined behavior when dividing byNaNor values that produce out-of-range quotients. The newly addedresult_doubleandFLOAT8_FITS_IN_INT64()guard on line 2425 protects onlyresult->time, notmonthorday.Apply the same guarding pattern already used in
yminterval_div(): compute the division result into adouble, check withisnan()andFLOAT8_FITS_IN_INT32(), then cast toint32.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/datatype/dsinterval.c` around lines 2390 - 2428, In dsinterval_div(), avoid casting span->month/factor and span->day/factor directly to int32; instead compute each division into a double (reuse result_double), check isnan() and FLOAT8_FITS_IN_INT32() for the month and day results (like the existing check used for result->time), then cast to (int32) only after the checks; update the assignments that set result->month and result->day to perform this safe double->int32 guarded conversion and use the same error handling (ERRCODE_DATETIME_VALUE_OUT_OF_RANGE) if checks fail.
2341-2346:⚠️ Potential issue | 🟠 MajorMissing int32 overflow check for
result->dayafter time-to-day carry normalization.The overflow validation at lines 2343-2346 and 2423-2428 only ensures
result->timefits in int64. It does not validate that the subsequent carry operation at lines 2356 and 2439—result->day += result->time / USECS_PER_DAY—keepsresult->daywithin int32 bounds. For example,interval '21 23:59:59.999999' day to second * 99000000passes the int64 check but the day carry causes result->day to exceed INT32_MAX.This also applies to
dsinterval_divat lines 2423-2428 and 2439.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/datatype/dsinterval.c` around lines 2341 - 2346, After normalizing time to microseconds and performing the carry into days (the operation result->day += result->time / USECS_PER_DAY in functions handling multiplication and division—e.g., dsinterval_mul and dsinterval_div), add an explicit int32 bounds check for result->day against INT32_MIN and INT32_MAX and ereport(ERROR, errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE), errmsg("interval out of range")) if the carry makes result->day overflow; keep the existing int64 check for result->time but validate result->day immediately after the carry to prevent examples like large multipliers causing day overflow.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@contrib/ivorysql_ora/sql/ora_datetime.sql`:
- Around line 570-592: Add a missing division-by-NaN test for the day-to-second
interval: insert the SQL line "interval '365 11:11:11' day(3) to second /
'NaN'::number" alongside the other interval division/multiplication cases so the
dsinterval_div() NaN path is covered, and add the corresponding "ERROR:
interval out of range" entry to the expected output file for ora_datetime tests
to match the new failing case.
---
Outside diff comments:
In `@contrib/ivorysql_ora/src/datatype/dsinterval.c`:
- Around line 2390-2428: In dsinterval_div(), avoid casting span->month/factor
and span->day/factor directly to int32; instead compute each division into a
double (reuse result_double), check isnan() and FLOAT8_FITS_IN_INT32() for the
month and day results (like the existing check used for result->time), then cast
to (int32) only after the checks; update the assignments that set result->month
and result->day to perform this safe double->int32 guarded conversion and use
the same error handling (ERRCODE_DATETIME_VALUE_OUT_OF_RANGE) if checks fail.
- Around line 2341-2346: After normalizing time to microseconds and performing
the carry into days (the operation result->day += result->time / USECS_PER_DAY
in functions handling multiplication and division—e.g., dsinterval_mul and
dsinterval_div), add an explicit int32 bounds check for result->day against
INT32_MIN and INT32_MAX and ereport(ERROR,
errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE), errmsg("interval out of range"))
if the carry makes result->day overflow; keep the existing int64 check for
result->time but validate result->day immediately after the carry to prevent
examples like large multipliers causing day overflow.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 7dda8807-d344-4cf6-9a4f-b6219585abcb
📒 Files selected for processing (4)
contrib/ivorysql_ora/expected/ora_datetime.outcontrib/ivorysql_ora/sql/ora_datetime.sqlcontrib/ivorysql_ora/src/datatype/dsinterval.ccontrib/ivorysql_ora/src/datatype/yminterval.c
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@contrib/ivorysql_ora/sql/ora_datetime.sql`:
- Around line 579-592: Add the three missing NaN test cases that exercise the
isnan() branches in the interval arithmetic functions: add SELECT interval
'10-11' year to month * 'NaN'::number to hit yminterval_mul, SELECT interval
'10-11' year to month / 'NaN'::number to hit yminterval_div, and SELECT interval
'365 11:11:11' day(3) to second / 'NaN'::number to hit dsinterval_div; place
them alongside the existing interval tests so yminterval_mul, yminterval_div,
dsinterval_mul, and dsinterval_div all have NaN coverage.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 5b17f001-173f-460f-8492-db6dfff810dd
📒 Files selected for processing (4)
contrib/ivorysql_ora/expected/ora_datetime.outcontrib/ivorysql_ora/sql/ora_datetime.sqlcontrib/ivorysql_ora/src/datatype/dsinterval.ccontrib/ivorysql_ora/src/datatype/yminterval.c
|
@jiaoshuntian follow up this PR |
|
in dsinterval_div(): |
dsinterval_mul() compared a rounded double directly to PG_INT64_MAX, which triggers Clang because that integer constant is not exactly representable as double near 2^63. Warning excerpt: ``` src/datatype/dsinterval.c:2336:22: warning: implicit conversion from long to double changes value from 9223372036854775807 to 9223372036854775808 [-Wimplicit-const-int-float-conversion] ``` Follow the same integer-fit pattern used in timestamp.c by checking isnan() and FLOAT8_FITS_IN_INT64() after rint(). This avoids custom bound constants and keeps overflow checks consistent with core code.
dsinterval_div() in HAVE_INT64_TIMESTAMP mode assigned a rounded double directly to result->time without validating NaN/range. That can produce undefined overflow behavior on extreme inputs. Mirror dsinterval_mul() by validating the rounded value with FLOAT8_FITS_IN_INT64() before casting, and raise interval out of range when it is not representable. Add regression cases in ora_datetime for both overflow directions: interval * huge_number and interval / tiny_number, each expecting "interval out of range".
yminterval_mul() and mul_d_yminterval() still used manual INT_MAX/ INT_MIN checks on double intermediates, and yminterval_div() cast the division result directly to int32 without representability validation. Switch all three paths to the same NaN-safe pattern used in interval arithmetic: reject isnan() and !FLOAT8_FITS_IN_INT32() before casting. Add regression cases in ora_datetime for year-to-month interval overflow on both multiply (huge factor) and divide (tiny factor), each expecting "interval out of range".
dsinterval_mul() still validated month/day intermediates with manual INT_MAX/INT_MIN comparisons. That style does not reject NaN reliably and diverges from the FLOAT8_FITS_IN_INT32 pattern now used in related interval arithmetic paths. Switch month/day checks to isnan() || !FLOAT8_FITS_IN_INT32() before casting to int32. Add an ora_datetime regression case for interval day-to-second multiplication by NaN and expect "interval out of range".
971560b to
902cc4f
Compare
- dsinterval_div(): replace bare (int32) casts on month/day division with isnan() + FLOAT8_FITS_IN_INT32() guards, matching the pattern already used in dsinterval_mul(). - dsinterval_mul() and dsinterval_div(): add int32 overflow check on result->day after the time-to-day carry normalization (result->day += result->time / USECS_PER_DAY). The int64 check on result->time alone does not prevent overflow when the carry pushes day past INT32_MAX. - Merge result_double declaration with existing double variables in dsinterval_div() for cleaner variable layout. - Add 3 missing NaN test cases to ora_datetime.sql covering the yminterval_mul * NaN, yminterval_div / NaN, and dsinterval_div / NaN paths that were untested despite having isnan() guards in code. Closes CodeRabbit critical findings and jiaoshuntian review comment on the unprotected (int32) casts in dsinterval_div().
Yes, addressed in the latest commit. Sorry for the delay. |
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@contrib/ivorysql_ora/src/datatype/dsinterval.c`:
- Around line 2356-2357: The issue is in both dsinterval_mul() and
dsinterval_div() functions where the compound assignment to result->day performs
an int32 narrowing before the bounds check, allowing overflow values to wrap
around. To fix this, introduce an int64 accumulator variable to hold the
calculated day value from result->time / USECS_PER_DAY plus any existing
result->day, perform the range check on this int64 accumulator value, and only
assign to result->day after confirming the accumulated value is within the valid
int32 range. Apply this same pattern to both locations: the dsinterval_mul()
function around line 2356 and the dsinterval_div() function around line 2454.
- Around line 2238-2250: The multiplication operations computing span1_usecs and
span2_usecs overflow int64 for large int32 day values before the overflow checks
can catch it. Instead of converting full microseconds and then subtracting,
refactor to subtract the day and time components separately: subtract span2->day
from span1->day to get result->day, and subtract span2->time from span1->time to
get result->time. Then normalize any negative time (borrow) by adjusting both
result->day and result->time so that result->time remains in valid range,
converting the day borrow into the widened day accumulator. This avoids the
intermediate multiplication overflow while achieving the correct interval
difference.
In `@contrib/ivorysql_ora/src/datatype/yminterval.c`:
- Line 574: The commented-out line at 574 no longer collapses year-month into
total months, which means val2 is now expected to contain a valid parsed month
value at line 699 and the surrounding code block (lines 692-704). However,
certain code paths such as Decimal or no-month DTK_DATE paths can leave val2
uninitialized with stale values like INT_MAX instead of a proper month value.
Add validation guards for val2 before it is used in month calculations around
line 699 to ensure it contains a valid month component, preventing overflow of
tm_mon and invalid data from being processed without proper bounds checking.
- Around line 1255-1263: The multiplication of interval->month by the constant
factors (30 * USECS_PER_DAY in the HAVE_INT64_TIMESTAMP block and DAYS_PER_MONTH
* SECS_PER_DAY in the else block) causes integer overflow for large month
values. Since the code explicitly ignores day and time fields (as indicated by
the commented-out day/time span calculations), replace the span calculation in
both the `#ifdef` HAVE_INT64_TIMESTAMP and `#else` branches to directly assign
interval->month to span instead of performing the multiplication operations,
which preserves ordering without risk of overflow.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 686fcc8f-ed14-4a9a-9e52-117844ac5de3
📒 Files selected for processing (4)
contrib/ivorysql_ora/expected/ora_datetime.outcontrib/ivorysql_ora/sql/ora_datetime.sqlcontrib/ivorysql_ora/src/datatype/dsinterval.ccontrib/ivorysql_ora/src/datatype/yminterval.c
🚧 Files skipped from review as they are similar to previous changes (2)
- contrib/ivorysql_ora/expected/ora_datetime.out
- contrib/ivorysql_ora/sql/ora_datetime.sql
| span2_usecs = span2->time; | ||
| span2_usecs += span2->day * INT64CONST(24) * USECS_PER_HOUR; | ||
|
|
||
| result = (Interval *) palloc(sizeof(Interval)); | ||
|
|
||
| /* | ||
| * Compatible oracle | ||
| * For Interval day to second, the field of datetime 'YEAR' 'MONTH' will be zero. | ||
| * Recompute the value of result->day and result->time . | ||
| /* | ||
| * Compatible oracle For Interval day to second, the field of datetime | ||
| * 'YEAR' 'MONTH' will be zero. Recompute the value of result->day and | ||
| * result->time . | ||
| */ | ||
| result->month = 0; | ||
| result->day = (span1_usecs - span2_usecs) / USECS_PER_DAY; | ||
| result->time = (span1_usecs - span2_usecs) % USECS_PER_DAY; |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Verify Interval day width and dsinterval_mi day-to-microsecond aggregation.
rg -n -C3 'typedef struct Interval|int32[[:space:]]+day|span[12]_usecs[[:space:]]*\+= span[12]->day \* INT64CONST\(24\) \* USECS_PER_HOUR|result->day = \(span1_usecs - span2_usecs\)'Repository: IvorySQL/IvorySQL
Length of output: 5053
🏁 Script executed:
#!/bin/bash
# 1. Find TimeOffset definition
echo "=== TimeOffset Definition ==="
rg -n 'typedef.*TimeOffset|`#define`.*TimeOffset' --type c
# 2. Get the full function context around the problematic lines
echo -e "\n=== Full function context (lines 2220-2270) ==="
sed -n '2220,2270p' contrib/ivorysql_ora/src/datatype/dsinterval.c
# 3. Find USECS_PER_DAY, USECS_PER_HOUR definitions
echo -e "\n=== USECS definitions ==="
rg -n 'USECS_PER_DAY|USECS_PER_HOUR' -A1 --type c | head -20Repository: IvorySQL/IvorySQL
Length of output: 2872
🏁 Script executed:
#!/bin/bash
# Calculate the overflow concern: int32.MAX * USECS_PER_DAY
python3 <<'PY'
import sys
# int32 max value
int32_max = 2**31 - 1
int32_min = -(2**31)
# USECS_PER_DAY = 24 hours * 60 min * 60 sec * 1000000 microsec
USECS_PER_HOUR = 3600 * 1000000 # 3,600,000,000
USECS_PER_DAY = 24 * USECS_PER_HOUR # 86,400,000,000
# int64 max/min
int64_max = 2**63 - 1
int64_min = -(2**63)
print(f"int32_max: {int32_max}")
print(f"int32_min: {int32_min}")
print(f"USECS_PER_DAY: {USECS_PER_DAY}")
print(f"USECS_PER_HOUR: {USECS_PER_HOUR}")
print(f"\nint64_max: {int64_max}")
print(f"int64_min: {int64_min}")
# Calculate overflow
max_product = int32_max * USECS_PER_DAY
min_product = int32_min * USECS_PER_DAY
print(f"\nint32_max * USECS_PER_DAY: {max_product}")
print(f"int32_min * USECS_PER_DAY: {min_product}")
print(f"\nDoes int32_max * USECS_PER_DAY fit in int64?")
print(f" {max_product} <= {int64_max}: {max_product <= int64_max}")
print(f" {min_product} >= {int64_min}: {min_product >= int64_min}")
# Difference between two max intervals
span1_max_usecs = int32_max * USECS_PER_DAY + (2**63 - 1) # day + time components
span2_min_usecs = int32_min * USECS_PER_DAY + (-(2**63)) # min day + min time
print(f"\nDifference scenario (span1_max - span2_min):")
print(f" span1 worst case: {int32_max} * USECS_PER_DAY would overflow int64")
print(f" But the actual difference: span1_usecs - span2_usecs might still be manageable")
PYRepository: IvorySQL/IvorySQL
Length of output: 675
🏁 Script executed:
#!/bin/bash
# Check if there are overflow checks and where they are positioned
echo "=== Looking for overflow checks in the function ==="
sed -n '2220,2300p' contrib/ivorysql_ora/src/datatype/dsinterval.c | grep -n -i 'overflow\|check\|error\|range'Repository: IvorySQL/IvorySQL
Length of output: 625
The conversion span->day * INT64CONST(24) * USECS_PER_HOUR overflows int64 for valid large int32 day values.
With int32_max (2,147,483,647) multiplied by USECS_PER_DAY (86,400,000,000), the intermediate result reaches ~185 quintillion, which exceeds int64_max (9,223,372,036,854,775,807). This overflow occurs during the conversion at lines 2236 and 2239, before the overflow checks at line 2252 can catch it. The existing SAMESIGN checks only validate sign consistency of the final result, not whether the intermediate multiplication already corrupted the values.
Subtract day and time components separately, then normalize any time carry into the widened day accumulator:
Suggested direction
- TimeOffset span1_usecs;
- TimeOffset span2_usecs;
+ int64 result_day;
+ TimeOffset result_time;
- span1_usecs = span1->time;
- span1_usecs += span1->day * INT64CONST(24) * USECS_PER_HOUR;
-
- span2_usecs = span2->time;
- span2_usecs += span2->day * INT64CONST(24) * USECS_PER_HOUR;
-
result = (Interval *) palloc(sizeof(Interval));
/*
* Compatible oracle For Interval day to second, the field of datetime
* 'YEAR' 'MONTH' will be zero. Recompute the value of result->day and
* result->time .
*/
result->month = 0;
- result->day = (span1_usecs - span2_usecs) / USECS_PER_DAY;
- result->time = (span1_usecs - span2_usecs) % USECS_PER_DAY;
+ result_day = (int64) span1->day - (int64) span2->day;
+ result_time = span1->time - span2->time;
+ result_day += result_time / USECS_PER_DAY;
+ result_time = result_time % USECS_PER_DAY;
+ if (result_day > INT_MAX || result_day < INT_MIN)
+ ereport(ERROR,
+ (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
+ errmsg("interval out of range")));
+ result->day = (int32) result_day;
+ result->time = result_time;🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@contrib/ivorysql_ora/src/datatype/dsinterval.c` around lines 2238 - 2250, The
multiplication operations computing span1_usecs and span2_usecs overflow int64
for large int32 day values before the overflow checks can catch it. Instead of
converting full microseconds and then subtracting, refactor to subtract the day
and time components separately: subtract span2->day from span1->day to get
result->day, and subtract span2->time from span1->time to get result->time. Then
normalize any negative time (borrow) by adjusting both result->day and
result->time so that result->time remains in valid range, converting the day
borrow into the widened day accumulator. This avoids the intermediate
multiplication overflow while achieving the correct interval difference.
| result->day += result->time / USECS_PER_DAY; | ||
| if (result->day > INT_MAX || result->day < INT_MIN) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Locate compound assignments to result->day before range checks in interval arithmetic.
rg -n -C3 'result->day[[:space:]]*\+=|result->day > INT_MAX|result->day < INT_MIN'Repository: IvorySQL/IvorySQL
Length of output: 5594
🏁 Script executed:
#!/bin/bash
# Get context around both occurrences (lines 2330-2370 and 2420-2470)
echo "=== First occurrence (lines 2350-2365) ==="
sed -n '2350,2365p' contrib/ivorysql_ora/src/datatype/dsinterval.c | cat -n
echo -e "\n=== Second occurrence (lines 2450-2465) ==="
sed -n '2450,2465p' contrib/ivorysql_ora/src/datatype/dsinterval.c | cat -n
echo -e "\n=== Check result->day declaration ==="
rg -n 'int32.*day|day.*int32' contrib/ivorysql_ora/src/datatype/dsinterval.c | head -5Repository: IvorySQL/IvorySQL
Length of output: 1531
🏁 Script executed:
#!/bin/bash
# Check the data type of result->day in the Interval struct
rg -B5 -A5 'typedef.*Interval|struct.*Interval' contrib/ivorysql_ora/src/datatype/dsinterval.c | head -30Repository: IvorySQL/IvorySQL
Length of output: 293
🏁 Script executed:
#!/bin/bash
# Examine the full functions containing these lines to understand context
echo "=== Function containing line 2356 ==="
sed -n '2280,2365p' contrib/ivorysql_ora/src/datatype/dsinterval.c | cat -n
echo -e "\n=== Function containing line 2454 ==="
sed -n '2390,2465p' contrib/ivorysql_ora/src/datatype/dsinterval.c | cat -nRepository: IvorySQL/IvorySQL
Length of output: 6915
Check day carries before writing back to result->day.
The compound assignment at line 2356 (and also at line 2454 in dsinterval_div()) narrows result->time / USECS_PER_DAY into the int32 day field before the bounds check, allowing an overflowed value to wrap around. Use an int64 day accumulator to cascade all additions, then check the range before assigning to result->day:
Suggested fix for both functions
int32 orig_month = span->month,
orig_day = span->day;
+ int64 result_day;
Interval *result;
@@
result->day = (int32) result_double;
+ result_day = result->day;
@@
- result->day += (int32) month_remainder_days;
+ result_day += (int64) month_remainder_days;
@@
- result->day += result->time / USECS_PER_DAY;
- if (result->day > INT_MAX || result->day < INT_MIN)
+ result_day += result->time / USECS_PER_DAY;
+ if (result_day > INT_MAX || result_day < INT_MIN)
ereport(ERROR,
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
errmsg("interval out of range")));
+ result->day = (int32) result_day;
result->time = result->time % USECS_PER_DAY;Apply the same pattern in both dsinterval_mul() (line 2356) and dsinterval_div() (line 2454).
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@contrib/ivorysql_ora/src/datatype/dsinterval.c` around lines 2356 - 2357, The
issue is in both dsinterval_mul() and dsinterval_div() functions where the
compound assignment to result->day performs an int32 narrowing before the bounds
check, allowing overflow values to wrap around. To fix this, introduce an int64
accumulator variable to hold the calculated day value from result->time /
USECS_PER_DAY plus any existing result->day, perform the range check on this
int64 accumulator value, and only assign to result->day after confirming the
accumulated value is within the valid int32 range. Apply this same pattern to
both locations: the dsinterval_mul() function around line 2356 and the
dsinterval_div() function around line 2454.
| ((double) val * MONTHS_PER_YEAR + val2) < INT_MIN) | ||
| return DTERR_FIELD_OVERFLOW; | ||
| // val = val * MONTHS_PER_YEAR + val2; | ||
| /* val = val * MONTHS_PER_YEAR + val2; */ |
There was a problem hiding this comment.
Guard val2 before adding it as a month component.
After Line 574 stops collapsing year-month into total months, Line 699 now assumes val2 always contains a parsed month. Decimal/no-month DTK_DATE paths leave it as INT_MAX or stale, so invalid inputs can overflow tm_mon before validation.
Proposed fix
- errno = 0;
+ errno = 0;
+ val2 = INT_MAX;
val = strtoi(field[i], &cp, 10);
if (errno == ERANGE)
return DTERR_FIELD_OVERFLOW;
@@
case DTK_DATE:
if (tm->tm_year == INT_MAX)
tm->tm_year = 0;
- if (tm->tm_mon == INT_MAX)
- tm->tm_mon = 0;
tm->tm_year += val;
- tm->tm_mon += val2;
+ if (val2 != INT_MAX || fval != 0)
+ {
+ if (tm->tm_mon == INT_MAX)
+ tm->tm_mon = 0;
+ if (val2 != INT_MAX)
+ tm->tm_mon += val2;
+ }
if (fval != 0)
tm->tm_mon += fval * MONTHS_PER_YEAR;Also applies to: 692-704
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@contrib/ivorysql_ora/src/datatype/yminterval.c` at line 574, The
commented-out line at 574 no longer collapses year-month into total months,
which means val2 is now expected to contain a valid parsed month value at line
699 and the surrounding code block (lines 692-704). However, certain code paths
such as Decimal or no-month DTK_DATE paths can leave val2 uninitialized with
stale values like INT_MAX instead of a proper month value. Add validation guards
for val2 before it is used in month calculations around line 699 to ensure it
contains a valid month component, preventing overflow of tm_mon and invalid data
from being processed without proper bounds checking.
| /* span = interval->time; */ | ||
| span = 0; | ||
|
|
||
| #ifdef HAVE_INT64_TIMESTAMP | ||
| span += interval->month * INT64CONST(30) * USECS_PER_DAY; | ||
| // span += interval->day * INT64CONST(24) * USECS_PER_HOUR; | ||
| /* span += interval->day * INT64CONST(24) * USECS_PER_HOUR; */ | ||
| #else | ||
| span += interval->month * ((double) DAYS_PER_MONTH * SECS_PER_DAY); | ||
| // span += interval->day * ((double) HOURS_PER_DAY * SECS_PER_HOUR); | ||
| /* span += interval->day * ((double) HOURS_PER_DAY * SECS_PER_HOUR); */ |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python - <<'PY'
INT64_MAX = 9223372036854775807
USECS_PER_DAY = 86400 * 1000000
scale = 30 * USECS_PER_DAY
limit = INT64_MAX // scale
print(f"safe month-to-usec conversion limit: {limit} months")
for months in (limit, limit + 1, 4_000_000, 2_147_483_647):
value = months * scale
print(f"{months} months -> {value} usec; exceeds int64: {value > INT64_MAX}")
PY
rg -n -C 4 'yminterval_cmp_value|yminterval_cmp_internal|yminterval_(eq|ne|lt|le|gt|ge|cmp)' contrib/ivorysql_ora/src/datatype/yminterval.cRepository: IvorySQL/IvorySQL
Length of output: 6389
🏁 Script executed:
# Find Interval struct definition
rg -n "struct Interval|typedef.*Interval" contrib/ivorysql_ora/src/datatype/yminterval.c -A 10 | head -40
# Also check PostgreSQL's interval.h or similar header
fd -t f "interval.h" contrib/ivorysql_ora/src/ -x cat {}Repository: IvorySQL/IvorySQL
Length of output: 43
🏁 Script executed:
# Search for Interval struct in all relevant files
rg -n "typedef.*Interval\|struct Interval" contrib/ivorysql_ora/src/ -t c -t h
# Also look for includes in yminterval.c
head -50 contrib/ivorysql_ora/src/datatype/yminterval.c | grep -E "^`#include`"Repository: IvorySQL/IvorySQL
Length of output: 544
🏁 Script executed:
# Search for interval->month usage to understand its type
rg -n "interval->month" contrib/ivorysql_ora/src/datatype/yminterval.c -B 2 -A 2 | head -60
# Look for TimeOffset definition
rg -n "typedef.*TimeOffset|`#define` TimeOffset" contrib/ivorysql_ora/src/Repository: IvorySQL/IvorySQL
Length of output: 1184
🏁 Script executed:
# Search for Interval struct definition in postgres headers
rg -n "struct Interval" contrib/ivorysql_ora/ -t c -t h -A 8
# Also check if Interval is from postgres.h/utils/datetime.h
# by looking in standard postgres include locations
rg -n "int32.*month|month.*int32" contrib/ivorysql_ora/src/ -t c -t hRepository: IvorySQL/IvorySQL
Length of output: 889
🏁 Script executed:
# Verify TimeOffset definition
rg -n "typedef.*TimeOffset|`#define` TimeOffset" --type-list | head -20
rg -n "typedef.*TimeOffset" contrib/ivorysql_ora/src/ -t c -t h
# Also check postgres includes for TimeOffset
rg -n "TimeOffset" contrib/ivorysql_ora/src/datatype/yminterval.c | head -10Repository: IvorySQL/IvorySQL
Length of output: 741
🏁 Script executed:
# Look for TimeOffset in standard postgres includes or definition
rg -n "typedef.*TimeOffset" --type c --type h
# Check what postgres.h brings in
find contrib/ivorysql_ora -name "postgres.h" -o -name "datetime.h" | xargs cat 2>/dev/null | grep -A 2 "TimeOffset" | head -20Repository: IvorySQL/IvorySQL
Length of output: 123
🏁 Script executed:
# Verify the range constraints for yminterval
rg -n "yminterval.*range|INTERVAL_YEAR_TO_MONTH|max.*month|min.*month" contrib/ivorysql_ora/src/datatype/yminterval.c -i | head -30
# Check if there are any bounds checks on month values
rg -n "interval->month.*<|interval->month.*>|interval->month.*range" contrib/ivorysql_ora/src/datatype/yminterval.cRepository: IvorySQL/IvorySQL
Length of output: 378
🏁 Script executed:
# Verify the bounds check context
sed -n '1200,1210p' contrib/ivorysql_ora/src/datatype/yminterval.c
# Check INT_MAX definition and confirm constraint
rg -n "INT_MAX|INT_MIN" contrib/ivorysql_ora/src/datatype/yminterval.c | head -5Repository: IvorySQL/IvorySQL
Length of output: 605
Return the month count directly to avoid overflow.
Line 1259 overflows TimeOffset (int64): multiplying interval->month (int32, range -2,147,483,648 to 2,147,483,647) by 30 * USECS_PER_DAY exceeds int64 for any month value above 3,558,399. Valid yminterval values can reach INT_MAX (2,147,483,647), causing overflow in comparisons, hashing, and window function support.
Since the code explicitly ignores day and time fields (see comment at line 1247), returning the month count directly preserves ordering without overflow:
Proposed fix
static inline TimeOffset
yminterval_cmp_value(const Interval *interval)
{
- TimeOffset span;
-
-/* span = interval->time; */
- span = 0;
-
-#ifdef HAVE_INT64_TIMESTAMP
- span += interval->month * INT64CONST(30) * USECS_PER_DAY;
-/* span += interval->day * INT64CONST(24) * USECS_PER_HOUR; */
-#else
- span += interval->month * ((double) DAYS_PER_MONTH * SECS_PER_DAY);
-/* span += interval->day * ((double) HOURS_PER_DAY * SECS_PER_HOUR); */
-#endif
-
- return span;
+ return (TimeOffset) interval->month;
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| /* span = interval->time; */ | |
| span = 0; | |
| #ifdef HAVE_INT64_TIMESTAMP | |
| span += interval->month * INT64CONST(30) * USECS_PER_DAY; | |
| // span += interval->day * INT64CONST(24) * USECS_PER_HOUR; | |
| /* span += interval->day * INT64CONST(24) * USECS_PER_HOUR; */ | |
| #else | |
| span += interval->month * ((double) DAYS_PER_MONTH * SECS_PER_DAY); | |
| // span += interval->day * ((double) HOURS_PER_DAY * SECS_PER_HOUR); | |
| /* span += interval->day * ((double) HOURS_PER_DAY * SECS_PER_HOUR); */ | |
| static inline TimeOffset | |
| yminterval_cmp_value(const Interval *interval) | |
| { | |
| return (TimeOffset) interval->month; | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@contrib/ivorysql_ora/src/datatype/yminterval.c` around lines 1255 - 1263, The
multiplication of interval->month by the constant factors (30 * USECS_PER_DAY in
the HAVE_INT64_TIMESTAMP block and DAYS_PER_MONTH * SECS_PER_DAY in the else
block) causes integer overflow for large month values. Since the code explicitly
ignores day and time fields (as indicated by the commented-out day/time span
calculations), replace the span calculation in both the `#ifdef`
HAVE_INT64_TIMESTAMP and `#else` branches to directly assign interval->month to
span instead of performing the multiplication operations, which preserves
ordering without risk of overflow.
…n-max Use FLOAT8_FITS_IN_INT64 in dsinterval_mul (cherry picked from commit dbf88be)
…n-max Use FLOAT8_FITS_IN_INT64 in dsinterval_mul (cherry picked from commit dbf88be)
dsinterval_mul() compared a rounded double directly to PG_INT64_MAX, which triggers Clang because that integer constant is not exactly representable as double near 2^63.
Warning excerpt:
Follow the same integer-fit pattern used in timestamp.c by checking isnan() and FLOAT8_FITS_IN_INT64() after rint(). This avoids custom bound constants and keeps overflow checks consistent with core code.
Summary by CodeRabbit
Bug Fixes
Tests
Style / Refactor
close #1366