Skip to content

Commit 0996313

Browse files
Support date arithmetic with INTERVAL operators (WordPress#539)
## Summary This PR **adds date arithmetic with `INTERVAL`**, building on WordPress#510 by @samuelmbabhazi: ```sql SELECT d + INTERVAL 1 DAY; SELECT d - INTERVAL 5 HOUR; SELECT d + INTERVAL 1 DAY - INTERVAL 2 HOUR; ``` These queries previously failed with a syntax error. They now use SQLite’s `DATE()` and `DATETIME()` functions, sharing the translation with `DATE_ADD()` and `DATE_SUB()`. ## Why the extra fixes Our current parser groups some expressions differently from MySQL. Translating them directly can produce wrong results—or update or delete the wrong rows. This PR adds safeguards to the implementation in WordPress#510: - **Reject expressions the parser cannot group correctly**, including `INTERVAL 1 DAY + d`, `1 + d + INTERVAL 1 DAY`, and `d + INTERVAL 1 DAY + x`. Errors suggest adding parentheses. - **Support `QUARTER` and `SQL_TSI_*` units**, and handle negative and computed interval values. - **Reject unsupported units**, including `MICROSECOND` and composite units such as `HOUR_MINUTE`, instead of silently returning `NULL`. - **Return dates for date-only inputs**, as MySQL does. Previously, `'2024-01-01' + INTERVAL 1 DAY` returned `2024-01-02 00:00:00`, so comparisons with `DATE` values could match the wrong rows. This also fixes `DATE_ADD()` and `DATE_SUB()`, the first case of WordPress#531. The supported forms cover the linked issues. The expression restrictions can be revisited after the planned switch to a parser based on MySQL’s own grammar. ## Remaining limitations The existing date translation still differs from MySQL in these cases: - **Numeric dates:** Values such as `20240101` are not interpreted as MySQL dates. - **Interval values:** MySQL converts the value to a whole number. Here, `INTERVAL 1.5 DAY` adds 36 hours instead of 2 days, and a string such as `' 1'` returns `NULL` with `+` but works with `-`. - **Time inputs:** `TIME` values return datetime strings, and times past midnight wrap around instead of going over 24 hours. - **Month ends:** Month-end arithmetic can overflow into the following month. - **`ADDDATE()` and `SUBDATE()`:** These functions remain unsupported. Month ends and `ADDDATE()`/`SUBDATE()` are tracked in WordPress#531. Expected results in the new tests were checked against MySQL 8.4. Fixes WordPress#454 Fixes WordPress#90 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Improved support for MySQL date and time interval calculations. - Added support for interval units from seconds through years, including weeks and quarters. - Supports chained additions and subtractions, computed intervals, and parenthesized expressions. - Date and datetime results are now handled appropriately across supported calculations. - **Bug Fixes** - Improved validation and handling of unsupported or ambiguous interval expressions. - Preserved correct NULL behavior and date calculations in updates and default values. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Samuel Mbabhazi <samuelmbabhazi@gmail.com>
1 parent e88a817 commit 0996313

3 files changed

Lines changed: 455 additions & 12 deletions

File tree

‎packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php‎

Lines changed: 154 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,23 @@ class WP_MySQL_On_SQLite extends PDO {
330330
'%y' => '%y',
331331
);
332332

333+
/**
334+
* Map MySQL INTERVAL units to SQLite units and value multipliers.
335+
*
336+
* MICROSECOND is excluded because DATETIME() drops fractional seconds.
337+
* Composite units, such as HOUR_MINUTE, are not supported.
338+
*/
339+
private const INTERVAL_UNIT_MAP = array(
340+
WP_MySQL_Lexer::SECOND_SYMBOL => array( 'SECOND', 1 ),
341+
WP_MySQL_Lexer::MINUTE_SYMBOL => array( 'MINUTE', 1 ),
342+
WP_MySQL_Lexer::HOUR_SYMBOL => array( 'HOUR', 1 ),
343+
WP_MySQL_Lexer::DAY_SYMBOL => array( 'DAY', 1 ),
344+
WP_MySQL_Lexer::WEEK_SYMBOL => array( 'DAY', 7 ),
345+
WP_MySQL_Lexer::MONTH_SYMBOL => array( 'MONTH', 1 ),
346+
WP_MySQL_Lexer::QUARTER_SYMBOL => array( 'MONTH', 3 ),
347+
WP_MySQL_Lexer::YEAR_SYMBOL => array( 'YEAR', 1 ),
348+
);
349+
333350
/**
334351
* A map of MySQL data types to implicit default values for non-strict mode.
335352
*
@@ -4349,6 +4366,8 @@ private function translate( $node ): ?string {
43494366
return null;
43504367
}
43514368
return $this->translate_sequence( $node->get_children() );
4369+
case 'bitExpr':
4370+
return $this->translate_bit_expr( $node );
43524371
case 'simpleExprBody':
43534372
return $this->translate_simple_expr_body( $node );
43544373
case 'predicateOperations':
@@ -4915,9 +4934,86 @@ private function translate_simple_expr_body( WP_Parser_Node $node ): string {
49154934
}
49164935
}
49174936

4937+
/*
4938+
* Reject "INTERVAL n unit + expr": the parser includes following AND, OR,
4939+
* and XOR conditions in "expr", unlike MySQL. It also reads
4940+
* "expr + INTERVAL 1 DAY + x" as "expr + (INTERVAL 1 DAY + x)".
4941+
*
4942+
* TODO: Support prefix intervals after switching to the LALR(1) parser.
4943+
*/
4944+
if ( null !== $token && WP_MySQL_Lexer::INTERVAL_SYMBOL === $token->id ) {
4945+
throw $this->new_not_supported_exception(
4946+
'INTERVAL n unit followed by "+"; use "(expr + INTERVAL n unit)" instead'
4947+
);
4948+
}
4949+
49184950
return $this->translate_sequence( $node->get_children() );
49194951
}
49204952

