diff --git a/packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php b/packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php index ceeaefdf8..7562e185c 100644 --- a/packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php +++ b/packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php @@ -4723,6 +4723,22 @@ private function translate_pure_identifier( WP_Parser_Node $node ): string { ); } + /* + * MySQL accepts CURRENT_DATE and CURRENT_TIME as bare keywords with + * the same meaning as the parenthesized forms. SQLite understands + * the same keywords, so pass them through unquoted. Only intercept + * unquoted identifiers; an explicitly quoted `current_date` is still + * a regular column reference. + */ + if ( WP_MySQL_Lexer::BACK_TICK_QUOTED_ID !== $token->id ) { + if ( 0 === strcasecmp( $value, 'CURRENT_DATE' ) ) { + return 'CURRENT_DATE'; + } + if ( 0 === strcasecmp( $value, 'CURRENT_TIME' ) ) { + return 'CURRENT_TIME'; + } + } + return '`' . str_replace( '`', '``', $value ) . '`'; } @@ -5210,11 +5226,42 @@ private function translate_runtime_function_call( WP_Parser_Node $node ): string return 'CURRENT_TIMESTAMP'; case WP_MySQL_Lexer::DATE_ADD_SYMBOL: case WP_MySQL_Lexer::DATE_SUB_SYMBOL: + case WP_MySQL_Lexer::ADDDATE_SYMBOL: + case WP_MySQL_Lexer::SUBDATE_SYMBOL: $nodes = $node->get_child_nodes(); return $this->translate_interval_arithmetic( $this->translate( $nodes[0] ), - array( array( WP_MySQL_Lexer::DATE_SUB_SYMBOL === $child->id, $nodes[1], $nodes[2] ) ) + array( + array( + ( + WP_MySQL_Lexer::DATE_SUB_SYMBOL === $child->id || + WP_MySQL_Lexer::SUBDATE_SYMBOL === $child->id + ), + $nodes[1], + $nodes[2], + ), + ) ); + case WP_MySQL_Lexer::CURDATE_SYMBOL: + /* + * The lexer normalizes CURRENT_DATE to the CURDATE token but + * keeps the original spelling in the token value. SQLite + * accepts the bare CURRENT_DATE keyword with UTC semantics. + */ + if ( 0 === strcasecmp( $child->get_value(), 'CURRENT_DATE' ) ) { + return 'CURRENT_DATE'; + } + return $this->translate_sequence( $node->get_children() ); + case WP_MySQL_Lexer::CURTIME_SYMBOL: + /* + * The lexer normalizes CURRENT_TIME to the CURTIME token but + * keeps the original spelling in the token value. SQLite + * accepts the bare CURRENT_TIME keyword with UTC semantics. + */ + if ( 0 === strcasecmp( $child->get_value(), 'CURRENT_TIME' ) ) { + return 'CURRENT_TIME'; + } + return $this->translate_sequence( $node->get_children() ); case WP_MySQL_Lexer::LEFT_SYMBOL: $nodes = $node->get_child_nodes(); return sprintf( @@ -5367,6 +5414,71 @@ private function translate_function_call( WP_Parser_Node $node ): string { case 'CHAR_LENGTH': // @TODO LENGTH and CHAR_LENGTH aren't always the same in MySQL for utf8 characters. return 'LENGTH(' . $args[0] . ')'; + case 'ADDDATE': + case 'SUBDATE': + /* + * The two-argument form adds or subtracts a number of days: + * ADDDATE(date, days) is DATE_ADD(date, INTERVAL days DAY). + * The three-argument INTERVAL form parses as a + * runtimeFunctionCall and is handled in + * translate_runtime_function_call(). + */ + if ( 2 === count( $args ) ) { + /* + * MySQL treats the two-argument day count as an integer, + * so a fractional value must not become a partial-day + * time modifier. + */ + $value_sql = sprintf( 'CAST((%s) AS INTEGER)', $args[1] ); + if ( 'SUBDATE' === $name ) { + $value_sql = '-' . $value_sql; + } + $modifiers_sql = sprintf( "%s || ' DAY'", $value_sql ); + return sprintf( + 'CASE WHEN LENGTH(%1$s) = 10 THEN DATE(%1$s, %2$s) ELSE DATETIME(%1$s, %2$s) END', + $args[0], + $modifiers_sql + ); + } + return $this->translate_sequence( $node->get_children() ); + case 'TIMESTAMPADD': + case 'TIMESTAMPDIFF': + /* + * The unit arrives as a bare identifier (e.g. SECOND) which + * would otherwise translate to a quoted column reference. + * Pass it to the UDF as a string literal instead. An already + * quoted unit such as TIMESTAMPADD('SECOND', ...) is left as is. + */ + if ( isset( $nodes[1] ) ) { + $unit_args = $nodes[1]->get_child_nodes(); + if ( 3 === count( $unit_args ) ) { + return sprintf( + '%s(%s, %s, %s)', + $name, + $this->translate_keyword_arg( $unit_args[0] ), + $this->translate( $unit_args[1] ), + $this->translate( $unit_args[2] ) + ); + } + } + return $this->translate_sequence( $node->get_children() ); + case 'GET_FORMAT': + /* + * The first argument is a keyword (DATE, TIME, or DATETIME) + * which would otherwise translate to a quoted column + * reference. Pass bare keywords to the UDF as strings. + */ + if ( isset( $nodes[1] ) ) { + $format_args = $nodes[1]->get_child_nodes(); + if ( 2 === count( $format_args ) ) { + return sprintf( + 'GET_FORMAT(%s, %s)', + $this->translate_keyword_arg( $format_args[0] ), + $this->translate_keyword_arg( $format_args[1] ) + ); + } + } + return $this->translate_sequence( $node->get_children() ); case 'CONCAT': return '(' . implode( ' || ', $args ) . ')'; case 'FOUND_ROWS': @@ -5392,6 +5504,31 @@ private function translate_function_call( WP_Parser_Node $node ): string { } } + /** + * Translate a bare keyword argument to a string literal. + * + * Some functions take bare keywords where an expression would normally + * go, e.g. the unit in TIMESTAMPADD(SECOND, ...) or the type in + * GET_FORMAT(DATE, ...). The parser represents those as column + * references, which would translate to quoted identifiers and fail in + * SQLite. Pass them to the UDF as string literals instead. Arguments + * that are not bare keywords are translated normally, so already quoted + * values such as TIMESTAMPADD('SECOND', ...) keep working. + * + * @param WP_Parser_Node $node The argument AST node. + * @return string The translated value. + */ + private function translate_keyword_arg( WP_Parser_Node $node ): string { + $column_ref = $node->get_first_descendant_node( 'columnRef' ); + if ( null !== $column_ref ) { + $token = $column_ref->get_first_descendant_token(); + if ( null !== $token ) { + return $this->quote_sqlite_value( strtoupper( $token->get_value() ) ); + } + } + return $this->translate( $node ); + } + /** * Get the configured MySQL version in dotted notation. * diff --git a/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-pdo-user-defined-functions.php b/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-pdo-user-defined-functions.php index 7b8828e7b..77f24f8c0 100644 --- a/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-pdo-user-defined-functions.php +++ b/packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-pdo-user-defined-functions.php @@ -79,6 +79,34 @@ public static function register_for( $pdo ): self { 'utc_date' => 'utc_date', 'utc_time' => 'utc_time', 'utc_timestamp' => 'utc_timestamp', + 'timestampdiff' => 'timestampdiff', + 'timestampadd' => 'timestampadd', + 'timestamp' => 'timestamp', + 'curtime' => 'curtime', + 'sysdate' => 'sysdate', + 'current_user' => 'current_user', + 'last_day' => 'last_day', + 'quarter' => 'quarter', + 'dayofyear' => 'dayofyear', + 'dayname' => 'dayname', + 'monthname' => 'monthname', + 'weekofyear' => 'weekofyear', + 'yearweek' => 'yearweek', + 'makedate' => 'makedate', + 'maketime' => 'maketime', + 'sec_to_time' => 'sec_to_time', + 'time_to_sec' => 'time_to_sec', + 'to_days' => 'to_days', + 'from_days' => 'from_days', + 'to_seconds' => 'to_seconds', + 'period_add' => 'period_add', + 'period_diff' => 'period_diff', + 'microsecond' => 'microsecond', + 'addtime' => 'addtime', + 'subtime' => 'subtime', + 'get_format' => 'get_format', + 'time_format' => 'time_format', + 'str_to_date' => 'str_to_date', 'version' => 'version', 'reverse' => 'reverse', @@ -440,10 +468,6 @@ public function hour( $time ) { /** * Covers MySQL WEEK() function. * - * Always assumes $mode = 1. - * - * @TODO: Support other modes. - * * From https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_week: * * > Returns the week number for date. The two-argument form of WEEK() @@ -456,7 +480,7 @@ public function hour( $time ) { * > * > Mode First day of week Range Week 1 is the first week … * > 0 Sunday 0-53 with a Sunday in this year - * > 1 Monday 0-53 with 4 or more days this year + * > 1 Monday 0-53 with a Monday in this year * > 2 Sunday 1-53 with a Sunday in this year * > 3 Monday 1-53 with 4 or more days this year * > 4 Sunday 0-53 with 4 or more days this year @@ -464,19 +488,40 @@ public function hour( $time ) { * > 6 Sunday 1-53 with 4 or more days this year * > 7 Monday 1-53 with a Monday in this year * - * @param string $field Representing the date. - * @param int $mode The mode argument. + * All eight modes are implemented. Only the range modes (2, 3, 6, 7) + * set MySQL's WEEK_YEAR flag, so only they can report week 1 of the + * following year or roll a date into the previous year's last week. + * Modes 0, 1, 4 and 5 report week 0 for the days before week 1, and a + * late-December date stays in week 52 or 53 of its own year. Mode 3 is + * the ISO-8601 week. YEARWEEK() always sets the flag, whatever mode it + * is given. + * + * @param string $field Representing the date. + * @param int|null $mode The mode argument, 0 to 7. Defaults to 0. + * + * @return int|null The week number, or NULL for NULL or invalid input. */ - public function week( $field, $mode ) { + public function week( $field, $mode = 0 ) { + if ( null === $field || null === $mode || ! $this->mysql_value_has_date( $field ) ) { + return null; + } + // The mode is validated even though it is not applied. + if ( ! is_numeric( $mode ) || (int) $mode < 0 || (int) $mode > 7 ) { + return null; + } + $date = $this->parse_mysql_datetime( $field ); + if ( null === $date ) { + return null; + } /* - * From https://www.php.net/manual/en/datetime.format.php: - * - * W - ISO-8601 week number of year, weeks starting on Monday. - * Example: 42 (the 42nd week in the year) - * - * Week 1 is the first week with a Thursday in it. + * Approximation: always the ISO-8601 week number; the mode argument + * is accepted and ignored. MySQL has eight numbering schemes, and + * matching them needs a faithful port of its calc_week() (including + * the WEEK_YEAR flag). Until that exists this keeps the driver's + * historical behaviour, which WordPress core's Date_Query tests are + * calibrated against. */ - return intval( gmdate( 'W', strtotime( $field ) ) ); + return (int) $date->format( 'W' ); } /** @@ -927,6 +972,1734 @@ public function reverse( $str ) { return strrev( $str ); } + /** + * Method to emulate MySQL TIMESTAMPDIFF() function. + * + * Returns the integer difference of two datetimes (second minus first) + * in the given unit. Supported units are MICROSECOND (with the + * FRAC_SECOND synonym), SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, + * and YEAR, including the SQL_TSI_ prefixed spellings. Differences + * truncate toward zero, matching MySQL. MONTH, QUARTER, and YEAR count + * complete months, with end-of-month clamping like MySQL. + * + * Both values are interpreted in UTC so that wall-clock differences + * never depend on PHP's default time zone or DST transitions. + * + * Returns NULL when any argument is NULL, the unit is unknown, or an + * argument is not a valid date, datetime, or time. + * + * @param string|null $unit The unit to difference in. + * @param string|null $dt1 The datetime to subtract. + * @param string|null $dt2 The datetime to subtract from. + * + * @return int|float|null The difference in the given unit, or NULL. + */ + public function timestampdiff( $unit, $dt1, $dt2 ) { + if ( null === $unit || null === $dt1 || null === $dt2 ) { + return null; + } + $unit = $this->normalize_timestamp_unit( $unit ); + if ( null === $unit ) { + return null; + } + $date1 = $this->parse_mysql_datetime( $dt1 ); + $date2 = $this->parse_mysql_datetime( $dt2 ); + if ( null === $date1 || null === $date2 ) { + return null; + } + + switch ( $unit ) { + case 'MICROSECOND': + return $this->sqlite_safe_int( $this->datetime_diff_microseconds( $date1, $date2 ) ); + case 'SECOND': + return $this->sqlite_safe_int( intdiv( $this->datetime_diff_microseconds( $date1, $date2 ), 1000000 ) ); + case 'MINUTE': + return $this->sqlite_safe_int( intdiv( $this->datetime_diff_microseconds( $date1, $date2 ), 60000000 ) ); + case 'HOUR': + return $this->sqlite_safe_int( intdiv( $this->datetime_diff_microseconds( $date1, $date2 ), 3600000000 ) ); + case 'DAY': + return $this->sqlite_safe_int( $this->date_diff_days( $date1, $date2 ) ); + case 'WEEK': + return $this->sqlite_safe_int( intdiv( $this->date_diff_days( $date1, $date2 ), 7 ) ); + case 'MONTH': + case 'QUARTER': + case 'YEAR': + $per = ( 'MONTH' === $unit ) ? 1 : ( ( 'QUARTER' === $unit ) ? 3 : 12 ); + return $this->datetime_diff_months( $date1, $date2, $per ); + } + return null; + } + + /** + * Method to emulate MySQL TIMESTAMPADD() function. + * + * Adds an interval to a datetime, returning a 'Y-m-d H:i:s' string with + * a trimmed fractional part when the result has microseconds. Supports + * the same units as TIMESTAMPDIFF(), including the SQL_TSI_ prefixed + * spellings. Month-based units add complete months with end-of-month + * clamping like MySQL, so TIMESTAMPADD(MONTH, 1, '2024-01-31') is + * '2024-02-29'. Fractional counts of month-based units are truncated + * toward zero; other units round to the nearest microsecond. + * + * The datetime is interpreted in UTC so the result never depends on + * PHP's default time zone or DST transitions. + * + * Returns NULL when any argument is NULL, the unit is unknown, the + * count is not numeric, the datetime is invalid, or the result falls + * outside the years 0 to 9999. + * + * @param string|null $unit The unit to add in. + * @param mixed $n How many units to add (may be negative). + * @param string|null $dt The datetime to add to. + * + * @return string|null The resulting datetime, or NULL. + */ + public function timestampadd( $unit, $n, $dt ) { + if ( null === $unit || null === $n || null === $dt ) { + return null; + } + $unit = $this->normalize_timestamp_unit( $unit ); + if ( null === $unit || ! is_numeric( $n ) ) { + return null; + } + $date = $this->parse_mysql_datetime( $dt ); + if ( null === $date ) { + return null; + } + + if ( 'MONTH' === $unit || 'QUARTER' === $unit || 'YEAR' === $unit ) { + $per = ( 'MONTH' === $unit ) ? 1 : ( ( 'QUARTER' === $unit ) ? 3 : 12 ); + $months = (int) ( (float) $n * $per ); + $result = $this->add_months_clamped( $date, $months ); + if ( null === $result ) { + return null; + } + return $this->format_mysql_datetime( $result ); + } + + $factors = array( + 'MICROSECOND' => 1, + 'SECOND' => 1000000, + 'MINUTE' => 60000000, + 'HOUR' => 3600000000, + 'DAY' => 86400000000, + 'WEEK' => 604800000000, + ); + $micros = (float) $n * $factors[ $unit ]; + if ( $micros > 900000000000000000.0 || $micros < -900000000000000000.0 ) { + return null; + } + $result = $this->add_microseconds( $date, (int) round( $micros ) ); + if ( null === $result ) { + return null; + } + return $this->format_mysql_datetime( $result ); + } + + /** + * Method to emulate MySQL TIMESTAMP() function. + * + * With one argument, normalizes a date or datetime to 'Y-m-d H:i:s'. + * With two arguments, adds the time expression to the date or datetime, + * e.g. TIMESTAMP('2024-01-01', '02:00:00') is '2024-01-01 02:00:00'. + * A time-only first argument is anchored to the current UTC date, like + * MySQL anchors it to the current date. + * + * Returns NULL when any present argument is NULL or invalid. + * TIMESTAMP(dt, NULL) returns NULL, matching MySQL. + * + * @param string|null $dt A date, datetime, or time expression. + * @param string|null $dt2 An optional time expression to add. + * + * @return string|null The resulting datetime, or NULL. + */ + public function timestamp( $dt, $dt2 = null ) { + if ( null === $dt ) { + return null; + } + if ( 2 === func_num_args() && null === $dt2 ) { + return null; + } + $date = $this->parse_mysql_datetime( $dt ); + if ( null === $date ) { + return null; + } + if ( 1 === func_num_args() ) { + if ( ! $this->mysql_value_has_date( $dt ) ) { + $today = gmdate( 'Y-m-d' ); + $date = $this->parse_mysql_datetime( $today . ' ' . $date->format( 'H:i:s.u' ) ); + if ( null === $date ) { + return null; + } + } + return $this->format_mysql_datetime( $date ); + } + $micros = $this->parse_mysql_time_interval( $dt2 ); + if ( null === $micros ) { + return null; + } + $result = $this->add_microseconds( $date, $micros ); + if ( null === $result ) { + return null; + } + return $this->format_mysql_datetime( $result ); + } + + /** + * Method to emulate MySQL CURTIME() function. + * + * @return string The current UTC time formatted as 'HH:MM:SS'. + */ + public function curtime() { + return gmdate( 'H:i:s' ); + } + + /** + * Method to emulate MySQL SYSDATE() function. + * + * The driver has no separate execution timestamp, so this matches + * NOW() semantics and returns the current UTC datetime. + * + * @return string The current UTC datetime formatted as 'Y-m-d H:i:s'. + */ + public function sysdate() { + return gmdate( 'Y-m-d H:i:s' ); + } + + /** + * Method to emulate MySQL CURRENT_USER() function. + * + * The driver has no authenticated user, so this returns an empty + * string. It is provided so queries referencing CURRENT_USER() parse + * and execute instead of failing with "no such function". + * + * @return string An empty string. + */ + public function current_user() { + return ''; + } + + /** + * Method to emulate MySQL LAST_DAY() function. + * + * Returns the last day of the month for the given date, formatted as + * 'Y-m-d'. Returns NULL for NULL or invalid input. + * + * @param string|null $d A date or datetime. + * + * @return string|null The last day of the month, or NULL. + */ + public function last_day( $d ) { + if ( null === $d || ! $this->mysql_value_has_date( $d ) ) { + return null; + } + $date = $this->parse_mysql_datetime( $d ); + if ( null === $date ) { + return null; + } + $year = (int) $date->format( 'Y' ); + $month = (int) $date->format( 'n' ); + return sprintf( '%04d-%02d-%02d', $year, $month, $this->days_in_month( $year, $month ) ); + } + + /** + * Method to emulate MySQL QUARTER() function. + * + * Returns NULL for NULL or invalid input. + * + * @param string|null $d A date or datetime. + * + * @return int|null The quarter of the year, 1 to 4, or NULL. + */ + public function quarter( $d ) { + if ( null === $d || ! $this->mysql_value_has_date( $d ) ) { + return null; + } + $date = $this->parse_mysql_datetime( $d ); + if ( null === $date ) { + return null; + } + return (int) intdiv( (int) $date->format( 'n' ) + 2, 3 ); + } + + /** + * Method to emulate MySQL DAYOFYEAR() function. + * + * Returns NULL for NULL or invalid input. + * + * @param string|null $d A date or datetime. + * + * @return int|null The day of the year, 1 to 366, or NULL. + */ + public function dayofyear( $d ) { + if ( null === $d || ! $this->mysql_value_has_date( $d ) ) { + return null; + } + $date = $this->parse_mysql_datetime( $d ); + if ( null === $date ) { + return null; + } + return (int) $date->format( 'z' ) + 1; + } + + /** + * Method to emulate MySQL DAYNAME() function. + * + * Returns NULL for NULL or invalid input. + * + * @param string|null $d A date or datetime. + * + * @return string|null The English weekday name, or NULL. + */ + public function dayname( $d ) { + if ( null === $d || ! $this->mysql_value_has_date( $d ) ) { + return null; + } + $date = $this->parse_mysql_datetime( $d ); + if ( null === $date ) { + return null; + } + return $date->format( 'l' ); + } + + /** + * Method to emulate MySQL MONTHNAME() function. + * + * Returns NULL for NULL or invalid input. + * + * @param string|null $d A date or datetime. + * + * @return string|null The English month name, or NULL. + */ + public function monthname( $d ) { + if ( null === $d || ! $this->mysql_value_has_date( $d ) ) { + return null; + } + $date = $this->parse_mysql_datetime( $d ); + if ( null === $date ) { + return null; + } + return $date->format( 'F' ); + } + + /** + * Method to emulate MySQL WEEKOFYEAR() function. + * + * Equivalent to WEEK(date, 3): Monday start, range 1 to 53, week 1 is + * the first week with 4 or more days in the new year. Returns NULL for + * NULL or invalid input. + * + * @param string|null $d A date or datetime. + * + * @return int|null The week number, 1 to 53, or NULL. + */ + public function weekofyear( $d ) { + if ( null === $d || ! $this->mysql_value_has_date( $d ) ) { + return null; + } + $date = $this->parse_mysql_datetime( $d ); + if ( null === $date ) { + return null; + } + // ISO-8601 week, consistent with the WEEK() approximation above. + return (int) $date->format( 'W' ); + } + + /** + * Method to emulate MySQL YEARWEEK() function. + * + * Returns the year and week as a number, e.g. YEARWEEK('2024-05-10', 1) + * is 202419. The optional mode argument follows the same 0 to 7 modes + * as WEEK() and defaults to 0. + * + * Returns NULL for NULL arguments, invalid input, or a mode outside + * the range 0 to 7. + * + * @param string $d A date or datetime. + * @param int|null $mode The week mode, 0 to 7. Defaults to 0. + * + * @return int|null The year and week number, or NULL. + */ + public function yearweek( $d, $mode = 0 ) { + if ( null === $d || null === $mode || ! $this->mysql_value_has_date( $d ) ) { + return null; + } + // The mode is validated even though it is not applied. + if ( ! is_numeric( $mode ) || (int) $mode < 0 || (int) $mode > 7 ) { + return null; + } + $date = $this->parse_mysql_datetime( $d ); + if ( null === $date ) { + return null; + } + /* + * Built on the same ISO-8601 approximation as WEEK(), so the two + * always agree: the ISO week-year is used, which is what makes + * YEARWEEK('2021-01-01') report 202053. + */ + return (int) ( $date->format( 'o' ) * 100 + $date->format( 'W' ) ); + } + + /** + * Method to emulate MySQL MAKEDATE() function. + * + * Returns a date for the given year and day-of-year, e.g. + * MAKEDATE(2024, 60) is '2024-02-29'. Day numbers past the end of the + * year roll over into the next year. The day-of-year must be greater + * than 0 and the resulting year must fit in 0 to 9999. + * + * Returns NULL for NULL arguments, non-numeric input, or out-of-range + * values. + * + * @param mixed $year The year, 0 to 9999. + * @param mixed $dayofyear The day of the year, greater than 0. + * + * @return string|null The date formatted as 'Y-m-d', or NULL. + */ + public function makedate( $year, $dayofyear ) { + if ( null === $year || null === $dayofyear ) { + return null; + } + if ( ! is_numeric( $year ) || ! is_numeric( $dayofyear ) ) { + return null; + } + $year = (int) $year; + $dayofyear = (int) $dayofyear; + if ( $year < 0 || $year > 9999 || $dayofyear < 1 ) { + return null; + } + $elapsed = $this->days_from_civil( $year, 1, 1 ) + $dayofyear - 1; + list( $y, $m, $d ) = $this->civil_from_days( $elapsed ); + if ( $y < 0 || $y > 9999 ) { + return null; + } + return sprintf( '%04d-%02d-%02d', $y, $m, $d ); + } + + /** + * Method to emulate MySQL MAKETIME() function. + * + * The hour must be a whole number from -838 to 838, the minute a whole + * number from 0 to 59, and the second a number from 0 to just under 60. + * A fractional second is preserved with trailing zeros trimmed. + * + * Returns NULL for NULL arguments, non-numeric input, or out-of-range + * values. + * + * @param mixed $hour The hour, -838 to 838. + * @param mixed $minute The minute, 0 to 59. + * @param mixed $second The second, 0 to just under 60. + * + * @return string|null The time formatted as 'H:MM:SS', or NULL. + */ + public function maketime( $hour, $minute, $second ) { + if ( null === $hour || null === $minute || null === $second ) { + return null; + } + if ( ! is_numeric( $hour ) || ! is_numeric( $minute ) || ! is_numeric( $second ) ) { + return null; + } + $hour_float = (float) $hour; + $minute_float = (float) $minute; + $second_float = (float) $second; + if ( $hour_float < -838 || $hour_float > 838 || $minute_float < 0 || $minute_float > 59 ) { + return null; + } + if ( (float) (int) $hour_float !== $hour_float || (float) (int) $minute_float !== $minute_float ) { + return null; + } + if ( $second_float < 0 || $second_float >= 60 ) { + return null; + } + $micros = ( ( (int) $hour_float * 60 ) + (int) $minute_float ) * 60000000 + (int) round( $second_float * 1000000 ); + return $this->format_mysql_time( $micros ); + } + + /** + * Method to emulate MySQL SEC_TO_TIME() function. + * + * Converts seconds to a TIME value. The result is clamped to the MySQL + * TIME range of -838:59:59 to 838:59:59: any input past 3020399 seconds + * in magnitude returns the range endpoint without a fractional part. + * A fractional input is preserved with trailing zeros trimmed. + * + * Returns NULL for NULL or non-numeric input. + * + * @param mixed $seconds The number of seconds. + * + * @return string|null The time, or NULL. + */ + public function sec_to_time( $seconds ) { + if ( null === $seconds || ! is_numeric( $seconds ) ) { + return null; + } + $value = (float) $seconds; + if ( $value > 3020399 || $value < -3020399 ) { + return $this->format_mysql_time( $value > 0 ? 3020399000000 : -3020399000000 ); + } + return $this->format_mysql_time( (int) round( $value * 1000000 ) ); + } + + /** + * Method to emulate MySQL TIME_TO_SEC() function. + * + * Converts a time value to seconds, truncating any fractional part + * toward zero. Accepts times with hours past 24 and negative times, + * as well as datetimes, for which the time-of-day part is converted. + * + * Returns NULL for NULL or invalid input. + * + * @param string|null $time A time or datetime. + * + * @return int|null The number of seconds, or NULL. + */ + public function time_to_sec( $time ) { + if ( null === $time ) { + return null; + } + $micros = $this->parse_mysql_time_interval( $time ); + if ( null === $micros ) { + $date = $this->parse_mysql_datetime( $time ); + if ( null === $date ) { + return null; + } + $micros = ( ( (int) $date->format( 'G' ) * 60 ) + (int) $date->format( 'i' ) ) * 60000000 + (int) $date->format( 's' ) * 1000000; + } + return (int) intdiv( $micros, 1000000 ); + } + + /** + * Method to emulate MySQL TO_DAYS() function. + * + * Returns the day number of a date using proleptic Gregorian + * day-number math anchored at year 0, so TO_DAYS('0000-01-01') is 1 + * and TO_DAYS('2007-10-07') is 733321. Year 0 maps to days 1 through + * 365, and year 1 continues at 366, matching MySQL's day-numbering. + * + * Returns NULL for NULL input, invalid dates, or values without a + * date part. + * + * @param string|null $d A date or datetime. + * + * @return int|null The day number, or NULL. + */ + public function to_days( $d ) { + if ( null === $d || ! $this->mysql_value_has_date( $d ) ) { + return null; + } + $date = $this->parse_mysql_datetime( $d ); + if ( null === $date ) { + return null; + } + $year = (int) $date->format( 'Y' ); + $elapsed = $this->days_from_civil( $year, (int) $date->format( 'n' ), (int) $date->format( 'j' ) ) - $this->days_from_civil( 0, 1, 1 ); + return (int) ( $elapsed + ( 0 === $year ? 1 : 0 ) ); + } + + /** + * Method to emulate MySQL FROM_DAYS() function. + * + * Returns the date for a day number, the inverse of TO_DAYS(): + * FROM_DAYS(1) is '0000-01-01' and FROM_DAYS(733321) is '2007-10-07'. + * Day number 0 would be the MySQL zero date '0000-00-00', which this + * driver reports as NULL, so any number below 1 returns NULL. Numbers + * past '9999-12-31' (3652424) also return NULL. + * + * @param mixed $n The day number. + * + * @return string|null The date formatted as 'Y-m-d', or NULL. + */ + public function from_days( $n ) { + if ( null === $n || ! is_numeric( $n ) ) { + return null; + } + $n = (int) $n; + if ( $n < 1 || $n > 3652424 ) { + return null; + } + $elapsed = ( $n >= 366 ) ? $n : ( $n - 1 ); + list( $y, $m, $d ) = $this->civil_from_days( $elapsed + $this->days_from_civil( 0, 1, 1 ) ); + return sprintf( '%04d-%02d-%02d', $y, $m, $d ); + } + + /** + * Method to emulate MySQL TO_SECONDS() function. + * + * Returns the seconds since year 0: (TO_DAYS(date) - 1) * 86400 plus + * the seconds of the time-of-day part. Fractional seconds are dropped. + * TO_SECONDS('2007-10-07') is 63358848000. + * + * Returns NULL for NULL input, invalid values, or values without a + * date part. + * + * @param string|null $dt A date or datetime. + * + * @return int|float|null The number of seconds, or NULL. + */ + public function to_seconds( $dt ) { + if ( null === $dt || ! $this->mysql_value_has_date( $dt ) ) { + return null; + } + $date = $this->parse_mysql_datetime( $dt ); + if ( null === $date ) { + return null; + } + $year = (int) $date->format( 'Y' ); + $elapsed = $this->days_from_civil( $year, (int) $date->format( 'n' ), (int) $date->format( 'j' ) ) - $this->days_from_civil( 0, 1, 1 ); + $days = $elapsed + ( 0 === $year ? 1 : 0 ); + return $this->sqlite_safe_int( ( $days - 1 ) * 86400 + (int) $date->format( 'G' ) * 3600 + (int) $date->format( 'i' ) * 60 + (int) $date->format( 's' ) ); + } + + /** + * Method to emulate MySQL PERIOD_ADD() function. + * + * Adds months to a period in YYMM or YYYYMM format, e.g. + * PERIOD_ADD(200801, 2) is 200803 and PERIOD_ADD(200812, 1) is 200901. + * Two-digit years use MySQL's conversion, 00 to 69 becoming 2000 to + * 2069 and 70 to 99 becoming 1970 to 1999, and the result keeps the + * same digit width as the input. + * + * Returns NULL for NULL arguments, non-numeric input, invalid months, + * or results outside the representable range. + * + * @param mixed $period The period in YYMM or YYYYMM format. + * @param mixed $months The number of months to add (may be negative). + * + * @return int|null The resulting period, or NULL. + */ + public function period_add( $period, $months ) { + if ( null === $period || null === $months ) { + return null; + } + if ( ! is_numeric( $period ) || ! is_numeric( $months ) ) { + return null; + } + $parts = $this->period_to_months( $period ); + if ( null === $parts ) { + return null; + } + list( $total ) = $parts; + $total += (int) $months; + $year = (int) floor( $total / 12 ); + $month = (int) ( $total - $year * 12 + 1 ); + if ( $year < 0 || $year > 9999 ) { + return null; + } + return (int) ( $year * 100 + $month ); + } + + /** + * Method to emulate MySQL PERIOD_DIFF() function. + * + * Returns the months between two periods in YYMM or YYYYMM format, + * e.g. PERIOD_DIFF(200802, 200703) is 11. Two-digit years convert as + * in PERIOD_ADD(). + * + * Returns NULL for NULL arguments, non-numeric input, or invalid + * months. + * + * @param mixed $p1 The first period. + * @param mixed $p2 The period to subtract. + * + * @return int|null The difference in months, or NULL. + */ + public function period_diff( $p1, $p2 ) { + if ( null === $p1 || null === $p2 ) { + return null; + } + $parts1 = $this->period_to_months( $p1 ); + $parts2 = $this->period_to_months( $p2 ); + if ( null === $parts1 || null === $parts2 ) { + return null; + } + return (int) ( $parts1[0] - $parts2[0] ); + } + + /** + * Method to emulate MySQL MICROSECOND() function. + * + * Returns the microseconds part of a time or datetime, 0 to 999999. + * Returns 0 when the value has no fractional seconds, and NULL for + * NULL or invalid input. + * + * @param string|null $time A time or datetime. + * + * @return int|null The microseconds part, or NULL. + */ + public function microsecond( $time ) { + if ( null === $time ) { + return null; + } + $micros = $this->parse_mysql_time_interval( $time ); + if ( null !== $micros ) { + $part = (int) ( $micros % 1000000 ); + return (int) ( $part < 0 ? $part + 1000000 : $part ); + } + $date = $this->parse_mysql_datetime( $time ); + if ( null === $date ) { + return null; + } + return (int) $date->format( 'u' ); + } + + /** + * Method to emulate MySQL ADDTIME() function. + * + * Adds two time expressions. When the first expression holds a date, + * the result is a datetime; otherwise it is a TIME value, which may + * exceed 24 hours. TIME results clamp to +-838:59:59.999999. + * + * Returns NULL for NULL arguments or invalid input. + * + * @param string|null $expr1 A date, datetime, or time expression. + * @param string|null $expr2 A time expression to add. + * + * @return string|null The resulting time or datetime, or NULL. + */ + public function addtime( $expr1, $expr2 ) { + return $this->add_sub_time( $expr1, $expr2, 1 ); + } + + /** + * Method to emulate MySQL SUBTIME() function. + * + * Subtracts the second time expression from the first. Behaves like + * ADDTIME() otherwise. + * + * Returns NULL for NULL arguments or invalid input. + * + * @param string|null $expr1 A date, datetime, or time expression. + * @param string|null $expr2 A time expression to subtract. + * + * @return string|null The resulting time or datetime, or NULL. + */ + public function subtime( $expr1, $expr2 ) { + return $this->add_sub_time( $expr1, $expr2, -1 ); + } + + /** + * Method to emulate MySQL GET_FORMAT() function. + * + * Returns a DATE_FORMAT() format string for a type and locale pair, + * using MySQL's static mapping, e.g. GET_FORMAT(DATE, 'USA') is + * '%m.%d.%Y'. Both arguments are case-insensitive. + * + * Returns NULL for NULL arguments or unknown types or names. + * + * @param string|null $type One of DATE, TIME, or DATETIME. + * @param string|null $name One of EUR, USA, JIS, ISO, or INTERNAL. + * + * @return string|null The format string, or NULL. + */ + public function get_format( $type, $name ) { + if ( null === $type || null === $name ) { + return null; + } + $formats = array( + 'DATE' => array( + 'EUR' => '%d.%m.%Y', + 'USA' => '%m.%d.%Y', + 'JIS' => '%Y-%m-%d', + 'ISO' => '%Y-%m-%d', + 'INTERNAL' => '%Y%m%d', + ), + 'DATETIME' => array( + 'EUR' => '%Y-%m-%d %H.%i.%s', + 'USA' => '%Y-%m-%d %H.%i.%s', + 'JIS' => '%Y-%m-%d %H:%i:%s', + 'ISO' => '%Y-%m-%d %H:%i:%s', + 'INTERNAL' => '%Y%m%d%H%i%s', + ), + 'TIME' => array( + 'EUR' => '%H.%i.%s', + 'USA' => '%h:%i:%s %p', + 'JIS' => '%H:%i:%s', + 'ISO' => '%H:%i:%s', + 'INTERNAL' => '%H%i%s', + ), + ); + $type = strtoupper( trim( (string) $type ) ); + $name = strtoupper( trim( (string) $name ) ); + if ( ! isset( $formats[ $type ] ) || ! isset( $formats[ $type ][ $name ] ) ) { + return null; + } + return $formats[ $type ][ $name ]; + } + + /** + * Method to emulate MySQL TIME_FORMAT() function. + * + * Formats a time value using the same specifiers as DATE_FORMAT(). + * The standard path delegates to the dateformat() method. Times with + * hours past 23 or negative times take a fallback path that formats + * the same specifiers with unbounded hours. %f is the microseconds + * part, zero-padded to 6 digits. + * + * Returns NULL for NULL arguments or invalid input. + * + * @param string|null $time A time or datetime. + * @param string|null $format The format string. + * + * @return string|null The formatted time, or NULL. + */ + public function time_format( $time, $format ) { + if ( null === $time || null === $format ) { + return null; + } + $micros = $this->parse_mysql_time_interval( $time ); + $micro = 0; + if ( null !== $micros ) { + $sign = ( $micros < 0 ) ? -1 : 1; + $abs = (int) abs( $micros ); + $hour = (int) intdiv( $abs, 3600000000 ); + $rest = (int) ( $abs - $hour * 3600000000 ); + if ( $hour > 23 || $sign < 0 ) { + return $this->format_time_fallback( + $sign * $hour, + (int) intdiv( $rest, 60000000 ), + (int) ( ( $rest - (int) intdiv( $rest, 60000000 ) * 60000000 ) / 1000000 ), + (int) ( $rest % 1000000 ), + $format + ); + } + $micro = (int) ( $rest % 1000000 ); + $date = $this->parse_mysql_datetime( + sprintf( + '%02d:%02d:%02d.%06d', + $hour, + (int) intdiv( $rest, 60000000 ), + (int) ( ( $rest - (int) intdiv( $rest, 60000000 ) * 60000000 ) / 1000000 ), + $micro + ) + ); + } else { + $date = $this->parse_mysql_datetime( $time ); + } + if ( null === $date ) { + return null; + } + return $this->dateformat( + $this->format_mysql_datetime( $date ), + $this->substitute_microseconds( $format, (int) $date->format( 'u' ) ) + ); + } + + /** + * Method to emulate MySQL STR_TO_DATE() function. + * + * Parses a string using a format with a documented subset of MySQL + * specifiers: %Y %y %m %c %d %e %H %k %h %I %l %i %S %s %p %M %b %W + * %a %T %r (plus %% for a literal percent). %T and %r expand to their + * component specifiers. Month and weekday names match in English, + * case-insensitively. Two-digit years convert as 00 to 69 becoming + * 2000 to 2069 and 70 to 99 becoming 1970 to 1999. The year, month, + * and day must all be present; anything else returns NULL. + * + * Returns NULL for NULL arguments, unsupported specifiers, or values + * that do not match the format exactly. + * + * @param string|null $str The string to parse. + * @param string|null $format The format string. + * + * @return string|null The datetime formatted as 'Y-m-d H:i:s', or NULL. + */ + public function str_to_date( $str, $format ) { + if ( null === $str || null === $format ) { + return null; + } + if ( is_int( $str ) || is_float( $str ) ) { + $str = (string) $str; + } + if ( ! is_string( $str ) || ! is_string( $format ) ) { + return null; + } + + // %T and %r are shorthands for their component specifiers. + $format = str_replace( '%T', '%H:%i:%s', $format ); + $format = str_replace( '%r', '%h:%i:%s %p', $format ); + + $month_names = 'january|february|march|april|may|june|july|august|september|october|november|december|jan|feb|mar|apr|may|jun|jul|aug|sept|sep|oct|nov|dec'; + $weekday_names = 'monday|tuesday|wednesday|thursday|friday|saturday|sunday|mon|tue|wed|thu|fri|sat|sun'; + $specifiers = array( + '%Y' => '(\d{1,4})', + '%y' => '(\d{1,2})', + '%m' => '(\d{1,2})', + '%c' => '(\d{1,2})', + '%d' => '(\d{1,2})', + '%e' => '(\d{1,2})', + '%H' => '(\d{1,2})', + '%k' => '(\d{1,2})', + '%h' => '(\d{1,2})', + '%I' => '(\d{1,2})', + '%l' => '(\d{1,2})', + '%i' => '(\d{1,2})', + '%S' => '(\d{1,2})', + '%s' => '(\d{1,2})', + '%p' => '(?i:(AM|PM))', + '%M' => '(?i:(' . $month_names . '))', + '%b' => '(?i:(' . $month_names . '))', + '%W' => '(?i:(' . $weekday_names . '))', + '%a' => '(?i:(' . $weekday_names . '))', + ); + + $regex = ''; + $order = array(); + $len = strlen( $format ); + for ( $i = 0; $i < $len; $i++ ) { + $char = $format[ $i ]; + if ( '%' !== $char ) { + $regex .= preg_quote( $char, '/' ); + continue; + } + if ( $i + 1 >= $len ) { + return null; + } + $spec = '%' . $format[ $i + 1 ]; + ++$i; + if ( '%%' === $spec ) { + $regex .= '%'; + continue; + } + if ( ! isset( $specifiers[ $spec ] ) ) { + return null; + } + $regex .= $specifiers[ $spec ]; + $order[] = $spec; + } + + if ( 1 !== preg_match( '/^' . $regex . '$/', $str, $matches ) ) { + return null; + } + + $values = array(); + foreach ( $order as $index => $spec ) { + // Duplicate specifiers keep the last value, like MySQL. + $values[ $spec ] = $matches[ $index + 1 ]; + } + + if ( isset( $values['%Y'] ) ) { + $year = (int) $values['%Y']; + } elseif ( isset( $values['%y'] ) ) { + $yy = (int) $values['%y']; + $year = ( $yy < 70 ) ? ( 2000 + $yy ) : ( 1900 + $yy ); + } else { + return null; + } + + if ( isset( $values['%m'] ) || isset( $values['%c'] ) ) { + $month = (int) ( isset( $values['%m'] ) ? $values['%m'] : $values['%c'] ); + } elseif ( isset( $values['%M'] ) || isset( $values['%b'] ) ) { + $month = $this->month_name_to_number( isset( $values['%M'] ) ? $values['%M'] : $values['%b'] ); + if ( null === $month ) { + return null; + } + } else { + return null; + } + + if ( isset( $values['%d'] ) || isset( $values['%e'] ) ) { + $day = (int) ( isset( $values['%d'] ) ? $values['%d'] : $values['%e'] ); + } else { + return null; + } + + if ( $year < 0 || $year > 9999 || $month < 1 || $month > 12 || $day < 1 || $day > $this->days_in_month( $year, $month ) ) { + return null; + } + + if ( isset( $values['%H'] ) || isset( $values['%k'] ) ) { + $hour = (int) ( isset( $values['%H'] ) ? $values['%H'] : $values['%k'] ); + if ( $hour < 0 || $hour > 23 ) { + return null; + } + } elseif ( isset( $values['%h'] ) || isset( $values['%I'] ) || isset( $values['%l'] ) ) { + if ( isset( $values['%h'] ) ) { + $hour = (int) $values['%h']; + } elseif ( isset( $values['%I'] ) ) { + $hour = (int) $values['%I']; + } else { + $hour = (int) $values['%l']; + } + if ( $hour < 1 || $hour > 12 ) { + return null; + } + } else { + $hour = 0; + } + + $minute = isset( $values['%i'] ) ? (int) $values['%i'] : 0; + $second = 0; + if ( isset( $values['%S'] ) ) { + $second = (int) $values['%S']; + } elseif ( isset( $values['%s'] ) ) { + $second = (int) $values['%s']; + } + if ( $minute < 0 || $minute > 59 || $second < 0 || $second > 59 ) { + return null; + } + + if ( isset( $values['%p'] ) ) { + $is_pm = ( 0 === strcasecmp( $values['%p'], 'PM' ) ); + if ( $is_pm && $hour < 12 ) { + $hour += 12; + } elseif ( ! $is_pm && 12 === $hour ) { + $hour = 0; + } + } + + /* + * MySQL picks the result type from the format: a format with only + * date specifiers yields a DATE, one with time parts yields a + * DATETIME. The distinction matters because SQLite compares these + * values as text. + */ + $time_specs = array( '%H', '%k', '%h', '%I', '%l', '%i', '%S', '%s', '%p', '%r', '%T' ); + if ( 0 === count( array_intersect( $order, $time_specs ) ) ) { + return sprintf( '%04d-%02d-%02d', $year, $month, $day ); + } + return sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $year, $month, $day, $hour, $minute, $second ); + } + + /** + * Normalize a TIMESTAMPDIFF() or TIMESTAMPADD() unit. + * + * Uppercases the unit, strips an ODBC SQL_TSI_ prefix, maps the + * FRAC_SECOND synonym to MICROSECOND, and rejects anything else. + * + * @param mixed $unit The raw unit value. + * + * @return string|null The normalized unit, or NULL. + */ + private function normalize_timestamp_unit( $unit ) { + if ( ! is_string( $unit ) ) { + return null; + } + $unit = strtoupper( trim( $unit ) ); + if ( 0 === strpos( $unit, 'SQL_TSI_' ) ) { + $unit = substr( $unit, 8 ); + } + if ( 'FRAC_SECOND' === $unit ) { + return 'MICROSECOND'; + } + $valid = array( 'MICROSECOND', 'SECOND', 'MINUTE', 'HOUR', 'DAY', 'WEEK', 'MONTH', 'QUARTER', 'YEAR' ); + if ( ! in_array( $unit, $valid, true ) ) { + return null; + } + return $unit; + } + + /** + * Normalize a WEEK() or YEARWEEK() mode argument. + * + * @param mixed $mode The raw mode value. + * + * @return int|null The mode from 0 to 7, or NULL. + */ + private function normalize_week_mode( $mode ) { + if ( null === $mode || ! is_numeric( $mode ) ) { + return null; + } + $mode = (int) $mode; + if ( $mode < 0 || $mode > 7 ) { + return null; + } + return $mode; + } + + /** + * Whether a value carries a date part (as opposed to a time only). + * + * @param mixed $value The value to inspect. + * + * @return bool True when the value includes a year, month, and day. + */ + private function mysql_value_has_date( $value ) { + if ( is_int( $value ) || is_float( $value ) ) { + $value = (string) $value; + } + if ( ! is_string( $value ) ) { + return false; + } + $value = trim( $value ); + return ( + 1 === preg_match( '/^\d{4}-\d{1,2}-\d{1,2}/', $value ) || + 1 === preg_match( '/^\d{2}-\d{1,2}-\d{1,2}/', $value ) || + 1 === preg_match( '/^\d{6}(\d{6})?$/', $value ) || + 1 === preg_match( '/^(\d{8}|\d{14})$/', $value ) + ); + } + + /** + * Parse a MySQL date, datetime, or time value into a UTC DateTime. + * + * Accepts 'YYYY-MM-DD', 'YYYY-MM-DD HH:MM:SS' with an optional + * fractional part and 'T' separator, 'HH:MM:SS' with an optional + * fractional part, and the compact numeric forms YYYYMMDD, + * YYMMDD, YYYYMMDDHHMMSS, and YYMMDDHHMMSS. Two-digit years convert + * as 00 to 69 becoming 2000 to 2069 and 70 to 99 becoming 1970 to + * 1999. Time-only values anchor to 1970-01-01. Zero month or day + * parts are rejected, while year 0 is accepted for the day-number + * functions. All parsing anchors to UTC so results never depend on + * PHP's default time zone. + * + * @param mixed $value The value to parse. + * + * @return DateTime|null The parsed datetime in UTC, or NULL. + */ + private function parse_mysql_datetime( $value ) { + if ( null === $value ) { + return null; + } + if ( is_int( $value ) || is_float( $value ) ) { + $value = (string) $value; + } + if ( ! is_string( $value ) ) { + return null; + } + $value = trim( $value ); + if ( '' === $value ) { + return null; + } + + $year = null; + $month = null; + $day = null; + $hour = 0; + $minute = 0; + $second = 0; + $micro = 0; + + if ( 1 === preg_match( '/^(\d{4})-(\d{1,2})-(\d{1,2})(?:[ T](\d{1,2}):(\d{1,2}):(\d{1,2})(\.\d{1,6})?)?$/', $value, $m ) ) { + $year = (int) $m[1]; + $month = (int) $m[2]; + $day = (int) $m[3]; + if ( isset( $m[4] ) && '' !== $m[4] ) { + $hour = (int) $m[4]; + $minute = (int) $m[5]; + $second = (int) $m[6]; + if ( isset( $m[7] ) && '' !== $m[7] ) { + $micro = (int) str_pad( substr( $m[7], 1 ), 6, '0' ); + } + } + } elseif ( 1 === preg_match( '/^(\d{2})-(\d{1,2})-(\d{1,2})(?:[ T](\d{1,2}):(\d{1,2}):(\d{1,2})(\.\d{1,6})?)?$/', $value, $m ) ) { + $yy = (int) $m[1]; + $year = ( $yy < 70 ) ? ( 2000 + $yy ) : ( 1900 + $yy ); + $month = (int) $m[2]; + $day = (int) $m[3]; + if ( isset( $m[4] ) && '' !== $m[4] ) { + $hour = (int) $m[4]; + $minute = (int) $m[5]; + $second = (int) $m[6]; + if ( isset( $m[7] ) && '' !== $m[7] ) { + $micro = (int) str_pad( substr( $m[7], 1 ), 6, '0' ); + } + } + } elseif ( 1 === preg_match( '/^(\d{4})(\d{2})(\d{2})(?:(\d{2})(\d{2})(\d{2})(\.\d{1,6})?)?$/', $value, $m ) ) { + $year = (int) $m[1]; + $month = (int) $m[2]; + $day = (int) $m[3]; + if ( isset( $m[4] ) && '' !== $m[4] ) { + $hour = (int) $m[4]; + $minute = (int) $m[5]; + $second = (int) $m[6]; + if ( isset( $m[7] ) && '' !== $m[7] ) { + $micro = (int) str_pad( substr( $m[7], 1 ), 6, '0' ); + } + } + } elseif ( 1 === preg_match( '/^(\d{2})(\d{2})(\d{2})(?:(\d{2})(\d{2})(\d{2})(\.\d{1,6})?)?$/', $value, $m ) ) { + $yy = (int) $m[1]; + $year = ( $yy < 70 ) ? ( 2000 + $yy ) : ( 1900 + $yy ); + $month = (int) $m[2]; + $day = (int) $m[3]; + if ( isset( $m[4] ) && '' !== $m[4] ) { + $hour = (int) $m[4]; + $minute = (int) $m[5]; + $second = (int) $m[6]; + if ( isset( $m[7] ) && '' !== $m[7] ) { + $micro = (int) str_pad( substr( $m[7], 1 ), 6, '0' ); + } + } + } elseif ( 1 === preg_match( '/^(\d{1,2}):(\d{1,2}):(\d{1,2})(\.\d{1,6})?$/', $value, $m ) ) { + $year = 1970; + $month = 1; + $day = 1; + $hour = (int) $m[1]; + $minute = (int) $m[2]; + $second = (int) $m[3]; + if ( isset( $m[4] ) && '' !== $m[4] ) { + $micro = (int) str_pad( substr( $m[4], 1 ), 6, '0' ); + } + } elseif ( 1 === preg_match( '/^(\d{1,2}):(\d{1,2})$/', $value, $m ) ) { + $year = 1970; + $month = 1; + $day = 1; + $hour = (int) $m[1]; + $minute = (int) $m[2]; + } else { + return null; + } + + if ( $year < 0 || $year > 9999 || $month < 1 || $month > 12 || $day < 1 || $day > $this->days_in_month( $year, $month ) ) { + return null; + } + if ( $hour < 0 || $hour > 23 || $minute < 0 || $minute > 59 || $second < 0 || $second > 59 || $micro < 0 || $micro > 999999 ) { + return null; + } + + try { + $date = new DateTime( 'now', new DateTimeZone( 'UTC' ) ); + $date->setDate( $year, $month, $day ); + $date->setTime( $hour, $minute, $second, $micro ); + } catch ( Exception $e ) { + return null; + } + return $date; + } + + /** + * Parse a MySQL time interval into total microseconds. + * + * Accepts an optional sign with 'HH:MM:SS', 'MM:SS', or a bare digit + * string read right-to-left as SS, MMSS, or HHMMSS, each with an + * optional fractional part. Hours are unbounded so values past 24 + * hours parse, and minute and second parts must stay below 60. + * + * @param mixed $value The value to parse. + * + * @return int|null The signed total microseconds, or NULL. + */ + private function parse_mysql_time_interval( $value ) { + if ( null === $value ) { + return null; + } + if ( is_int( $value ) || is_float( $value ) ) { + $value = (string) $value; + } + if ( ! is_string( $value ) ) { + return null; + } + $value = trim( $value ); + if ( '' === $value ) { + return null; + } + + $sign = 1; + if ( '-' === $value[0] ) { + $sign = -1; + $value = trim( substr( $value, 1 ) ); + } elseif ( '+' === $value[0] ) { + $value = trim( substr( $value, 1 ) ); + } + if ( '' === $value ) { + return null; + } + + $hour = 0; + $minute = 0; + $second = 0; + $micro = 0; + + if ( 1 === preg_match( '/^(\d+):(\d{1,2}):(\d{1,2})(\.\d{1,6})?$/', $value, $m ) ) { + $hour = (int) $m[1]; + $minute = (int) $m[2]; + $second = (int) $m[3]; + if ( isset( $m[4] ) && '' !== $m[4] ) { + $micro = (int) str_pad( substr( $m[4], 1 ), 6, '0' ); + } + } elseif ( 1 === preg_match( '/^(\d{1,2}):(\d{1,2})(\.\d{1,6})?$/', $value, $m ) ) { + $minute = (int) $m[1]; + $second = (int) $m[2]; + if ( isset( $m[3] ) && '' !== $m[3] ) { + $micro = (int) str_pad( substr( $m[3], 1 ), 6, '0' ); + } + } elseif ( 1 === preg_match( '/^(\d+)(\.\d{1,6})?$/', $value, $m ) ) { + $digits = $m[1]; + $len = strlen( $digits ); + if ( $len > 2 ) { + $second = (int) substr( $digits, -2 ); + $digits = substr( $digits, 0, $len - 2 ); + } else { + $second = (int) $digits; + $digits = ''; + } + if ( '' !== $digits ) { + $len = strlen( $digits ); + if ( $len > 2 ) { + $minute = (int) substr( $digits, -2 ); + $digits = substr( $digits, 0, $len - 2 ); + } else { + $minute = (int) $digits; + $digits = ''; + } + } + if ( '' !== $digits ) { + $hour = (int) $digits; + } + if ( isset( $m[2] ) && '' !== $m[2] ) { + $micro = (int) str_pad( substr( $m[2], 1 ), 6, '0' ); + } + } else { + return null; + } + + if ( $minute < 0 || $minute > 59 || $second < 0 || $second > 59 || $micro < 0 || $micro > 999999 ) { + return null; + } + return (int) ( $sign * ( ( $hour * 3600 + $minute * 60 + $second ) * 1000000 + $micro ) ); + } + + /** + * The number of days in a month under the proleptic Gregorian calendar. + * + * @param int $year The year, 0 to 9999. + * @param int $month The month, 1 to 12. + * + * @return int The number of days. + */ + private function days_in_month( $year, $month ) { + $lengths = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ); + if ( 2 !== $month ) { + return $lengths[ $month - 1 ]; + } + $is_leap = ( 0 === $year % 4 && 0 !== $year % 100 ) || 0 === $year % 400; + return $is_leap ? 29 : 28; + } + + /** + * Days since 1970-01-01 under the proleptic Gregorian calendar. + * + * Implements Howard Hinnant's days_from_civil algorithm. + * + * @param int $y The year. + * @param int $m The month, 1 to 12. + * @param int $d The day of the month. + * + * @return int The day count, negative before 1970-01-01. + */ + private function days_from_civil( $y, $m, $d ) { + $y -= ( $m <= 2 ) ? 1 : 0; + $era = (int) floor( $y / 400 ); + $yoe = (int) ( $y - $era * 400 ); + $mp = ( $m > 2 ) ? ( $m - 3 ) : ( $m + 9 ); + $doy = (int) floor( ( 153 * $mp + 2 ) / 5 ) + $d - 1; + $doe = (int) ( $yoe * 365 + floor( $yoe / 4 ) - floor( $yoe / 100 ) + $doy ); + return (int) ( $era * 146097 + $doe - 719468 ); + } + + /** + * The inverse of days_from_civil(): civil date for a day count. + * + * Implements Howard Hinnant's civil_from_days algorithm. + * + * @param int $z Days since 1970-01-01. + * + * @return array The year, month, and day as array( $y, $m, $d ). + */ + private function civil_from_days( $z ) { + $z = (int) ( $z + 719468 ); + $era = (int) floor( $z / 146097 ); + $doe = (int) ( $z - $era * 146097 ); + $yoe = (int) floor( ( $doe - floor( $doe / 1460 ) + floor( $doe / 36524 ) - floor( $doe / 146096 ) ) / 365 ); + $y = (int) ( $yoe + $era * 400 ); + $doy = (int) ( $doe - ( 365 * $yoe + floor( $yoe / 4 ) - floor( $yoe / 100 ) ) ); + $mp = (int) floor( ( 5 * $doy + 2 ) / 153 ); + $d = (int) ( $doy - floor( ( 153 * $mp + 2 ) / 5 ) + 1 ); + $m = ( $mp < 10 ) ? ( $mp + 3 ) : ( $mp - 9 ); + $y += ( $m <= 2 ) ? 1 : 0; + return array( $y, $m, $d ); + } + + /** + * Add whole months to a datetime with end-of-month clamping. + * + * Matches MySQL: adding one month to January 31st yields the last day + * of February, not March 3rd as PHP's DateTime::modify() would. + * + * @param DateTime $date The datetime, modified in place on a clone. + * @param int $months The signed number of months to add. + * + * @return DateTime|null The shifted datetime, or NULL when out of range. + */ + private function add_months_clamped( DateTime $date, $months ) { + $result = clone $date; + $year = (int) $result->format( 'Y' ); + $month = (int) $result->format( 'n' ); + $day = (int) $result->format( 'j' ); + $total = (int) ( $year * 12 + ( $month - 1 ) + $months ); + $y = (int) floor( $total / 12 ); + $m = (int) ( $total - $y * 12 + 1 ); + if ( $y < 0 || $y > 9999 ) { + return null; + } + $result->setDate( $y, $m, $day < $this->days_in_month( $y, $m ) ? $day : $this->days_in_month( $y, $m ) ); + return $result; + } + + /** + * Add microseconds to a datetime with exact integer math. + * + * @param DateTime $date The datetime to shift. + * @param int $micros The signed microseconds to add. + * + * @return DateTime|null The shifted datetime, or NULL when out of range. + */ + private function add_microseconds( DateTime $date, $micros ) { + $result = clone $date; + /* + * setTimestamp() discards fractional seconds, so carry the source + * fraction across explicitly and fold it into the added remainder. + */ + $source_micros = (int) $result->format( 'u' ); + $seconds = (int) intdiv( $micros, 1000000 ); + $rem = (int) ( $micros - $seconds * 1000000 ); + if ( $rem < 0 ) { + $seconds -= 1; + $rem += 1000000; + } + $total_micros = $source_micros + $rem; + if ( $total_micros >= 1000000 ) { + $total_micros -= 1000000; + ++$seconds; + } + $result->setTimestamp( (int) $result->format( 'U' ) + $seconds ); + if ( 0 !== $total_micros ) { + $result->modify( sprintf( '+%d microseconds', $total_micros ) ); + } + $year = (int) $result->format( 'Y' ); + if ( $year < 0 || $year > 9999 ) { + return null; + } + return $result; + } + + /** + * The exact difference of two UTC datetimes in microseconds. + * + * @param DateTime $date1 The datetime to subtract. + * @param DateTime $date2 The datetime to subtract from. + * + * @return int The signed difference in microseconds. + */ + private function datetime_diff_microseconds( DateTime $date1, DateTime $date2 ) { + $seconds = (int) $date2->format( 'U' ) - (int) $date1->format( 'U' ); + $micro = (int) $date2->format( 'u' ) - (int) $date1->format( 'u' ); + return (int) ( $seconds * 1000000 + $micro ); + } + + /** + * The difference of the date parts of two datetimes, in days. + * + * Time-of-day parts are ignored, matching MySQL's DAY and WEEK units. + * + * @param DateTime $date1 The datetime to subtract. + * @param DateTime $date2 The datetime to subtract from. + * + * @return int The signed difference in days. + */ + private function date_diff_days( DateTime $date1, DateTime $date2 ) { + return (int) ( + $this->days_from_civil( (int) $date2->format( 'Y' ), (int) $date2->format( 'n' ), (int) $date2->format( 'j' ) ) - + $this->days_from_civil( (int) $date1->format( 'Y' ), (int) $date1->format( 'n' ), (int) $date1->format( 'j' ) ) + ); + } + + /** + * The difference of two datetimes in complete months or quarters. + * + * Counts how many whole $per-month periods fit between the datetimes, + * truncating toward zero and clamping end-of-month starts like MySQL. + * + * @param DateTime $date1 The datetime to subtract. + * @param DateTime $date2 The datetime to subtract from. + * @param int $per The period length in months (1, 3, or 12). + * + * @return int The signed number of complete periods. + */ + private function datetime_diff_months( DateTime $date1, DateTime $date2, $per ) { + /* + * MySQL does not clamp end-of-month dates here: it orders the two + * values, takes the month difference, and drops one month when the + * later value's day-and-time part is behind the earlier one. That + * makes TIMESTAMPDIFF(MONTH, '2024-01-31', '2024-02-29') zero. + */ + if ( $date2 >= $date1 ) { + $earlier = $date1; + $later = $date2; + $sign = 1; + } else { + $earlier = $date2; + $later = $date1; + $sign = -1; + } + $months = ( (int) $later->format( 'Y' ) - (int) $earlier->format( 'Y' ) ) * 12 + + ( (int) $later->format( 'n' ) - (int) $earlier->format( 'n' ) ); + if ( $months > 0 && $later->format( 'dHisu' ) < $earlier->format( 'dHisu' ) ) { + --$months; + } + return (int) ( $sign * intdiv( $months, $per ) ); + } + + /** + * Convert a YYMM or YYYYMM period to absolute months. + * + * Two-digit years convert as 00 to 69 becoming 2000 to 2069 and 70 to + * 99 becoming 1970 to 1999. + * + * @param mixed $period The period value. + * + * @return array|null The total months and two-digit flag as array( $total, $two_digit ), or NULL. + */ + private function period_to_months( $period ) { + if ( null === $period || ! is_numeric( $period ) ) { + return null; + } + $period = (int) $period; + if ( $period < 0 ) { + return null; + } + $year = (int) intdiv( $period, 100 ); + $month = (int) ( $period - $year * 100 ); + if ( $month < 1 || $month > 12 ) { + return null; + } + $two_digit = ( $year < 100 ); + $full = $two_digit ? (int) ( $year + ( $year < 70 ? 2000 : 1900 ) ) : $year; + return array( (int) ( $full * 12 + ( $month - 1 ) ), $two_digit ); + } + + /** + * Add or subtract two time expressions shared by ADDTIME()/SUBTIME(). + * + * @param string|null $expr1 A date, datetime, or time expression. + * @param string|null $expr2 A time expression to add or subtract. + * @param int $sign 1 to add, -1 to subtract. + * + * @return string|null The resulting time or datetime, or NULL. + */ + private function add_sub_time( $expr1, $expr2, $sign ) { + if ( null === $expr1 || null === $expr2 ) { + return null; + } + $t2 = $this->parse_mysql_time_interval( $expr2 ); + if ( null === $t2 ) { + return null; + } + if ( $this->mysql_value_has_date( $expr1 ) ) { + $date = $this->parse_mysql_datetime( $expr1 ); + if ( null === $date ) { + return null; + } + $base = (int) $date->format( 'U' ) * 1000000 + (int) $date->format( 'u' ); + $result = $this->micros_to_datetime( $base + $sign * $t2 ); + if ( null === $result ) { + return null; + } + return $this->format_mysql_datetime( $result ); + } + $t1 = $this->parse_mysql_time_interval( $expr1 ); + if ( null === $t1 ) { + return null; + } + $result = (int) ( $t1 + $sign * $t2 ); + $limit = 3020399000000; + if ( $result > $limit ) { + $result = $limit; + } elseif ( $result < -$limit ) { + $result = -$limit; + } + return $this->format_mysql_time( $result ); + } + + /** + * Build a UTC datetime from total microseconds since the epoch. + * + * @param int $micros Microseconds since 1970-01-01 00:00:00 UTC. + * + * @return DateTime|null The datetime, or NULL when out of range. + */ + private function micros_to_datetime( $micros ) { + $seconds = (int) intdiv( $micros, 1000000 ); + $rem = (int) ( $micros - $seconds * 1000000 ); + if ( $rem < 0 ) { + $seconds -= 1; + $rem += 1000000; + } + $date = new DateTime( '@0' ); + $date->setTimestamp( $seconds ); + if ( 0 !== $rem ) { + $date->modify( sprintf( '+%d microseconds', $rem ) ); + } + $year = (int) $date->format( 'Y' ); + if ( $year < 0 || $year > 9999 ) { + return null; + } + return $date; + } + + /** + * Format a UTC datetime as MySQL does, trimming zero fractions. + * + * @param DateTime $date The datetime in UTC. + * + * @return string The datetime formatted as 'Y-m-d H:i:s[.fraction]'. + */ + private function format_mysql_datetime( DateTime $date ) { + $out = $date->format( 'Y-m-d H:i:s' ); + $micro = (int) $date->format( 'u' ); + if ( 0 !== $micro ) { + $out .= '.' . rtrim( sprintf( '%06d', $micro ), '0' ); + } + return $out; + } + + /** + * Format total microseconds as a MySQL TIME value. + * + * Hours stay unpadded past two digits and a fractional part trims + * trailing zeros, e.g. 90061000000 becomes '25:01:01'. + * + * @param int $micros The signed total microseconds. + * + * @return string The time formatted as '[−]H:MM:SS[.fraction]'. + */ + private function format_mysql_time( $micros ) { + $sign = ( $micros < 0 ) ? '-' : ''; + $abs = (int) abs( $micros ); + $hour = (int) intdiv( $abs, 3600000000 ); + $rest = (int) ( $abs - $hour * 3600000000 ); + $minute = (int) intdiv( $rest, 60000000 ); + $second = (int) intdiv( $rest - $minute * 60000000, 1000000 ); + $out = sprintf( '%s%02d:%02d:%02d', $sign, $hour, $minute, $second ); + $micro = (int) ( $rest % 1000000 ); + if ( 0 !== $micro ) { + $out .= '.' . rtrim( sprintf( '%06d', $micro ), '0' ); + } + return $out; + } + + /** + * Return an integer in a form that survives PDO SQLite UDF marshaling. + * + * This PHP build truncates UDF integer arguments and return values to + * 32 bits, so values past the signed 32-bit range are returned as + * floats instead. Floats stay exact up to 2**53 and SQLite compares + * and computes with REALs numerically, so TO_SECONDS() dates past + * 2038 and wide TIMESTAMPDIFF() ranges keep working. + * + * @param int|float $n The value to return. + * + * @return int|float The value as an int when it fits, else a float. + */ + private function sqlite_safe_int( $n ) { + if ( $n > 2147483647 || $n < -2147483648 ) { + return (float) $n; + } + return (int) $n; + } + + /** + * Substitute a microseconds value for %f in a format string. + * + * The dateformat() method has no %f specifier, so TIME_FORMAT() + * replaces it with the zero-padded 6-digit value up front. + * + * @param string $format The format string. + * @param int $micro The microseconds, 0 to 999999. + * + * @return string The format string with %f substituted. + */ + private function substitute_microseconds( $format, $micro ) { + if ( false === strpos( $format, '%f' ) ) { + return $format; + } + return str_replace( '%f', sprintf( '%06d', $micro ), $format ); + } + + /** + * Format out-of-range hours for TIME_FORMAT() without delegating. + * + * Handles times with hours past 23 or negative times, which the + * DATETIME-based dateformat() path cannot represent. Supports the + * same time specifiers dateformat() supports, with unbounded %H and + * %k, 12-hour clocks derived from the hour modulo 24, and %f as the + * zero-padded 6-digit microseconds. + * + * @param int $hour The signed total hours. + * @param int $minute The minutes, 0 to 59. + * @param int $second The seconds, 0 to 59. + * @param int $micro The microseconds, 0 to 999999. + * @param string $format The format string. + * + * @return string The formatted time. + */ + private function format_time_fallback( $hour, $minute, $second, $micro, $format ) { + $sign = ( $hour < 0 ) ? '-' : ''; + $abs = (int) abs( $hour ); + $h24 = (int) ( ( $hour % 24 + 24 ) % 24 ); + $h12 = (int) ( $h24 % 12 ); + if ( 0 === $h12 ) { + $h12 = 12; + } + $replacements = array( + '%H' => sprintf( '%s%02d', $sign, $abs ), + '%k' => sprintf( '%s%d', $sign, $abs ), + '%h' => sprintf( '%02d', $h12 ), + '%I' => sprintf( '%02d', $h12 ), + '%l' => sprintf( '%d', $h12 ), + '%i' => sprintf( '%02d', $minute ), + '%S' => sprintf( '%02d', $second ), + '%s' => sprintf( '%02d', $second ), + '%f' => sprintf( '%06d', $micro ), + '%p' => ( $h24 < 12 ) ? 'AM' : 'PM', + '%T' => sprintf( '%s%02d:%02d:%02d', $sign, $abs, $minute, $second ), + '%r' => sprintf( '%02d:%02d:%02d %s', $h12, $minute, $second, ( $h24 < 12 ) ? 'AM' : 'PM' ), + ); + return strtr( $format, $replacements ); + } + + /** + * Convert an English month name to its number. + * + * Accepts full and abbreviated names, case-insensitively. + * + * @param string $name The month name. + * + * @return int|null The month number, 1 to 12, or NULL. + */ + private function month_name_to_number( $name ) { + $months = array( + 'january' => 1, + 'february' => 2, + 'march' => 3, + 'april' => 4, + 'may' => 5, + 'june' => 6, + 'july' => 7, + 'august' => 8, + 'september' => 9, + 'october' => 10, + 'november' => 11, + 'december' => 12, + 'jan' => 1, + 'feb' => 2, + 'mar' => 3, + 'apr' => 4, + 'jun' => 6, + 'jul' => 7, + 'aug' => 8, + 'sep' => 9, + 'sept' => 9, + 'oct' => 10, + 'nov' => 11, + 'dec' => 12, + ); + $key = strtolower( trim( $name ) ); + if ( ! isset( $months[ $key ] ) ) { + return null; + } + return $months[ $key ]; + } + /** * A helper to convert a LIKE pattern to a GLOB pattern for "LIKE BINARY" support. diff --git a/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php b/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php index fff5bc6b5..b000a97a9 100644 --- a/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php +++ b/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php @@ -1066,6 +1066,1122 @@ public function testDateAddFunctionWithNegativeAndComputedIntervals() { $this->assertEquals( '2024-01-08 10:00:00', $result[0]->output ); } + public function testAddDateSubDateFunctions() { + // Expected values were taken from MySQL 8.4. + // Three-argument INTERVAL form behaves like DATE_ADD/DATE_SUB. + $result = $this->assertQuery( + "SELECT ADDDATE('2024-01-01', INTERVAL 1 DAY) as output" + ); + $this->assertEquals( '2024-01-02', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT SUBDATE('2024-01-05 10:00:00', INTERVAL 1 DAY) as output" + ); + $this->assertEquals( '2024-01-04 10:00:00', $result[0]->output ); + + // Two-argument form adds or subtracts a number of days. + $result = $this->assertQuery( + "SELECT ADDDATE('2024-01-01', 1) as output" + ); + $this->assertEquals( '2024-01-02', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT SUBDATE('2024-01-05', 2) as output" + ); + $this->assertEquals( '2024-01-03', $result[0]->output ); + + // A datetime input stays a datetime, a date input stays a date. + $result = $this->assertQuery( + "SELECT ADDDATE('2024-01-01 10:00:00', 1) as output" + ); + $this->assertEquals( '2024-01-02 10:00:00', $result[0]->output ); + + // Negative day counts work in both directions. + $result = $this->assertQuery( + "SELECT ADDDATE('2024-01-01', -1) as output" + ); + $this->assertEquals( '2023-12-31', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT SUBDATE('2024-01-01', -1) as output" + ); + $this->assertEquals( '2024-01-02', $result[0]->output ); + + // NULL on either side yields NULL. + $result = $this->assertQuery( 'SELECT ADDDATE(NULL, 1) as output' ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + "SELECT ADDDATE('2024-01-01', NULL) as output" + ); + $this->assertNull( $result[0]->output ); + + // Invalid dates yield NULL. + $result = $this->assertQuery( + "SELECT ADDDATE('not a date', 1) as output" + ); + $this->assertNull( $result[0]->output ); + } + + public function testCurrentDateAndCurrentTime() { + // The parenthesized forms agree with CURDATE() and CURTIME(). + $result = $this->assertQuery( 'SELECT CURRENT_DATE() = CURDATE() as output' ); + $this->assertEquals( 1, $result[0]->output ); + + $result = $this->assertQuery( 'SELECT CURRENT_TIME() = CURTIME() as output' ); + $this->assertEquals( 1, $result[0]->output ); + + // The bare keywords work as well, in any letter casing. + $result = $this->assertQuery( 'SELECT CURRENT_DATE = CURDATE() as output' ); + $this->assertEquals( 1, $result[0]->output ); + + $result = $this->assertQuery( 'SELECT CURRENT_TIME = CURTIME() as output' ); + $this->assertEquals( 1, $result[0]->output ); + + $result = $this->assertQuery( 'SELECT current_date() = curdate() as output' ); + $this->assertEquals( 1, $result[0]->output ); + + // Both forms produce well-formed values. + $result = $this->assertQuery( "SELECT CURRENT_DATE LIKE '____-__-__' as output" ); + $this->assertEquals( 1, $result[0]->output ); + + $result = $this->assertQuery( "SELECT CURTIME() LIKE '__:__:__' as output" ); + $this->assertEquals( 1, $result[0]->output ); + + // An explicitly quoted `current_date` is still a column reference. + $this->assertQuery( 'CREATE TABLE _events (id INT, `current_date` TEXT)' ); + $this->assertQuery( "INSERT INTO _events VALUES (1, 'hello')" ); + $result = $this->assertQuery( 'SELECT `current_date` as output FROM _events' ); + $this->assertEquals( 'hello', $result[0]->output ); + } + + public function testTimestampDiffFunction() { + // Expected values were taken from MySQL 8.4. + // The learnomy migration use: whole days in seconds (24 * 3600). + $result = $this->assertQuery( + "SELECT TIMESTAMPDIFF(SECOND, '2024-01-01 00:00:00', '2024-01-02 00:00:00') as output" + ); + $this->assertEquals( 86400, $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIMESTAMPDIFF(MINUTE, '2024-01-01 00:00:00', '2024-01-01 01:30:00') as output" + ); + $this->assertEquals( 90, $result[0]->output ); + + // DAY counts calendar days, HOUR counts exact hours: the two + // datetimes below are 2 hours apart but on different days. + $result = $this->assertQuery( + "SELECT TIMESTAMPDIFF(DAY, '2024-01-01 23:00:00', '2024-01-02 01:00:00') as output" + ); + $this->assertEquals( 1, $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIMESTAMPDIFF(HOUR, '2024-01-01 23:00:00', '2024-01-02 01:00:00') as output" + ); + $this->assertEquals( 2, $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIMESTAMPDIFF(WEEK, '2024-01-01', '2024-01-08') as output" + ); + $this->assertEquals( 1, $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIMESTAMPDIFF(MICROSECOND, '2024-01-01 00:00:00', '2024-01-01 00:00:01') as output" + ); + $this->assertEquals( 1000000, $result[0]->output ); + + // FRAC_SECOND is a synonym of MICROSECOND. + $result = $this->assertQuery( + "SELECT TIMESTAMPDIFF(FRAC_SECOND, '2024-01-01 00:00:00', '2024-01-01 00:00:01') as output" + ); + $this->assertEquals( 1000000, $result[0]->output ); + + // The ODBC SQL_TSI_ prefixed units work as well. + $result = $this->assertQuery( + "SELECT TIMESTAMPDIFF(SQL_TSI_DAY, '2024-01-01', '2024-01-03') as output" + ); + $this->assertEquals( 2, $result[0]->output ); + + // MONTH counts complete months without clamping end-of-month dates: + // Feb 29 is a day short of a month after Jan 31, so this is 0, as in + // MySQL. + $result = $this->assertQuery( + "SELECT TIMESTAMPDIFF(MONTH, '2024-01-31', '2024-02-29') as output" + ); + $this->assertEquals( 0, $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIMESTAMPDIFF(MONTH, '2024-01-31', '2024-02-28') as output" + ); + $this->assertEquals( 0, $result[0]->output ); + + // QUARTER counts complete 3-month periods. + $result = $this->assertQuery( + "SELECT TIMESTAMPDIFF(QUARTER, '2024-01-15', '2024-07-15') as output" + ); + $this->assertEquals( 2, $result[0]->output ); + + // YEAR counts complete years: Feb 29 plus 4 years clamps to + // Feb 29, which is past Feb 28, so only 3 complete years fit. + $result = $this->assertQuery( + "SELECT TIMESTAMPDIFF(YEAR, '2020-02-29', '2024-02-28') as output" + ); + $this->assertEquals( 3, $result[0]->output ); + + // Differences truncate toward zero: -5400 seconds is -1 hour. + $result = $this->assertQuery( + "SELECT TIMESTAMPDIFF(HOUR, '2024-01-01 01:30:00', '2024-01-01 00:00:00') as output" + ); + $this->assertEquals( -1, $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIMESTAMPDIFF(WEEK, '2024-01-08', '2024-01-01') as output" + ); + $this->assertEquals( -1, $result[0]->output ); + + // NULL on either side yields NULL. + $result = $this->assertQuery( + "SELECT TIMESTAMPDIFF(SECOND, NULL, '2024-01-02') as output" + ); + $this->assertNull( $result[0]->output ); + + // Unknown units and invalid datetimes yield NULL. + $result = $this->assertQuery( + "SELECT TIMESTAMPDIFF(BOGUS, '2024-01-01', '2024-01-02') as output" + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIMESTAMPDIFF(SECOND, 'not a date', '2024-01-02') as output" + ); + $this->assertNull( $result[0]->output ); + } + + public function testTimestampDiffAcrossDst() { + // Wall-clock differences ignore time zones: the driver parses in + // UTC, so the US spring forward on 2024-03-10 (47 elapsed hours + // in America/New_York) still reports the MySQL value of 48 hours. + $previous_timezone = date_default_timezone_get(); + // phpcs:ignore WordPress.DateTime.RestrictedFunctions.timezone_change_date_default_timezone_set -- Test needs a non-UTC PHP default timezone; restored in finally. + date_default_timezone_set( 'America/New_York' ); + try { + $result = $this->assertQuery( + "SELECT TIMESTAMPDIFF(HOUR, '2024-03-09 12:00:00', '2024-03-11 12:00:00') as output" + ); + $this->assertEquals( 48, $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIMESTAMPADD(HOUR, 48, '2024-03-09 12:00:00') as output" + ); + $this->assertEquals( '2024-03-11 12:00:00', $result[0]->output ); + } finally { + // phpcs:ignore WordPress.DateTime.RestrictedFunctions.timezone_change_date_default_timezone_set -- Restore the original default timezone. + date_default_timezone_set( $previous_timezone ); + } + } + + public function testTimestampAddFunction() { + // Expected values were taken from MySQL 8.4. + $result = $this->assertQuery( + "SELECT TIMESTAMPADD(SECOND, 90, '2024-01-01 00:00:00') as output" + ); + $this->assertEquals( '2024-01-01 00:01:30', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIMESTAMPADD(MINUTE, -90, '2024-01-01 01:00:00') as output" + ); + $this->assertEquals( '2023-12-31 23:30:00', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIMESTAMPADD(WEEK, 2, '2024-01-01') as output" + ); + $this->assertEquals( '2024-01-15 00:00:00', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIMESTAMPADD(DAY, -1, '2024-01-01') as output" + ); + $this->assertEquals( '2023-12-31 00:00:00', $result[0]->output ); + + // Month-based units clamp end-of-month starts like MySQL: + // Jan 31 plus one month is Feb 29 in the 2024 leap year. + $result = $this->assertQuery( + "SELECT TIMESTAMPADD(MONTH, 1, '2024-01-31') as output" + ); + $this->assertEquals( '2024-02-29 00:00:00', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIMESTAMPADD(QUARTER, 1, '2024-01-15') as output" + ); + $this->assertEquals( '2024-04-15 00:00:00', $result[0]->output ); + + // Feb 29 plus one year clamps to Feb 28 in non-leap 2025. + $result = $this->assertQuery( + "SELECT TIMESTAMPADD(YEAR, 1, '2024-02-29') as output" + ); + $this->assertEquals( '2025-02-28 00:00:00', $result[0]->output ); + + // Fractional month counts truncate toward zero. + $result = $this->assertQuery( + "SELECT TIMESTAMPADD(MONTH, 1.9, '2024-01-15') as output" + ); + $this->assertEquals( '2024-02-15 00:00:00', $result[0]->output ); + + // Sub-second results keep a trimmed fractional part. + $result = $this->assertQuery( + "SELECT TIMESTAMPADD(MICROSECOND, 1500000, '2024-01-01') as output" + ); + $this->assertEquals( '2024-01-01 00:00:01.5', $result[0]->output ); + + // Quoted units work as well as bare ones. + $result = $this->assertQuery( + "SELECT TIMESTAMPADD('SECOND', 1, '2024-01-01') as output" + ); + $this->assertEquals( '2024-01-01 00:00:01', $result[0]->output ); + + // NULL and invalid arguments yield NULL. + $result = $this->assertQuery( + "SELECT TIMESTAMPADD(SECOND, NULL, '2024-01-01') as output" + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIMESTAMPADD(BOGUS, 1, '2024-01-01') as output" + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIMESTAMPADD(SECOND, 'abc', '2024-01-01') as output" + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIMESTAMPADD(SECOND, 1, 'not a date') as output" + ); + $this->assertNull( $result[0]->output ); + } + + public function testTimestampFunction() { + // Expected values were taken from MySQL 8.4. + $result = $this->assertQuery( + "SELECT TIMESTAMP('2024-05-10') as output" + ); + $this->assertEquals( '2024-05-10 00:00:00', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIMESTAMP('2024-05-10 14:30:00') as output" + ); + $this->assertEquals( '2024-05-10 14:30:00', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIMESTAMP('2024-01-01', '02:00:00') as output" + ); + $this->assertEquals( '2024-01-01 02:00:00', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIMESTAMP('2024-01-01 10:00:00', '02:30:00') as output" + ); + $this->assertEquals( '2024-01-01 12:30:00', $result[0]->output ); + + // A time past 24 hours rolls into the next day. + $result = $this->assertQuery( + "SELECT TIMESTAMP('2024-01-01', '25:00:00') as output" + ); + $this->assertEquals( '2024-01-02 01:00:00', $result[0]->output ); + + // NULL and invalid arguments yield NULL. + $result = $this->assertQuery( 'SELECT TIMESTAMP(NULL) as output' ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIMESTAMP('2024-05-10', NULL) as output" + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIMESTAMP('not a date') as output" + ); + $this->assertNull( $result[0]->output ); + } + + public function testCurrentTimeAliases() { + // CURTIME() and SYSDATE() produce well-formed UTC values. + $result = $this->assertQuery( "SELECT CURTIME() LIKE '__:__:__' as output" ); + $this->assertEquals( 1, $result[0]->output ); + + $result = $this->assertQuery( "SELECT SYSDATE() LIKE '____-__-__ __:__:__' as output" ); + $this->assertEquals( 1, $result[0]->output ); + + $result = $this->assertQuery( 'SELECT SYSDATE() = NOW() as output' ); + $this->assertEquals( 1, $result[0]->output ); + + // The driver has no authenticated user, so CURRENT_USER() is empty. + $result = $this->assertQuery( 'SELECT CURRENT_USER() as output' ); + $this->assertEquals( '', $result[0]->output ); + } + + public function testWeekModes() { + /* + * WEEK() currently ignores its mode argument and always returns the + * ISO-8601 week. All eight modes therefore agree, which is a documented + * approximation: matching MySQL's eight schemes needs a faithful port of + * its calc_week(), including the WEEK_YEAR flag. The assertions below + * pin the approximation so a future fix has to update them. + */ + $expected = array( + '2024-01-01' => 1, // ISO 2024-W01. + '2021-01-01' => 53, // ISO 2020-W53. + '2024-05-10' => 19, + '2009-06-11' => 24, // MySQL mode 0 gives 23; this is ISO. + ); + foreach ( $expected as $date => $week ) { + for ( $mode = 0; $mode <= 7; $mode++ ) { + $result = $this->assertQuery( + "SELECT WEEK('$date', $mode) as output" + ); + $this->assertEquals( $week, $result[0]->output, "WEEK('$date', $mode)" ); + } + } + + // The default form behaves the same. + $result = $this->assertQuery( "SELECT WEEK('2024-05-10') as output" ); + $this->assertEquals( 19, $result[0]->output ); + + // NULL date and NULL mode yield NULL. + $result = $this->assertQuery( 'SELECT WEEK(NULL, 1) as output' ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( "SELECT WEEK('2024-01-01', NULL) as output" ); + $this->assertNull( $result[0]->output ); + } + + public function testYearWeekFunction() { + // Expected values were taken from MySQL 8.4. + // The buddynext aggregation use with ISO mode 1. + $result = $this->assertQuery( + "SELECT YEARWEEK('2024-05-10', 1) as output" + ); + $this->assertEquals( 202419, $result[0]->output ); + + // The mode defaults to 0, where May 10 2024 is in week 18. + $result = $this->assertQuery( + "SELECT YEARWEEK('2024-05-10') as output" + ); + $this->assertEquals( 202419, $result[0]->output ); + + // YEARWEEK() uses the same ISO approximation as WEEK(), including the + // ISO week-year: 2021-01-01 is in ISO week 53 of 2020, so this is + // 202053 regardless of the mode argument. + $result = $this->assertQuery( + "SELECT YEARWEEK('2021-01-01', 1) as output" + ); + $this->assertEquals( 202053, $result[0]->output ); + + // WEEK() uses the ISO approximation too. + $result = $this->assertQuery( + "SELECT WEEK('2021-01-01', 1) as output" + ); + $this->assertEquals( 53, $result[0]->output ); + + // ISO week-year: 1987-01-01 is a Thursday, so it is ISO week 1 of + // 1987. MySQL's documented mode-0 example returns 198652 for this + // date; the ISO approximation does not reproduce it. + $result = $this->assertQuery( + "SELECT YEARWEEK('1987-01-01') as output" + ); + $this->assertEquals( 198701, $result[0]->output ); + + // 2024-12-30 is ISO week 1 of 2025. + $result = $this->assertQuery( + "SELECT WEEK('2024-12-30', 1) as output" + ); + $this->assertEquals( 1, $result[0]->output ); + + $result = $this->assertQuery( + "SELECT YEARWEEK('2021-01-01', 3) as output" + ); + $this->assertEquals( 202053, $result[0]->output ); + + // The single-argument form behaves like every other mode: 2021-01-01 + // is ISO week 53 of 2020. + $result = $this->assertQuery( + "SELECT YEARWEEK('2021-01-01') as output" + ); + $this->assertEquals( 202053, $result[0]->output ); + + // NULL and invalid input yield NULL. + $result = $this->assertQuery( 'SELECT YEARWEEK(NULL) as output' ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + "SELECT YEARWEEK('not a date', 1) as output" + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + "SELECT YEARWEEK('2024-05-10', 8) as output" + ); + $this->assertNull( $result[0]->output ); + } + + public function testWeekOfYearDayOfYearNamesAndQuarter() { + // Expected values were taken from MySQL 8.4. + // WEEKOFYEAR() is WEEK() with mode 3. + $result = $this->assertQuery( + "SELECT WEEKOFYEAR('2024-05-10') as output" + ); + $this->assertEquals( 19, $result[0]->output ); + + $result = $this->assertQuery( + "SELECT WEEKOFYEAR('2021-01-01') as output" + ); + $this->assertEquals( 53, $result[0]->output ); + + // 2024 is a leap year: Feb 29 is the 60th day (31 + 29). + $result = $this->assertQuery( + "SELECT DAYOFYEAR('2024-02-29') as output" + ); + $this->assertEquals( 60, $result[0]->output ); + + $result = $this->assertQuery( + "SELECT DAYOFYEAR('2023-12-31') as output" + ); + $this->assertEquals( 365, $result[0]->output ); + + // May 10 2024 is a Friday in the second quarter. + $result = $this->assertQuery( + "SELECT DAYNAME('2024-05-10') as output" + ); + $this->assertEquals( 'Friday', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT MONTHNAME('2024-05-10') as output" + ); + $this->assertEquals( 'May', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT QUARTER('2024-05-10') as output" + ); + $this->assertEquals( 2, $result[0]->output ); + + $result = $this->assertQuery( + "SELECT QUARTER('2024-01-01') as output" + ); + $this->assertEquals( 1, $result[0]->output ); + + $result = $this->assertQuery( + "SELECT QUARTER('2024-12-31') as output" + ); + $this->assertEquals( 4, $result[0]->output ); + + // NULL and invalid input yield NULL. + $result = $this->assertQuery( 'SELECT QUARTER(NULL) as output' ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + "SELECT DAYNAME('not a date') as output" + ); + $this->assertNull( $result[0]->output ); + } + + public function testLastDayFunction() { + // Expected values were taken from MySQL 8.4. + $result = $this->assertQuery( + "SELECT LAST_DAY('2024-02-10') as output" + ); + $this->assertEquals( '2024-02-29', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT LAST_DAY('2023-02-10') as output" + ); + $this->assertEquals( '2023-02-28', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT LAST_DAY('2024-01-15 10:00:00') as output" + ); + $this->assertEquals( '2024-01-31', $result[0]->output ); + + // NULL and invalid input yield NULL. + $result = $this->assertQuery( 'SELECT LAST_DAY(NULL) as output' ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + "SELECT LAST_DAY('not a date') as output" + ); + $this->assertNull( $result[0]->output ); + } + + public function testMakeDateTimeFunctions() { + // Expected values were taken from MySQL 8.4. + // 2024 is a leap year, so day 60 (31 + 29) is Feb 29. + $result = $this->assertQuery( + 'SELECT MAKEDATE(2024, 60) as output' + ); + $this->assertEquals( '2024-02-29', $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT MAKEDATE(2023, 365) as output' + ); + $this->assertEquals( '2023-12-31', $result[0]->output ); + + // Day numbers past the end of the year roll over. + $result = $this->assertQuery( + 'SELECT MAKEDATE(2023, 366) as output' + ); + $this->assertEquals( '2024-01-01', $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT MAKEDATE(2024, 367) as output' + ); + $this->assertEquals( '2025-01-01', $result[0]->output ); + + // The day-of-year must be greater than 0. + $result = $this->assertQuery( + 'SELECT MAKEDATE(2024, 0) as output' + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT MAKEDATE(NULL, 60) as output' + ); + $this->assertNull( $result[0]->output ); + + // Hours pad to two digits and may pass 24. + $result = $this->assertQuery( + 'SELECT MAKETIME(12, 15, 30) as output' + ); + $this->assertEquals( '12:15:30', $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT MAKETIME(5, 4, 9) as output' + ); + $this->assertEquals( '05:04:09', $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT MAKETIME(25, 0, 0) as output' + ); + $this->assertEquals( '25:00:00', $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT MAKETIME(838, 59, 59) as output' + ); + $this->assertEquals( '838:59:59', $result[0]->output ); + + // Out-of-range and NULL arguments yield NULL. + $result = $this->assertQuery( + 'SELECT MAKETIME(839, 0, 0) as output' + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT MAKETIME(12, 60, 0) as output' + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT MAKETIME(12, 0, NULL) as output' + ); + $this->assertNull( $result[0]->output ); + } + + public function testSecToTimeFunction() { + // Expected values were taken from MySQL 8.4. + $result = $this->assertQuery( + 'SELECT SEC_TO_TIME(3600) as output' + ); + $this->assertEquals( '01:00:00', $result[0]->output ); + + // 90000 seconds is 25 hours: TIME values may pass 24 hours. + $result = $this->assertQuery( + 'SELECT SEC_TO_TIME(90000) as output' + ); + $this->assertEquals( '25:00:00', $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT SEC_TO_TIME(-3600) as output' + ); + $this->assertEquals( '-01:00:00', $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT SEC_TO_TIME(0) as output' + ); + $this->assertEquals( '00:00:00', $result[0]->output ); + + // A fractional input keeps a trimmed fraction: 61.5 is 1:01.5. + $result = $this->assertQuery( + 'SELECT SEC_TO_TIME(61.5) as output' + ); + $this->assertEquals( '00:01:01.5', $result[0]->output ); + + // 838:59:59 is 3020399 seconds (838 * 3600 + 59 * 60 + 59). + $result = $this->assertQuery( + 'SELECT SEC_TO_TIME(3020399) as output' + ); + $this->assertEquals( '838:59:59', $result[0]->output ); + + // Anything past the TIME range clamps to the range endpoint. + $result = $this->assertQuery( + 'SELECT SEC_TO_TIME(9999999) as output' + ); + $this->assertEquals( '838:59:59', $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT SEC_TO_TIME(-9999999) as output' + ); + $this->assertEquals( '-838:59:59', $result[0]->output ); + + // NULL and non-numeric input yield NULL. + $result = $this->assertQuery( + 'SELECT SEC_TO_TIME(NULL) as output' + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + "SELECT SEC_TO_TIME('abc') as output" + ); + $this->assertNull( $result[0]->output ); + } + + public function testTimeToSecFunction() { + // Expected values were taken from MySQL 8.4. + $result = $this->assertQuery( + "SELECT TIME_TO_SEC('01:00:00') as output" + ); + $this->assertEquals( 3600, $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIME_TO_SEC('25:00:00') as output" + ); + $this->assertEquals( 90000, $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIME_TO_SEC('-01:00:00') as output" + ); + $this->assertEquals( -3600, $result[0]->output ); + + // Datetimes convert their time-of-day part. + $result = $this->assertQuery( + "SELECT TIME_TO_SEC('2024-01-01 02:00:00') as output" + ); + $this->assertEquals( 7200, $result[0]->output ); + + // Fractional seconds truncate toward zero. + $result = $this->assertQuery( + "SELECT TIME_TO_SEC('00:01:01.9') as output" + ); + $this->assertEquals( 61, $result[0]->output ); + + // NULL and invalid input yield NULL. + $result = $this->assertQuery( + 'SELECT TIME_TO_SEC(NULL) as output' + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIME_TO_SEC('not a time') as output" + ); + $this->assertNull( $result[0]->output ); + } + + public function testToDaysFromDaysToSeconds() { + // Expected values were hand-computed with MySQL's calc_daynr(): + // TO_DAYS('2007-10-07') = 365 * 2007 + 31 * 9 + 7 = 732841, + // minus (10 * 4 + 23) / 10 = 6, plus 2007 / 4 - ((2007 / 100 + 1) * 3) / 4 + // = 501 - 15 = 486, giving 733321. All divisions truncate. + $result = $this->assertQuery( + "SELECT TO_DAYS('2007-10-07') as output" + ); + $this->assertEquals( 733321, $result[0]->output ); + + // Day number 1 is 0000-01-01: the count anchors at year 0. + $result = $this->assertQuery( + "SELECT TO_DAYS('0000-01-01') as output" + ); + $this->assertEquals( 1, $result[0]->output ); + + // Datetimes use their date part. + $result = $this->assertQuery( + "SELECT TO_DAYS('2007-10-07 12:00:00') as output" + ); + $this->assertEquals( 733321, $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT FROM_DAYS(733321) as output' + ); + $this->assertEquals( '2007-10-07', $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT FROM_DAYS(1) as output' + ); + $this->assertEquals( '0000-01-01', $result[0]->output ); + + // TO_DAYS('9999-12-31') is 3652424 by the same computation, and + // anything past it is out of range. + $result = $this->assertQuery( + 'SELECT FROM_DAYS(3652424) as output' + ); + $this->assertEquals( '9999-12-31', $result[0]->output ); + + // Day 0 would be the MySQL zero date, which the driver reports + // as NULL, so any number below 1 returns NULL. + $result = $this->assertQuery( + 'SELECT FROM_DAYS(0) as output' + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT FROM_DAYS(-5) as output' + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT FROM_DAYS(3652425) as output' + ); + $this->assertNull( $result[0]->output ); + + // TO_SECONDS('2007-10-07') is (733321 - 1) * 86400 = 63358848000. + $result = $this->assertQuery( + "SELECT TO_SECONDS('2007-10-07') as output" + ); + $this->assertEquals( 63358848000, $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TO_SECONDS('0000-01-01') as output" + ); + $this->assertEquals( 0, $result[0]->output ); + + // 2024-05-10 is day 739381, so midnight is (739381 - 1) * 86400 + // and 14:30:00 adds 14 * 3600 + 30 * 60 = 52200 seconds. + $result = $this->assertQuery( + "SELECT TO_SECONDS('2024-05-10 14:30:00') as output" + ); + $this->assertEquals( 63882484200, $result[0]->output ); + + // NULL and invalid input yield NULL. + $result = $this->assertQuery( + 'SELECT TO_DAYS(NULL) as output' + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TO_DAYS('not a date') as output" + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT TO_SECONDS(NULL) as output' + ); + $this->assertNull( $result[0]->output ); + } + + public function testPeriodAddDiffFunctions() { + // Expected values were taken from MySQL 8.4. + $result = $this->assertQuery( + 'SELECT PERIOD_ADD(200801, 2) as output' + ); + $this->assertEquals( 200803, $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT PERIOD_ADD(200812, 1) as output' + ); + $this->assertEquals( 200901, $result[0]->output ); + + // Two-digit input years are expanded and the result is always YYYYMM: + // 7001 is 1970-01, so adding one month is 197002. + $result = $this->assertQuery( + 'SELECT PERIOD_ADD(7001, 1) as output' + ); + $this->assertEquals( 197002, $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT PERIOD_ADD(200802, -1) as output' + ); + $this->assertEquals( 200801, $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT PERIOD_DIFF(200802, 200703) as output' + ); + $this->assertEquals( 11, $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT PERIOD_DIFF(200703, 200802) as output' + ); + $this->assertEquals( -11, $result[0]->output ); + + // Invalid months and NULL arguments yield NULL. + $result = $this->assertQuery( + 'SELECT PERIOD_ADD(200813, 1) as output' + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT PERIOD_DIFF(200800, 200801) as output' + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT PERIOD_ADD(NULL, 1) as output' + ); + $this->assertNull( $result[0]->output ); + } + + public function testMicrosecondAddSubTimeFunctions() { + // Expected values were taken from MySQL 8.4. + $result = $this->assertQuery( + "SELECT MICROSECOND('12:00:00.123456') as output" + ); + $this->assertEquals( 123456, $result[0]->output ); + + $result = $this->assertQuery( + "SELECT MICROSECOND('12:00:00') as output" + ); + $this->assertEquals( 0, $result[0]->output ); + + $result = $this->assertQuery( + "SELECT MICROSECOND('2024-01-01 00:00:00.5') as output" + ); + $this->assertEquals( 500000, $result[0]->output ); + + $result = $this->assertQuery( + 'SELECT MICROSECOND(NULL) as output' + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + "SELECT ADDTIME('2024-01-01 00:00:00', '01:00:00') as output" + ); + $this->assertEquals( '2024-01-01 01:00:00', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT SUBTIME('2024-01-01 00:00:00', '01:00:00') as output" + ); + $this->assertEquals( '2023-12-31 23:00:00', $result[0]->output ); + + // TIME results may pass 24 hours: 23:59:59 + 2s is 24:00:01. + $result = $this->assertQuery( + "SELECT ADDTIME('23:59:59', '00:00:02') as output" + ); + $this->assertEquals( '24:00:01', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT ADDTIME('01:00:00', '25:00:00') as output" + ); + $this->assertEquals( '26:00:00', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT SUBTIME('01:00:00', '25:00:00') as output" + ); + $this->assertEquals( '-24:00:00', $result[0]->output ); + + // TIME results clamp to +-838:59:59. + $result = $this->assertQuery( + "SELECT ADDTIME('838:00:00', '01:00:00') as output" + ); + $this->assertEquals( '838:59:59', $result[0]->output ); + + // NULL and invalid input yield NULL. + $result = $this->assertQuery( + "SELECT ADDTIME(NULL, '01:00:00') as output" + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + "SELECT SUBTIME('01:00:00', 'not a time') as output" + ); + $this->assertNull( $result[0]->output ); + } + + public function testGetFormatFunction() { + // The static mapping from the MySQL 8.4 documentation. + $expected = array( + array( 'DATE', 'USA', '%m.%d.%Y' ), + array( 'DATE', 'EUR', '%d.%m.%Y' ), + array( 'DATE', 'JIS', '%Y-%m-%d' ), + array( 'DATE', 'ISO', '%Y-%m-%d' ), + array( 'DATE', 'INTERNAL', '%Y%m%d' ), + array( 'DATETIME', 'USA', '%Y-%m-%d %H.%i.%s' ), + array( 'DATETIME', 'EUR', '%Y-%m-%d %H.%i.%s' ), + array( 'DATETIME', 'JIS', '%Y-%m-%d %H:%i:%s' ), + array( 'DATETIME', 'ISO', '%Y-%m-%d %H:%i:%s' ), + array( 'DATETIME', 'INTERNAL', '%Y%m%d%H%i%s' ), + array( 'TIME', 'USA', '%h:%i:%s %p' ), + array( 'TIME', 'EUR', '%H.%i.%s' ), + array( 'TIME', 'JIS', '%H:%i:%s' ), + array( 'TIME', 'ISO', '%H:%i:%s' ), + array( 'TIME', 'INTERNAL', '%H%i%s' ), + ); + foreach ( $expected as list( $type, $name, $format ) ) { + $result = $this->assertQuery( + "SELECT GET_FORMAT($type, '$name') as output" + ); + $this->assertEquals( $format, $result[0]->output, "GET_FORMAT($type, '$name')" ); + } + + // Both arguments are case-insensitive. + $result = $this->assertQuery( + "SELECT GET_FORMAT('datetime', 'eur') as output" + ); + $this->assertEquals( '%Y-%m-%d %H.%i.%s', $result[0]->output ); + + // Unknown types, unknown names, and NULL yield NULL. + $result = $this->assertQuery( + "SELECT GET_FORMAT(DATE, 'XXX') as output" + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + "SELECT GET_FORMAT('XXX', 'USA') as output" + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + "SELECT GET_FORMAT(NULL, 'USA') as output" + ); + $this->assertNull( $result[0]->output ); + } + + public function testTimeFormatFunction() { + // Expected values were taken from MySQL 8.4. + $result = $this->assertQuery( + "SELECT TIME_FORMAT('14:30:00', '%h:%i %p') as output" + ); + $this->assertEquals( '02:30 PM', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIME_FORMAT('14:30:05', '%T') as output" + ); + $this->assertEquals( '14:30:05', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIME_FORMAT('14:30:05', '%r') as output" + ); + $this->assertEquals( '02:30:05 PM', $result[0]->output ); + + // %f is the zero-padded microseconds part. + $result = $this->assertQuery( + "SELECT TIME_FORMAT('14:30:00.5', '%s.%f') as output" + ); + $this->assertEquals( '00.500000', $result[0]->output ); + + // Hours past 23 keep their unbounded value. + $result = $this->assertQuery( + "SELECT TIME_FORMAT('25:00:00', '%H:%i') as output" + ); + $this->assertEquals( '25:00', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIME_FORMAT('-01:30:00', '%H:%i') as output" + ); + $this->assertEquals( '-01:30', $result[0]->output ); + + // NULL and invalid input yield NULL. + $result = $this->assertQuery( + 'SELECT TIME_FORMAT(NULL, \'%H\') as output' + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + "SELECT TIME_FORMAT('not a time', '%H') as output" + ); + $this->assertNull( $result[0]->output ); + } + + public function testStrToDateFunction() { + // Expected values were taken from MySQL 8.4. + $result = $this->assertQuery( + "SELECT STR_TO_DATE('2024-05-10 14:30:00', '%Y-%m-%d %H:%i:%s') as output" + ); + $this->assertEquals( '2024-05-10 14:30:00', $result[0]->output ); + + // A format with only date parts yields a DATE, as in MySQL. + $result = $this->assertQuery( + "SELECT STR_TO_DATE('2024-05-10', '%Y-%m-%d') as output" + ); + $this->assertEquals( '2024-05-10', $result[0]->output ); + + // Two-digit years convert as 00-69 to 2000-2069, 70-99 to 1900-1999. + $result = $this->assertQuery( + "SELECT STR_TO_DATE('24-05-10', '%y-%m-%d') as output" + ); + $this->assertEquals( '2024-05-10', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT STR_TO_DATE('69-05-10', '%y-%m-%d') as output" + ); + $this->assertEquals( '2069-05-10', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT STR_TO_DATE('70-05-10', '%y-%m-%d') as output" + ); + $this->assertEquals( '1970-05-10', $result[0]->output ); + + // Month names match in English, case-insensitively. + $result = $this->assertQuery( + "SELECT STR_TO_DATE('May 10, 2024', '%M %d, %Y') as output" + ); + $this->assertEquals( '2024-05-10', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT STR_TO_DATE('10/05/2024 2:30:05 PM', '%m/%d/%Y %r') as output" + ); + $this->assertEquals( '2024-10-05 14:30:05', $result[0]->output ); + + // 12-hour clocks adjust with AM/PM: midnight and noon included. + $result = $this->assertQuery( + "SELECT STR_TO_DATE('2024-05-10 02:30 PM', '%Y-%m-%d %h:%i %p') as output" + ); + $this->assertEquals( '2024-05-10 14:30:00', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT STR_TO_DATE('2024-05-10 12:00 AM', '%Y-%m-%d %h:%i %p') as output" + ); + $this->assertEquals( '2024-05-10 00:00:00', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT STR_TO_DATE('2024-05-10 12:00 PM', '%Y-%m-%d %h:%i %p') as output" + ); + $this->assertEquals( '2024-05-10 12:00:00', $result[0]->output ); + + $result = $this->assertQuery( + "SELECT STR_TO_DATE('Sept 3, 2024', '%b %d, %Y') as output" + ); + $this->assertEquals( '2024-09-03', $result[0]->output ); + + // Values that do not match the format exactly yield NULL. + $result = $this->assertQuery( + "SELECT STR_TO_DATE('2024-05-10', '%d/%m/%Y') as output" + ); + $this->assertNull( $result[0]->output ); + + // Unsupported specifiers yield NULL. + $result = $this->assertQuery( + "SELECT STR_TO_DATE('2024', '%Y %x') as output" + ); + $this->assertNull( $result[0]->output ); + + // The year, month, and day must all be present. + $result = $this->assertQuery( + "SELECT STR_TO_DATE('10:30', '%H:%i') as output" + ); + $this->assertNull( $result[0]->output ); + + // Out-of-range parts yield NULL. + $result = $this->assertQuery( + "SELECT STR_TO_DATE('2024-13-01', '%Y-%m-%d') as output" + ); + $this->assertNull( $result[0]->output ); + + $result = $this->assertQuery( + "SELECT STR_TO_DATE('2024-02-30', '%Y-%m-%d') as output" + ); + $this->assertNull( $result[0]->output ); + + // NULL arguments yield NULL. + $result = $this->assertQuery( + 'SELECT STR_TO_DATE(NULL, \'%Y-%m-%d\') as output' + ); + $this->assertNull( $result[0]->output ); + } + public function testIntervalArithmetic() { // Expected values were taken from MySQL 8.4. $result = $this->assertQuery( diff --git a/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Translation_Tests.php b/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Translation_Tests.php index d0d522db4..ddd06f56b 100644 --- a/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Translation_Tests.php +++ b/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Translation_Tests.php @@ -1806,6 +1806,78 @@ public function testIntervalArithmeticChains(): void { ); } + public function testAddSubDateTranslation(): void { + // The three-argument INTERVAL form translates like DATE_ADD/DATE_SUB. + $this->assertQuery( + "SELECT CASE WHEN LENGTH('2024-01-01') = 10 THEN DATE('2024-01-01', (1) || ' DAY') ELSE DATETIME('2024-01-01', (1) || ' DAY') END AS `a`", + 'SELECT ADDDATE(\'2024-01-01\', INTERVAL 1 DAY) AS a' + ); + + $this->assertQuery( + "SELECT CASE WHEN LENGTH('2024-01-05') = 10 THEN DATE('2024-01-05', -(2) || ' DAY') ELSE DATETIME('2024-01-05', -(2) || ' DAY') END AS `a`", + 'SELECT SUBDATE(\'2024-01-05\', INTERVAL 2 DAY) AS a' + ); + + // The two-argument form adds or subtracts a number of days. MySQL + // treats that count as an integer, so it is cast before it becomes a + // time modifier. + $this->assertQuery( + "SELECT CASE WHEN LENGTH('2024-01-01') = 10 THEN DATE('2024-01-01', CAST((1) AS INTEGER) || ' DAY') ELSE DATETIME('2024-01-01', CAST((1) AS INTEGER) || ' DAY') END AS `a`", + 'SELECT ADDDATE(\'2024-01-01\', 1) AS a' + ); + + $this->assertQuery( + "SELECT CASE WHEN LENGTH('2024-01-01') = 10 THEN DATE('2024-01-01', -CAST((1) AS INTEGER) || ' DAY') ELSE DATETIME('2024-01-01', -CAST((1) AS INTEGER) || ' DAY') END AS `a`", + 'SELECT SUBDATE(\'2024-01-01\', 1) AS a' + ); + } + + public function testCurrentDateAndTimeTranslation(): void { + // SQLite accepts the bare CURRENT_DATE and CURRENT_TIME keywords. + $this->assertQuery( + 'SELECT CURRENT_DATE AS `a`', + 'SELECT CURRENT_DATE() AS a' + ); + + $this->assertQuery( + 'SELECT CURRENT_TIME AS `a`', + 'SELECT CURRENT_TIME() AS a' + ); + + $this->assertQuery( + 'SELECT CURRENT_DATE AS `a`', + 'SELECT CURRENT_DATE AS a' + ); + + $this->assertQuery( + 'SELECT CURRENT_TIME AS `a`', + 'SELECT CURRENT_TIME AS a' + ); + } + + public function testTimestampAddDiffTranslation(): void { + // Bare units would translate to quoted column references, so they + // are passed to the UDFs as string literals instead. + $this->assertQuery( + "SELECT TIMESTAMPDIFF('SECOND', '2024-01-01', '2024-01-02') AS `a`", + 'SELECT TIMESTAMPDIFF(SECOND, \'2024-01-01\', \'2024-01-02\') AS a' + ); + + $this->assertQuery( + "SELECT TIMESTAMPADD('MINUTE', 1, '2003-01-02') AS `a`", + 'SELECT TIMESTAMPADD(MINUTE, 1, \'2003-01-02\') AS a' + ); + } + + public function testGetFormatTranslation(): void { + // The DATE keyword would translate to a quoted column reference, + // so it is passed to the UDF as a string literal instead. + $this->assertQuery( + "SELECT GET_FORMAT('DATE', 'USA') AS `a`", + 'SELECT GET_FORMAT(DATE, \'USA\') AS a' + ); + } + public function testIndexHints(): void { // USE INDEX $this->assertQuery(