4953+
/**
4954+
* Translate a "bitExpr" AST node.
4955+
*
4956+
* Translate interval additions and subtractions to a single date function
4957+
* call, applying each interval from left to right, as MySQL does.
4958+
*
4959+
* TODO: After switching to LALR(1), use the tree's operator grouping
4960+
* and remove the loop over this parser's flat interval sequence.
4961+
*
4962+
* @param WP_Parser_Node $node The "bitExpr" AST node.
4963+
* @return string|null The translated value.
4964+
* @throws WP_MySQL_On_SQLite_Exception When the translation fails.
4965+
*/
4966+
private function translate_bit_expr( WP_Parser_Node $node ): ?string {
4967+
/*
4968+
* The first child is an expression. Each interval adds four children:
4969+
* operator, INTERVAL, value, unit. A final "op bitExpr" may follow.
4970+
*/
4971+
$children = $node->get_children();
4972+
$count = count( $children );
4973+
$sql = $this->translate( $children[0] );
4974+
$intervals = array();
4975+
$i = 1;
4976+
while (
4977+
isset( $children[ $i + 1 ] )
4978+
&& $children[ $i + 1 ] instanceof WP_Parser_Token
4979+
&& WP_MySQL_Lexer::INTERVAL_SYMBOL === $children[ $i + 1 ]->id
4980+
) {
4981+
$intervals[] = array(
4982+
WP_MySQL_Lexer::MINUS_OPERATOR === $children[ $i ]->id,
4983+
$children[ $i + 2 ],
4984+
$children[ $i + 3 ],
4985+
);
4986+
$i += 4;
4987+
}
4988+
if ( count( $intervals ) > 0 ) {
4989+
$sql = $this->translate_interval_arithmetic( $sql, $intervals );
4990+
}
4991+
4992+
if ( $i === $count ) {
4993+
return $sql;
4994+
}
4995+
4996+
/*
4997+
* The parser groups "a + b + INTERVAL 1 DAY" as "a + (b + INTERVAL 1 DAY)".
4998+
* MySQL applies the interval to "a + b". Reject this form to avoid
4999+
* applying the interval to only part of the expression. For simplicity,
5000+
* also reject operators that bind less tightly than "+", such as "|".
5001+
*
5002+
* TODO: Remove this guard and support mixed arithmetic with LALR(1).
5003+
*/
5004+
$operator = $children[ $i ];
5005+
$operand = $children[ $i + 1 ];
5006+
if ( $operand->has_child_token( WP_MySQL_Lexer::INTERVAL_SYMBOL ) ) {
5007+
throw $this->new_not_supported_exception(
5008+
sprintf(
5009+
'INTERVAL after the "%s" operator; add parentheses to make the grouping explicit',
5010+
$operator->get_value()
5011+
)
5012+
);
5013+
}
5014+
return sprintf( '%s %s %s', $sql, $this->translate( $operator ), $this->translate( $operand ) );
5015+
}
5016+
49215017
/**
49225018
* Translate a MySQL CAST expression to SQLite.
49235019
*
@@ -5051,18 +5147,9 @@ private function translate_runtime_function_call( WP_Parser_Node $node ): string
50515147
case WP_MySQL_Lexer::DATE_ADD_SYMBOL:
50525148
case WP_MySQL_Lexer::DATE_SUB_SYMBOL:
50535149
$nodes = $node->get_child_nodes();
5054-
$value = $this->translate( $nodes[1] );
5055-
$unit = $this->translate( $nodes[2] );
5056-
if ( 'WEEK' === $unit ) {
5057-
$unit = 'DAY';
5058-
$value = 7 * $value;
5059-
}
5060-
return sprintf(
5061-
"DATETIME(%s, '%s' || %s || ' %s')",
5150+
return $this->translate_interval_arithmetic(
50625151
$this->translate( $nodes[0] ),
5063-
WP_MySQL_Lexer::DATE_SUB_SYMBOL === $child->id ? '-' : '+',
5064-
$value,
5065-
$unit
5152+
array( array( WP_MySQL_Lexer::DATE_SUB_SYMBOL === $child->id, $nodes[1], $nodes[2] ) )
50665153
);
50675154
case WP_MySQL_Lexer::LEFT_SYMBOL:
50685155
$nodes = $node->get_child_nodes();
@@ -5076,6 +5163,62 @@ private function translate_runtime_function_call( WP_Parser_Node $node ): string
50765163
}
50775164
}
50785165

5166+
/**
5167+
* Translate MySQL date arithmetic to a SQLite DATE() or DATETIME() call.
5168+
*
5169+
* Each interval becomes a modifier, and SQLite applies them from left to right.
5170+
* Parenthesize the value before appending the unit: SQLite evaluates "||"
5171+
* before "*". Negate the value for subtraction so negative intervals work
5172+
* without invalid sign combinations such as "+-5 HOUR".
5173+
* Convert units where needed, e.g., WEEK to 7 days.
5174+
*
5175+
* MySQL returns a date when it adds only date units to a date. The driver
5176+
* stores dates as 10-character strings, so use DATE() for such inputs.
5177+
*
5178+
* @param string $expr The translated date expression.
5179+
* @param array $intervals List of intervals, each as an array of:
5180+
* - bool Whether the interval is subtracted.
5181+
* - WP_Parser_Node The interval value expression node.
5182+
* - WP_Parser_Node The "interval" AST node holding the unit.
5183+
* @return string The translated value.
5184+
* @throws WP_MySQL_On_SQLite_Exception When the translation fails.
5185+
*/
5186+
private function translate_interval_arithmetic( string $expr, array $intervals ): string {
5187+
$modifiers = array();
5188+
$date_units = true;
5189+
foreach ( $intervals as list( $subtract, $value, $interval ) ) {
5190+
// Token IDs also cover unit synonyms, e.g., SQL_TSI_HOUR.
5191+
$unit_token = $interval->get_first_descendant_token();
5192+
if ( ! isset( self::INTERVAL_UNIT_MAP[ $unit_token->id ] ) ) {
5193+
throw $this->new_not_supported_exception(
5194+
sprintf( 'INTERVAL unit: %s', $unit_token->get_value() )
5195+
);
5196+
}
5197+
5198+
list( $unit, $multiplier ) = self::INTERVAL_UNIT_MAP[ $unit_token->id ];
5199+
5200+
$value_sql = sprintf( '(%s)', $this->translate( $value ) );
5201+
if ( 1 !== $multiplier ) {
5202+
$value_sql = sprintf( '(%s * %d)', $value_sql, $multiplier );
5203+
}
5204+
if ( $subtract ) {
5205+
$value_sql = '-' . $value_sql;
5206+
}
5207+
$modifiers[] = sprintf( "%s || ' %s'", $value_sql, $unit );
5208+
$date_units = $date_units && in_array( $unit, array( 'DAY', 'MONTH', 'YEAR' ), true );
5209+
}
5210+
5211+
$modifiers_sql = implode( ', ', $modifiers );
5212+
if ( ! $date_units ) {
5213+
return sprintf( 'DATETIME(%s, %s)', $expr, $modifiers_sql );
5214+
}
5215+
return sprintf(
5216+
'CASE WHEN LENGTH(%1$s) = 10 THEN DATE(%1$s, %2$s) ELSE DATETIME(%1$s, %2$s) END',
5217+
$expr,
5218+
$modifiers_sql
5219+
);
5220+
}
5221+
50795222
/**
50805223
* Translate a MySQL function call to SQLite.
50815224
*

0 commit comments

Comments
 (0)