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..0ef61c737 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 @@ -5185,6 +5185,9 @@ private function translate_regexp_functions( WP_Parser_Node $node ): string { private function translate_runtime_function_call( WP_Parser_Node $node ): string { $child = $node->get_first_child(); if ( $child instanceof WP_Parser_Node ) { + if ( 'trimFunction' === $child->rule_name ) { + return $this->translate_trim_function( $child ); + } return $this->translate( $child ); } @@ -5222,11 +5225,152 @@ private function translate_runtime_function_call( WP_Parser_Node $node ): string $this->translate( $nodes[0] ), $this->translate( $nodes[1] ) ); + case WP_MySQL_Lexer::RIGHT_SYMBOL: + /* + * RIGHT is parsed as a keyword, and it is a join keyword in + * newer SQLite versions, where it cannot be called as a + * function. Route it to a UDF with a non-reserved name. + */ + $nodes = $node->get_child_nodes(); + return sprintf( + 'right_str(%s, %s)', + $this->translate( $nodes[0] ), + $this->translate( $nodes[1] ) + ); + case WP_MySQL_Lexer::POSITION_SYMBOL: + // POSITION(substr IN str) is LOCATE() with swapped arguments. + $nodes = $node->get_child_nodes(); + return sprintf( + 'locate(%s, %s)', + $this->translate( $nodes[0] ), + $this->translate( $nodes[1] ) + ); + case WP_MySQL_Lexer::INSERT_SYMBOL: + // The string function INSERT(). Emitted under a different + // name because SQLite will not accept INSERT as a function. + $nodes = $node->get_child_nodes(); + return sprintf( + 'insert_str(%s, %s, %s, %s)', + $this->translate( $nodes[0] ), + $this->translate( $nodes[1] ), + $this->translate( $nodes[2] ), + $this->translate( $nodes[3] ) + ); + case WP_MySQL_Lexer::EXTRACT_SYMBOL: + $nodes = $node->get_child_nodes(); + return $this->translate_extract_function( $nodes[0], $nodes[1] ); default: return $this->translate_sequence( $node->get_children() ); } } + /** + * Translate a MySQL EXTRACT(part FROM date) call to SQLite. + * + * @param WP_Parser_Node $part_node The "interval" AST node holding the unit. + * @param WP_Parser_Node $date_node The date expression AST node. + * @return string The translated value. + * @throws WP_MySQL_On_SQLite_Exception When the translation fails. + */ + private function translate_extract_function( WP_Parser_Node $part_node, WP_Parser_Node $date_node ): string { + $unit_token = $part_node->get_first_descendant_token(); + $date = $this->translate( $date_node ); + + switch ( $unit_token->id ) { + case WP_MySQL_Lexer::YEAR_SYMBOL: + return sprintf( 'year(%s)', $date ); + case WP_MySQL_Lexer::QUARTER_SYMBOL: + return sprintf( + 'CAST(((CAST(STRFTIME(%s, %s) AS INTEGER) + 2) / 3) AS INTEGER)', + $this->quote_sqlite_value( '%m' ), + $date + ); + case WP_MySQL_Lexer::MONTH_SYMBOL: + return sprintf( 'month(%s)', $date ); + case WP_MySQL_Lexer::WEEK_SYMBOL: + return sprintf( 'week(%s, 0)', $date ); + case WP_MySQL_Lexer::DAY_SYMBOL: + return sprintf( 'day(%s)', $date ); + case WP_MySQL_Lexer::HOUR_SYMBOL: + return sprintf( 'hour(%s)', $date ); + case WP_MySQL_Lexer::MINUTE_SYMBOL: + return sprintf( 'minute(%s)', $date ); + case WP_MySQL_Lexer::SECOND_SYMBOL: + return sprintf( 'second(%s)', $date ); + case WP_MySQL_Lexer::MICROSECOND_SYMBOL: + return sprintf( + 'CASE WHEN (%1$s) IS NULL THEN NULL WHEN INSTR((%1$s), %2$s) > 0 THEN CAST(SUBSTR((%1$s) || %3$s, INSTR((%1$s), %2$s) + 1, 6) AS INTEGER) ELSE 0 END', + $date, + $this->quote_sqlite_value( '.' ), + $this->quote_sqlite_value( '000000' ) + ); + default: + throw $this->new_not_supported_exception( + sprintf( 'EXTRACT unit: %s', $unit_token->get_value() ) + ); + } + } + + /** + * Translate a MySQL TRIM() call to SQLite. + * + * Handles the extended TRIM([{BOTH | LEADING | TRAILING} [remstr] FROM] str) + * syntax. The plain TRIM(str) and TRIM(remstr FROM str) forms are covered + * by the same mapping. + * + * @param WP_Parser_Node $node The "trimFunction" AST node. + * @return string The translated value. + * @throws WP_MySQL_On_SQLite_Exception When the translation fails. + */ + private function translate_trim_function( WP_Parser_Node $node ): string { + $spec = null; + $exprs = array(); + foreach ( $node->get_children() as $child ) { + if ( $child instanceof WP_MySQL_Token ) { + if ( WP_MySQL_Lexer::LEADING_SYMBOL === $child->id ) { + $spec = 'LEADING'; + } elseif ( WP_MySQL_Lexer::TRAILING_SYMBOL === $child->id ) { + $spec = 'TRAILING'; + } elseif ( WP_MySQL_Lexer::BOTH_SYMBOL === $child->id ) { + $spec = 'BOTH'; + } + continue; + } + if ( $child instanceof WP_Parser_Node ) { + $exprs[] = $this->translate( $child ); + } + } + + if ( 0 === count( $exprs ) || 2 < count( $exprs ) ) { + throw $this->new_invalid_input_exception(); + } + + if ( 2 === count( $exprs ) ) { + $str = $exprs[1]; + $remstr = $exprs[0]; + } else { + $str = $exprs[0]; + $remstr = null; + } + + if ( 'LEADING' === $spec ) { + if ( null === $remstr ) { + return sprintf( 'LTRIM(%s)', $str ); + } + return sprintf( 'LTRIM(%s, %s)', $str, $remstr ); + } + if ( 'TRAILING' === $spec ) { + if ( null === $remstr ) { + return sprintf( 'RTRIM(%s)', $str ); + } + return sprintf( 'RTRIM(%s, %s)', $str, $remstr ); + } + if ( null === $remstr ) { + return sprintf( 'TRIM(%s)', $str ); + } + return sprintf( 'TRIM(%s, %s)', $str, $remstr ); + } + /** * Translate MySQL date arithmetic to a SQLite DATE() or DATETIME() call. * @@ -5367,6 +5511,29 @@ 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 'LCASE': + if ( 1 === count( $args ) ) { + return 'LOWER(' . $args[0] . ')'; + } + return $this->translate_sequence( $node->get_children() ); + case 'UCASE': + if ( 1 === count( $args ) ) { + return 'UPPER(' . $args[0] . ')'; + } + return $this->translate_sequence( $node->get_children() ); + case 'TRUNCATE': + /* + * SQLite's TRUNC() takes a single argument, and POW() is only + * available when SQLite is built with math functions, which + * older supported builds are not. Delegate to a UDF instead. + */ + if ( 1 === count( $args ) ) { + $args[1] = '0'; + } + if ( 2 === count( $args ) ) { + return sprintf( 'truncate(%s, %s)', $args[0], $args[1] ); + } + return $this->translate_sequence( $node->get_children() ); case 'CONCAT': return '(' . implode( ' || ', $args ) . ')'; case 'FOUND_ROWS': 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..55629b1b5 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 @@ -38,6 +38,15 @@ public static function register_for( $pdo ): self { * * @var array */ + /** + * Maximum size of a string a UDF will allocate, in bytes. + * + * Matches the MySQL 8.0 default max_allowed_packet. MySQL returns NULL + * for results above the limit; doing the same here avoids a fatal + * out-of-memory error inside str_repeat(). + */ + private const MAX_STRING_RESULT_BYTES = 67108864; + private $functions = array( 'throw' => 'throw', 'month' => 'month', @@ -67,8 +76,6 @@ public static function register_for( $pdo ): self { 'greatest' => 'greatest', 'get_lock' => 'get_lock', 'release_lock' => 'release_lock', - 'ucase' => 'ucase', - 'lcase' => 'lcase', 'unhex' => 'unhex', 'from_base64' => 'from_base64', 'to_base64' => 'to_base64', @@ -81,6 +88,22 @@ public static function register_for( $pdo ): self { 'utc_timestamp' => 'utc_timestamp', 'version' => 'version', 'reverse' => 'reverse', + 'repeat' => 'repeat', + 'right_str' => 'right', + 'lpad' => 'lpad', + 'rpad' => 'rpad', + 'space' => 'space', + 'ascii' => 'ascii', + 'ord' => 'ord', + 'strcmp' => 'strcmp', + 'find_in_set' => 'find_in_set', + 'elt' => 'elt', + 'make_set' => 'make_set', + 'export_set' => 'export_set', + 'soundex' => 'soundex', + 'format' => 'format', + 'insert_str' => 'insert_str', + 'truncate' => 'truncate', // Internal helper functions. '_helper_like_to_glob_pattern' => '_helper_like_to_glob_pattern', @@ -713,34 +736,6 @@ public function release_lock( $name ) { return '1=1'; } - /** - * Method to emulate MySQL UCASE() function. - * - * This is MySQL alias for upper() function. This function rewrites it - * to SQLite compatible name upper(). - * - * @param string $content String to be converted to uppercase. - * - * @return string SQLite compatible function name. - */ - public function ucase( $content ) { - return "upper($content)"; - } - - /** - * Method to emulate MySQL LCASE() function. - * - * This is MySQL alias for lower() function. This function rewrites it - * to SQLite compatible name lower(). - * - * @param string $content String to be converted to lowercase. - * - * @return string SQLite compatible function name. - */ - public function lcase( $content ) { - return "lower($content)"; - } - /** * Method to emulate MySQL UNHEX() function. * @@ -847,23 +842,47 @@ public function datediff( $start, $end ) { * * @param string $substr Needle. * @param string $str Haystack. - * @param integer $pos Position. + * @param integer $pos 1-based position to start the search from. * - * @return integer + * @return integer|null */ - public function locate( $substr, $str, $pos = 0 ) { - if ( ! extension_loaded( 'mbstring' ) ) { - $val = strpos( $str, $substr, $pos ); - if ( false !== $val ) { - return $val + 1; - } + public function locate( $substr, $str, $pos = 1 ) { + if ( null === $substr || null === $str || null === $pos ) { + return null; + } + $substr = (string) $substr; + $str = (string) $str; + + // MySQL positions are 1-based; clamp invalid values to the start. + $offset = (int) round( (float) $pos ) - 1; + if ( 0 > $offset ) { + $offset = 0; + } + + /* + * strpos()/mb_strpos() throw when the offset is past the end of the + * haystack, and an empty needle returns false with a warning on + * older PHP. MySQL returns 0 and the start position respectively. + */ + if ( $offset > $this->char_strlen( $str ) ) { return 0; } - $val = mb_strpos( $str, $substr, $pos ); - if ( false !== $val ) { + if ( '' === $substr ) { + return $offset + 1; + } + + if ( extension_loaded( 'mbstring' ) ) { + $val = mb_strpos( $str, $substr, $offset, 'UTF-8' ); + if ( false === $val ) { + return 0; + } return $val + 1; } - return 0; + $val = strpos( $str, $substr, $offset ); + if ( false === $val ) { + return 0; + } + return $val + 1; } /** @@ -927,6 +946,644 @@ public function reverse( $str ) { return strrev( $str ); } + /** + * Get the length of a string in characters. + * + * Uses mb_strlen() when the mbstring extension is loaded, so that + * multi-byte characters are counted like MySQL does. Falls back to a + * byte count otherwise. + * + * @param string $str The string to measure. + * + * @return int The character length. + */ + private function char_strlen( $str ) { + if ( extension_loaded( 'mbstring' ) ) { + $length = mb_strlen( $str, 'UTF-8' ); + if ( false !== $length ) { + return $length; + } + } + return strlen( $str ); + } + + /** + * Get a substring counted in characters, not bytes. + * + * Uses mb_substr() when the mbstring extension is loaded, so that + * multi-byte characters are not split like MySQL does. Falls back to a + * byte-based substr() otherwise. + * + * @param string $str The input string. + * @param int $start 0-based start offset in characters. + * @param int|null $length Optional length in characters. + * + * @return string The substring, or an empty string when out of range. + */ + private function char_substr( $str, $start, $length = null ) { + if ( extension_loaded( 'mbstring' ) ) { + if ( null === $length ) { + $result = mb_substr( $str, $start, null, 'UTF-8' ); + } else { + $result = mb_substr( $str, $start, $length, 'UTF-8' ); + } + if ( false !== $result ) { + return $result; + } + } + if ( null === $length ) { + $result = substr( $str, $start ); + } else { + $result = substr( $str, $start, $length ); + } + if ( false === $result ) { + return ''; + } + return $result; + } + + /** + * Build a padding string of an exact character length. + * + * Repeats $padstr and truncates it to $length characters, counting + * multi-byte characters like MySQL does. + * + * @param string $padstr The padding string, must not be empty. + * @param int $length The number of characters to build. + * + * @return string The padding string. + */ + private function build_pad_string( $padstr, $length ) { + $pad_length = $this->char_strlen( $padstr ); + $repeat = (int) ceil( $length / $pad_length ); + if ( 1 > $repeat ) { + $repeat = 1; + } + if ( ! $this->string_size_within_limit( strlen( $padstr ), $repeat ) ) { + return null; + } + return $this->char_substr( str_repeat( $padstr, $repeat ), 0, $length ); + } + + /** + * Whether a generated string stays within the maximum result size. + * + * MySQL returns NULL with a warning when a string result exceeds + * max_allowed_packet. Here an unbounded str_repeat() would exhaust the + * PHP memory limit and end the request, so the same limit is applied + * before allocating. + * + * @param int $unit_length Length of one unit in bytes. + * @param int $units Number of units to concatenate. + * + * @return bool Whether the result fits. + */ + private function string_size_within_limit( $unit_length, $units ) { + return ( $unit_length * $units ) <= self::MAX_STRING_RESULT_BYTES; + } + + /** + * Method to emulate MySQL REPEAT() function. + * + * Returns a string consisting of $str repeated $count times. Returns an + * empty string when $count is less than 1, and NULL when any argument + * is NULL. + * + * @param string|null $str The string to repeat. + * @param mixed $count The repeat count. + * + * @return string|null The repeated string, or NULL. + */ + public function repeat( $str, $count ) { + if ( null === $str || null === $count ) { + return null; + } + $count = (int) round( (float) $count ); + if ( 1 > $count ) { + return ''; + } + $str = (string) $str; + if ( ! $this->string_size_within_limit( strlen( $str ), $count ) ) { + return null; + } + return str_repeat( $str, $count ); + } + + /** + * Method to emulate MySQL RIGHT() function. + * + * Returns the rightmost $len characters of $str. Returns an empty string + * when $len is less than 1, and NULL when any argument is NULL. + * + * @param string|null $str The input string. + * @param mixed $len The number of characters. + * + * @return string|null The rightmost characters, or NULL. + */ + public function right( $str, $len ) { + if ( null === $str || null === $len ) { + return null; + } + $len = (int) round( (float) $len ); + if ( 1 > $len ) { + return ''; + } + $str = (string) $str; + if ( $len >= $this->char_strlen( $str ) ) { + return $str; + } + if ( extension_loaded( 'mbstring' ) ) { + return mb_substr( $str, -$len, null, 'UTF-8' ); + } + return substr( $str, -$len ); + } + + /** + * Method to emulate MySQL LPAD() function. + * + * Left-pads $str with $padstr to a length of $len characters. Longer + * strings are truncated. Returns NULL when any argument is NULL, when + * $len is negative, or when padding is needed but $padstr is empty. + * + * @param string|null $str The input string. + * @param mixed $len The target length in characters. + * @param string|null $padstr The padding string. + * + * @return string|null The padded string, or NULL. + */ + public function lpad( $str, $len, $padstr ) { + if ( null === $str || null === $len || null === $padstr ) { + return null; + } + $len = (int) round( (float) $len ); + if ( 0 > $len ) { + return null; + } + if ( 0 === $len ) { + return ''; + } + $str = (string) $str; + $padstr = (string) $padstr; + if ( $this->char_strlen( $str ) >= $len ) { + return $this->char_substr( $str, 0, $len ); + } + if ( '' === $padstr ) { + return null; + } + $pad = $this->build_pad_string( $padstr, $len - $this->char_strlen( $str ) ); + if ( null === $pad || ! $this->string_size_within_limit( strlen( $pad ) + strlen( $str ), 1 ) ) { + return null; + } + return $pad . $str; + } + + /** + * Method to emulate MySQL RPAD() function. + * + * Right-pads $str with $padstr to a length of $len characters. Longer + * strings are truncated. Returns NULL when any argument is NULL, when + * $len is negative, or when padding is needed but $padstr is empty. + * + * @param string|null $str The input string. + * @param mixed $len The target length in characters. + * @param string|null $padstr The padding string. + * + * @return string|null The padded string, or NULL. + */ + public function rpad( $str, $len, $padstr ) { + if ( null === $str || null === $len || null === $padstr ) { + return null; + } + $len = (int) round( (float) $len ); + if ( 0 > $len ) { + return null; + } + if ( 0 === $len ) { + return ''; + } + $str = (string) $str; + $padstr = (string) $padstr; + if ( $this->char_strlen( $str ) >= $len ) { + return $this->char_substr( $str, 0, $len ); + } + if ( '' === $padstr ) { + return null; + } + $pad = $this->build_pad_string( $padstr, $len - $this->char_strlen( $str ) ); + if ( null === $pad || ! $this->string_size_within_limit( strlen( $pad ) + strlen( $str ), 1 ) ) { + return null; + } + return $str . $pad; + } + + /** + * Method to emulate MySQL SPACE() function. + * + * Returns a string of $n spaces, or an empty string when $n is less + * than 1. Returns NULL when $n is NULL. + * + * @param mixed $n The number of spaces. + * + * @return string|null The spaces, or NULL. + */ + public function space( $n ) { + if ( null === $n ) { + return null; + } + $n = (int) round( (float) $n ); + if ( 1 > $n ) { + return ''; + } + if ( ! $this->string_size_within_limit( 1, $n ) ) { + return null; + } + return str_repeat( ' ', $n ); + } + + /** + * Method to emulate MySQL ASCII() function. + * + * Returns the numeric value of the first byte of $str. Returns 0 when + * $str is the empty string, and NULL when $str is NULL. + * + * @param string|null $str The input string. + * + * @return int|null The byte value, 0, or NULL. + */ + public function ascii( $str ) { + if ( null === $str ) { + return null; + } + $str = (string) $str; + if ( '' === $str ) { + return 0; + } + return ord( $str[0] ); + } + + /** + * Method to emulate MySQL ORD() function. + * + * Returns the code of the leftmost character of $str. Multi-byte + * characters are decoded as UTF-8. Returns 0 when $str is the empty + * string, and NULL when $str is NULL. + * + * @param string|null $str The input string. + * + * @return int|null The character code, 0, or NULL. + */ + public function ord( $str ) { + if ( null === $str ) { + return null; + } + $str = (string) $str; + if ( '' === $str ) { + return 0; + } + /* + * MySQL computes ORD() from the bytes of the leftmost character, + * not from its Unicode code point: ORD('é') in utf8mb4 is + * (0xC3 * 256) + 0xA9 = 50089, not 233. + */ + $char = $this->char_substr( $str, 0, 1 ); + if ( '' === $char ) { + return ord( $str[0] ); + } + $code = 0; + foreach ( unpack( 'C*', $char ) as $byte ) { + $code = $code * 256 + $byte; + } + return $code; + } + + /** + * Decode the first UTF-8 character of a string into its codepoint. + * + * Returns NULL when the string does not start with a valid UTF-8 + * sequence. Used only when the mbstring extension is not loaded. + * + * @param string $str The input string. + * + * @return int|null The codepoint, or NULL. + */ + private function utf8_codepoint( $str ) { + $b0 = ord( $str[0] ); + if ( 0x80 > $b0 ) { + return $b0; + } + if ( 0xC0 === ( $b0 & 0xE0 ) ) { + $code = $b0 & 0x1F; + $expected = 1; + $min = 0x80; + } elseif ( 0xE0 === ( $b0 & 0xF0 ) ) { + $code = $b0 & 0x0F; + $expected = 2; + $min = 0x800; + } elseif ( 0xF0 === ( $b0 & 0xF8 ) ) { + $code = $b0 & 0x07; + $expected = 3; + $min = 0x10000; + } else { + return null; + } + if ( strlen( $str ) < $expected + 1 ) { + return null; + } + for ( $i = 1; $i <= $expected; $i++ ) { + $b = ord( $str[ $i ] ); + if ( 0x80 !== ( $b & 0xC0 ) ) { + return null; + } + $code = ( $code << 6 ) | ( $b & 0x3F ); + } + if ( $code < $min || 0x10FFFF < $code || ( 0xD800 <= $code && 0xDFFF >= $code ) ) { + return null; + } + return $code; + } + + /** + * Method to emulate MySQL STRCMP() function. + * + * Returns -1, 0, or 1 depending on whether $a is smaller than, equal + * to, or greater than $b. The comparison is byte-wise. Returns NULL + * when any argument is NULL. + * + * @param mixed $a The first string. + * @param mixed $b The second string. + * + * @return int|null -1, 0, 1, or NULL. + */ + public function strcmp( $a, $b ) { + if ( null === $a || null === $b ) { + return null; + } + $result = strcmp( (string) $a, (string) $b ); + if ( 0 > $result ) { + return -1; + } + if ( 0 < $result ) { + return 1; + } + return 0; + } + + /** + * Method to emulate MySQL FIND_IN_SET() function. + * + * Returns the 1-based position of $str in the comma-separated $strlist, + * or 0 when not found. Returns NULL when any argument is NULL. + * + * @param mixed $str The string to find. + * @param mixed $strlist The comma-separated list. + * + * @return int|null The position, 0, or NULL. + */ + public function find_in_set( $str, $strlist ) { + if ( null === $str || null === $strlist ) { + return null; + } + $str = (string) $str; + if ( false !== strpos( $str, ',' ) ) { + return 0; + } + $strlist = (string) $strlist; + if ( '' === $strlist ) { + return 0; + } + // MySQL compares with the column collation, which is + // case-insensitive by default. + foreach ( explode( ',', $strlist ) as $index => $part ) { + if ( 0 === strcasecmp( $part, $str ) ) { + return $index + 1; + } + } + return 0; + } + + /** + * Method to emulate MySQL ELT() function. + * + * Returns the Nth string of the argument list, counting from 1. Returns + * NULL when N is NULL, less than 1, or greater than the number of + * strings. + * + * @return mixed The Nth string, or NULL. + */ + public function elt() { + $args = func_get_args(); + $n = array_shift( $args ); + if ( null === $n ) { + return null; + } + $n = (int) round( (float) $n ); + if ( 1 > $n || $n > count( $args ) ) { + return null; + } + return $args[ $n - 1 ]; + } + + /** + * Method to emulate MySQL MAKE_SET() function. + * + * Returns a comma-separated string of the arguments that have a + * corresponding bit set in $bits. NULL arguments are skipped. Returns + * NULL when $bits is NULL. + * + * @return string|null The set string, or NULL. + */ + public function make_set() { + $args = func_get_args(); + $bits = array_shift( $args ); + if ( null === $bits ) { + return null; + } + $bits = (int) $bits; + $result = array(); + foreach ( $args as $index => $str ) { + if ( null === $str ) { + continue; + } + if ( ( $bits >> $index ) & 1 ) { + $result[] = $str; + } + } + return implode( ',', $result ); + } + + /** + * Method to emulate MySQL EXPORT_SET() function. + * + * Returns a string with one $on/$off word per examined bit, lowest bit + * first, joined with $separator. Examines $number_of_bits bits, 64 by + * default. Returns NULL when any argument is NULL. + * + * @param mixed $bits The bit vector. + * @param mixed $on The word for set bits. + * @param mixed $off The word for clear bits. + * @param mixed $separator The separator, defaults to ','. + * @param mixed $number_of_bits The number of bits, defaults to 64. + * + * @return string|null The bit string, or NULL. + */ + public function export_set( $bits, $on, $off, $separator = ',', $number_of_bits = 64 ) { + if ( 4 < func_num_args() && null === $number_of_bits ) { + return null; + } + if ( null === $bits || null === $on || null === $off || null === $separator ) { + return null; + } + $number_of_bits = (int) round( (float) $number_of_bits ); + if ( 1 > $number_of_bits ) { + return ''; + } + // MySQL clips the bit count to the width of a BIGINT. + if ( 64 < $number_of_bits ) { + $number_of_bits = 64; + } + $bits = (int) $bits; + $words = array(); + for ( $i = 0; $i < $number_of_bits; $i++ ) { + if ( ( $bits >> $i ) & 1 ) { + $words[] = $on; + } else { + $words[] = $off; + } + } + return implode( (string) $separator, $words ); + } + + /** + * Method to emulate MySQL TRUNCATE() function. + * + * Truncates toward zero to $decimals decimal places; a negative value + * zeroes digits to the left of the decimal point. Returns an integer + * when no fractional part remains, mirroring MySQL's result type. + * + * @param mixed $x The number to truncate. + * @param mixed $decimals The number of decimal places. + * + * @return int|float|null The truncated value, or NULL. + */ + public function truncate( $x, $decimals ) { + if ( null === $x || null === $decimals ) { + return null; + } + $decimals = (int) round( (float) $decimals ); + if ( is_bool( $x ) ) { + $x = (int) $x; + } + if ( ! is_numeric( $x ) ) { + $x = 0; + } + $value = (float) $x; + if ( ! is_finite( $value ) ) { + return null; + } + $factor = pow( 10, abs( $decimals ) ); + if ( ! is_finite( $factor ) ) { + return null; + } + $sign = $value < 0 ? -1 : 1; + $abs = abs( $value ); + if ( 0 <= $decimals ) { + $result = floor( $abs * $factor ) / $factor; + } else { + $result = floor( $abs / $factor ) * $factor; + } + $result *= $sign; + if ( 0 >= $decimals ) { + if ( $result > PHP_INT_MAX || $result < PHP_INT_MIN ) { + return $result; + } + return (int) $result; + } + return $result; + } + + /** + * Method to emulate MySQL SOUNDEX() function. + * + * Returns a soundex string of $str. Returns NULL when $str is NULL. + * + * @param string|null $str The input string. + * + * @return string|null The soundex string, or NULL. + */ + public function soundex( $str ) { + if ( null === $str ) { + return null; + } + return soundex( (string) $str ); + } + + /** + * Method to emulate MySQL FORMAT() function. + * + * Formats $number with thousands separators and $decimals decimals, + * rounding half away from zero. The optional $locale argument is + * accepted but only the default separators are produced. Returns NULL + * when any given argument is NULL. + * + * @param mixed $number The number to format. + * @param mixed $decimals The number of decimals. + * @param mixed|null $locale An optional locale name, ignored. + * + * @return string|null The formatted number, or NULL. + */ + public function format( $number, $decimals, $locale = null ) { + if ( 2 < func_num_args() && null === $locale ) { + return null; + } + if ( null === $number || null === $decimals ) { + return null; + } + $decimals = (int) round( (float) $decimals ); + if ( 0 > $decimals ) { + $decimals = 0; + } + return number_format( (float) $number, $decimals, '.', ',' ); + } + + /** + * Method to emulate the MySQL string function INSERT(). + * + * Returns $str with the substring beginning at 1-based position $pos + * and $len characters long replaced by $newstr. Returns the original + * $str when $pos is outside the string. A $len beyond the rest of the + * string replaces everything from $pos. Returns NULL when any argument + * is NULL. + * + * Registered as "insert_str" because INSERT is a reserved word that + * SQLite will not accept as a function name. + * + * @param string|null $str The input string. + * @param mixed $pos The 1-based position. + * @param mixed $len The number of characters to replace. + * @param string|null $newstr The replacement string. + * + * @return string|null The resulting string, or NULL. + */ + public function insert_str( $str, $pos, $len, $newstr ) { + if ( null === $str || null === $pos || null === $len || null === $newstr ) { + return null; + } + $str = (string) $str; + $newstr = (string) $newstr; + $pos = (int) round( (float) $pos ); + $len = (int) round( (float) $len ); + if ( 0 > $len ) { + $len = 0; + } + $strlen = $this->char_strlen( $str ); + if ( 1 > $pos || $pos > $strlen ) { + return $str; + } + return $this->char_substr( $str, 0, $pos - 1 ) + . $newstr + . $this->char_substr( $str, $pos - 1 + $len ); + } + /** * 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..b59f542cf 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 @@ -16291,4 +16291,539 @@ public function testReverseFunction(): void { $result = $this->assertQuery( 'SELECT REVERSE(NULL) AS reversed' ); $this->assertNull( $result[0]->reversed ); } + + public function testTruncateFunction(): void { + $result = $this->assertQuery( 'SELECT TRUNCATE(123.456, 1) AS t' ); + $this->assertSame( '123.4', $result[0]->t ); + + $result = $this->assertQuery( 'SELECT TRUNCATE(123.456, 2) AS t' ); + $this->assertSame( '123.45', $result[0]->t ); + + // Truncation is toward zero, like MySQL. + $result = $this->assertQuery( 'SELECT TRUNCATE(-1.29, 1) AS t' ); + $this->assertSame( '-1.2', $result[0]->t ); + + // Negative decimals truncate left of the decimal point. + $result = $this->assertQuery( 'SELECT TRUNCATE(123.456, -1) AS t' ); + $this->assertSame( '120', $result[0]->t ); + + $result = $this->assertQuery( 'SELECT TRUNCATE(123.456, 0) AS t' ); + $this->assertSame( '123', $result[0]->t ); + + // No rounding up, unlike ROUND(). + $result = $this->assertQuery( 'SELECT TRUNCATE(1.99, 1) AS t' ); + $this->assertSame( '1.9', $result[0]->t ); + + // NULL input returns NULL. + $result = $this->assertQuery( 'SELECT TRUNCATE(NULL, 1) AS t' ); + $this->assertNull( $result[0]->t ); + + $result = $this->assertQuery( 'SELECT TRUNCATE(123.456, NULL) AS t' ); + $this->assertNull( $result[0]->t ); + } + + public function testLcaseUcaseFunctions(): void { + // Regression test: these used to return the literal strings + // "lower(...)" and "upper(...)" instead of computing a value. + $result = $this->assertQuery( "SELECT LCASE('AbC') AS s" ); + $this->assertSame( 'abc', $result[0]->s ); + + $result = $this->assertQuery( "SELECT UCASE('AbC') AS s" ); + $this->assertSame( 'ABC', $result[0]->s ); + + $result = $this->assertQuery( "SELECT LOWER('AbC') AS s" ); + $this->assertSame( 'abc', $result[0]->s ); + + $result = $this->assertQuery( "SELECT UPPER('AbC') AS s" ); + $this->assertSame( 'ABC', $result[0]->s ); + + $result = $this->assertQuery( 'SELECT LCASE(NULL) AS s' ); + $this->assertNull( $result[0]->s ); + + $result = $this->assertQuery( 'SELECT UCASE(NULL) AS s' ); + $this->assertNull( $result[0]->s ); + } + + public function testPositionFunction(): void { + $result = $this->assertQuery( "SELECT POSITION('b' IN 'abc') AS p" ); + $this->assertSame( '2', $result[0]->p ); + + // Not found returns 0. + $result = $this->assertQuery( "SELECT POSITION('z' IN 'abc') AS p" ); + $this->assertSame( '0', $result[0]->p ); + + // NULL input returns NULL. + $result = $this->assertQuery( "SELECT POSITION(NULL IN 'abc') AS p" ); + $this->assertNull( $result[0]->p ); + + $result = $this->assertQuery( "SELECT POSITION('b' IN NULL) AS p" ); + $this->assertNull( $result[0]->p ); + + // Multi-byte needle. + $result = $this->assertQuery( "SELECT POSITION('é' IN 'héllo') AS p" ); + $this->assertSame( '2', $result[0]->p ); + } + + public function testLocateFunctionPositions(): void { + $result = $this->assertQuery( "SELECT LOCATE('b', 'abc') AS p" ); + $this->assertSame( '2', $result[0]->p ); + + // The start position is 1-based. + $result = $this->assertQuery( "SELECT LOCATE('b', 'abc', 1) AS p" ); + $this->assertSame( '2', $result[0]->p ); + + $result = $this->assertQuery( "SELECT LOCATE('b', 'abc', 2) AS p" ); + $this->assertSame( '2', $result[0]->p ); + + $result = $this->assertQuery( "SELECT LOCATE('b', 'abc', 3) AS p" ); + $this->assertSame( '0', $result[0]->p ); + + $result = $this->assertQuery( "SELECT LOCATE('bar', 'foobarbar', 6) AS p" ); + $this->assertSame( '7', $result[0]->p ); + + // NULL input returns NULL. + $result = $this->assertQuery( "SELECT LOCATE(NULL, 'abc') AS p" ); + $this->assertNull( $result[0]->p ); + + $result = $this->assertQuery( "SELECT LOCATE('b', NULL) AS p" ); + $this->assertNull( $result[0]->p ); + + $result = $this->assertQuery( "SELECT LOCATE('b', 'abc', NULL) AS p" ); + $this->assertNull( $result[0]->p ); + } + + public function testExtractFunction(): void { + $result = $this->assertQuery( "SELECT EXTRACT(YEAR FROM '2024-05-06 10:11:12') AS e" ); + $this->assertSame( '2024', $result[0]->e ); + + $result = $this->assertQuery( "SELECT EXTRACT(QUARTER FROM '2024-05-06') AS e" ); + $this->assertSame( '2', $result[0]->e ); + + $result = $this->assertQuery( "SELECT EXTRACT(QUARTER FROM '2024-01-01') AS e" ); + $this->assertSame( '1', $result[0]->e ); + + $result = $this->assertQuery( "SELECT EXTRACT(QUARTER FROM '2024-12-31') AS e" ); + $this->assertSame( '4', $result[0]->e ); + + $result = $this->assertQuery( "SELECT EXTRACT(MONTH FROM '2024-05-06') AS e" ); + $this->assertSame( '5', $result[0]->e ); + + $result = $this->assertQuery( "SELECT EXTRACT(WEEK FROM '2024-05-06') AS e" ); + $this->assertSame( '19', $result[0]->e ); + + $result = $this->assertQuery( "SELECT EXTRACT(DAY FROM '2024-05-06 10:11:12') AS e" ); + $this->assertSame( '6', $result[0]->e ); + + $result = $this->assertQuery( "SELECT EXTRACT(HOUR FROM '2024-05-06 10:11:12') AS e" ); + $this->assertSame( '10', $result[0]->e ); + + $result = $this->assertQuery( "SELECT EXTRACT(MINUTE FROM '2024-05-06 10:11:12') AS e" ); + $this->assertSame( '11', $result[0]->e ); + + $result = $this->assertQuery( "SELECT EXTRACT(SECOND FROM '2024-05-06 10:11:12') AS e" ); + $this->assertSame( '12', $result[0]->e ); + + $result = $this->assertQuery( "SELECT EXTRACT(MICROSECOND FROM '2024-05-06 10:00:00.123456') AS e" ); + $this->assertSame( '123456', $result[0]->e ); + + $result = $this->assertQuery( "SELECT EXTRACT(MICROSECOND FROM '2024-05-06 10:00:00.5') AS e" ); + $this->assertSame( '500000', $result[0]->e ); + + // No fractional seconds means zero microseconds. + $result = $this->assertQuery( "SELECT EXTRACT(MICROSECOND FROM '2024-05-06 10:00:00') AS e" ); + $this->assertSame( '0', $result[0]->e ); + + // NULL input returns NULL. + $result = $this->assertQuery( 'SELECT EXTRACT(MICROSECOND FROM NULL) AS e' ); + $this->assertNull( $result[0]->e ); + } + + public function testTrimExtendedForms(): void { + // The plain form keeps working. + $result = $this->assertQuery( "SELECT TRIM(' a ') AS s" ); + $this->assertSame( 'a', $result[0]->s ); + + $result = $this->assertQuery( "SELECT TRIM(BOTH ' ' FROM ' a ') AS s" ); + $this->assertSame( 'a', $result[0]->s ); + + $result = $this->assertQuery( "SELECT TRIM(BOTH 'x' FROM 'xxabxx') AS s" ); + $this->assertSame( 'ab', $result[0]->s ); + + $result = $this->assertQuery( "SELECT TRIM(BOTH FROM ' a ') AS s" ); + $this->assertSame( 'a', $result[0]->s ); + + $result = $this->assertQuery( "SELECT TRIM(LEADING FROM ' a ') AS s" ); + $this->assertSame( 'a ', $result[0]->s ); + + $result = $this->assertQuery( "SELECT TRIM(LEADING 'x' FROM 'xxabx') AS s" ); + $this->assertSame( 'abx', $result[0]->s ); + + $result = $this->assertQuery( "SELECT TRIM(TRAILING FROM ' a ') AS s" ); + $this->assertSame( ' a', $result[0]->s ); + + $result = $this->assertQuery( "SELECT TRIM(TRAILING 'x' FROM 'xabxx') AS s" ); + $this->assertSame( 'xab', $result[0]->s ); + + // A custom trim string without an explicit specifier. + $result = $this->assertQuery( "SELECT TRIM('x' FROM 'xxabxx') AS s" ); + $this->assertSame( 'ab', $result[0]->s ); + } + + public function testStringInsertFunction(): void { + $result = $this->assertQuery( "SELECT INSERT('Quadratic', 3, 4, 'What') AS s" ); + $this->assertSame( 'QuWhattic', $result[0]->s ); + + // A length beyond the rest of the string replaces everything after pos. + $result = $this->assertQuery( "SELECT INSERT('abc', 2, 99, 'X') AS s" ); + $this->assertSame( 'aX', $result[0]->s ); + + // A position outside the string returns the original string. + $result = $this->assertQuery( "SELECT INSERT('abc', 0, 1, 'X') AS s" ); + $this->assertSame( 'abc', $result[0]->s ); + + $result = $this->assertQuery( "SELECT INSERT('abc', 9, 1, 'X') AS s" ); + $this->assertSame( 'abc', $result[0]->s ); + + // Multi-byte positions count characters. + $result = $this->assertQuery( "SELECT INSERT('héllo', 2, 2, 'X') AS s" ); + $this->assertSame( 'hXlo', $result[0]->s ); + + // NULL input returns NULL. + $result = $this->assertQuery( "SELECT INSERT(NULL, 1, 1, 'X') AS s" ); + $this->assertNull( $result[0]->s ); + + $result = $this->assertQuery( "SELECT INSERT('abc', NULL, 1, 'X') AS s" ); + $this->assertNull( $result[0]->s ); + + $result = $this->assertQuery( "SELECT INSERT('abc', 1, NULL, 'X') AS s" ); + $this->assertNull( $result[0]->s ); + + $result = $this->assertQuery( "SELECT INSERT('abc', 1, 1, NULL) AS s" ); + $this->assertNull( $result[0]->s ); + } + + public function testRepeatFunction(): void { + $result = $this->assertQuery( "SELECT REPEAT('ab', 3) AS s" ); + $this->assertSame( 'ababab', $result[0]->s ); + + // A count below 1 returns an empty string. + $result = $this->assertQuery( "SELECT REPEAT('ab', 0) AS s" ); + $this->assertSame( '', $result[0]->s ); + + $result = $this->assertQuery( "SELECT REPEAT('ab', -2) AS s" ); + $this->assertSame( '', $result[0]->s ); + + // NULL input returns NULL. + $result = $this->assertQuery( 'SELECT REPEAT(NULL, 3) AS s' ); + $this->assertNull( $result[0]->s ); + + $result = $this->assertQuery( "SELECT REPEAT('ab', NULL) AS s" ); + $this->assertNull( $result[0]->s ); + } + + public function testRightFunction(): void { + $result = $this->assertQuery( "SELECT RIGHT('abcde', 2) AS s" ); + $this->assertSame( 'de', $result[0]->s ); + + // A length beyond the string returns the whole string. + $result = $this->assertQuery( "SELECT RIGHT('abc', 9) AS s" ); + $this->assertSame( 'abc', $result[0]->s ); + + // Multi-byte characters are not split. + $result = $this->assertQuery( "SELECT RIGHT('héllo', 2) AS s" ); + $this->assertSame( 'lo', $result[0]->s ); + + // A length below 1 returns an empty string. + $result = $this->assertQuery( "SELECT RIGHT('abc', 0) AS s" ); + $this->assertSame( '', $result[0]->s ); + + // NULL input returns NULL. + $result = $this->assertQuery( 'SELECT RIGHT(NULL, 1) AS s' ); + $this->assertNull( $result[0]->s ); + + $result = $this->assertQuery( "SELECT RIGHT('abc', NULL) AS s" ); + $this->assertNull( $result[0]->s ); + } + + public function testPadFunctions(): void { + $result = $this->assertQuery( "SELECT LPAD('hi', 5, 'xy') AS s" ); + $this->assertSame( 'xyxhi', $result[0]->s ); + + $result = $this->assertQuery( "SELECT RPAD('hi', 5, 'xy') AS s" ); + $this->assertSame( 'hixyx', $result[0]->s ); + + // Longer strings are truncated. + $result = $this->assertQuery( "SELECT LPAD('hello', 3, 'xy') AS s" ); + $this->assertSame( 'hel', $result[0]->s ); + + $result = $this->assertQuery( "SELECT RPAD('hello', 3, 'xy') AS s" ); + $this->assertSame( 'hel', $result[0]->s ); + + // Padding counts characters, not bytes. + $result = $this->assertQuery( "SELECT LPAD('é', 3, 'ab') AS s" ); + $this->assertSame( 'abé', $result[0]->s ); + + $result = $this->assertQuery( "SELECT RPAD('é', 3, 'ab') AS s" ); + $this->assertSame( 'éab', $result[0]->s ); + + // A zero length returns an empty string. + $result = $this->assertQuery( "SELECT LPAD('hi', 0, 'x') AS s" ); + $this->assertSame( '', $result[0]->s ); + + // A negative length returns NULL. + $result = $this->assertQuery( "SELECT LPAD('hi', -1, 'x') AS s" ); + $this->assertNull( $result[0]->s ); + + $result = $this->assertQuery( "SELECT RPAD('hi', -1, 'x') AS s" ); + $this->assertNull( $result[0]->s ); + + // NULL input returns NULL. + $result = $this->assertQuery( "SELECT LPAD(NULL, 3, 'x') AS s" ); + $this->assertNull( $result[0]->s ); + + $result = $this->assertQuery( "SELECT RPAD('hi', NULL, 'x') AS s" ); + $this->assertNull( $result[0]->s ); + + $result = $this->assertQuery( "SELECT RPAD('hi', 5, NULL) AS s" ); + $this->assertNull( $result[0]->s ); + } + + public function testSpaceFunction(): void { + $result = $this->assertQuery( 'SELECT SPACE(3) AS s' ); + $this->assertSame( ' ', $result[0]->s ); + + $result = $this->assertQuery( 'SELECT SPACE(0) AS s' ); + $this->assertSame( '', $result[0]->s ); + + // NULL input returns NULL. + $result = $this->assertQuery( 'SELECT SPACE(NULL) AS s' ); + $this->assertNull( $result[0]->s ); + } + + public function testAsciiFunction(): void { + $result = $this->assertQuery( "SELECT ASCII('A') AS n" ); + $this->assertSame( '65', $result[0]->n ); + + // An empty string returns 0. + $result = $this->assertQuery( "SELECT ASCII('') AS n" ); + $this->assertSame( '0', $result[0]->n ); + + // NULL input returns NULL. + $result = $this->assertQuery( 'SELECT ASCII(NULL) AS n' ); + $this->assertNull( $result[0]->n ); + } + + public function testOrdFunction(): void { + $result = $this->assertQuery( "SELECT ORD('A') AS n" ); + $this->assertSame( '65', $result[0]->n ); + + // Multi-byte characters are composed from their bytes, as MySQL + // does: ORD('©') in utf8mb4 is (0xC2 * 256) + 0xA9 = 49833. + $result = $this->assertQuery( "SELECT ORD('©') AS n" ); + $this->assertSame( '49833', $result[0]->n ); + + $result = $this->assertQuery( "SELECT ORD('é') AS n" ); + $this->assertSame( '50089', $result[0]->n ); + + // An empty string returns 0. + $result = $this->assertQuery( "SELECT ORD('') AS n" ); + $this->assertSame( '0', $result[0]->n ); + + // NULL input returns NULL. + $result = $this->assertQuery( 'SELECT ORD(NULL) AS n' ); + $this->assertNull( $result[0]->n ); + } + + public function testLocateEdgeCases(): void { + // A start position past the end returns 0 instead of throwing. + $result = $this->assertQuery( "SELECT LOCATE('b', 'abc', 10) AS n" ); + $this->assertSame( '0', $result[0]->n ); + + // An empty needle returns the start position. + $result = $this->assertQuery( "SELECT LOCATE('', 'abc') AS n" ); + $this->assertSame( '1', $result[0]->n ); + + $result = $this->assertQuery( "SELECT LOCATE('', 'abc', 3) AS n" ); + $this->assertSame( '3', $result[0]->n ); + } + + public function testFindInSetCollation(): void { + // Default column collations are case-insensitive in MySQL. + $result = $this->assertQuery( "SELECT FIND_IN_SET('B', 'a,b,c') AS n" ); + $this->assertSame( '2', $result[0]->n ); + + $result = $this->assertQuery( "SELECT FIND_IN_SET('', '') AS n" ); + $this->assertSame( '0', $result[0]->n ); + } + + public function testExportSetBitLimit(): void { + // MySQL clips number_of_bits at 64. + $result = $this->assertQuery( "SELECT EXPORT_SET(5, 'Y', 'N', ',', 100) AS e" ); + $this->assertSame( 64, substr_count( $result[0]->e, ',' ) + 1 ); + } + + public function testRepeatSizeLimit(): void { + /* + * Results above 64 MiB return NULL instead of exhausting the PHP + * memory limit. Arguments above the 32-bit range are not usable for + * this: the PDO UDF bridge truncates integer arguments to 32 bits, + * so REPEAT('a', 4000000000) arrives as a negative count and yields + * an empty string, as MySQL does for any negative count. + */ + $result = $this->assertQuery( 'SELECT REPEAT(\'a\', 67108865) AS r' ); + $this->assertNull( $result[0]->r ); + + $result = $this->assertQuery( 'SELECT SPACE(67108865) AS r' ); + $this->assertNull( $result[0]->r ); + + $result = $this->assertQuery( "SELECT LPAD('a', 67108865, 'x') AS r" ); + $this->assertNull( $result[0]->r ); + + $result = $this->assertQuery( "SELECT RPAD('a', 67108865, 'x') AS r" ); + $this->assertNull( $result[0]->r ); + + // Small results are unaffected. + $result = $this->assertQuery( "SELECT REPEAT('ab', 2) AS r" ); + $this->assertSame( 'abab', $result[0]->r ); + } + + public function testStrcmpFunction(): void { + $result = $this->assertQuery( "SELECT STRCMP('a', 'b') AS n" ); + $this->assertSame( '-1', $result[0]->n ); + + $result = $this->assertQuery( "SELECT STRCMP('b', 'a') AS n" ); + $this->assertSame( '1', $result[0]->n ); + + $result = $this->assertQuery( "SELECT STRCMP('a', 'a') AS n" ); + $this->assertSame( '0', $result[0]->n ); + + // NULL input returns NULL. + $result = $this->assertQuery( "SELECT STRCMP(NULL, 'a') AS n" ); + $this->assertNull( $result[0]->n ); + + $result = $this->assertQuery( "SELECT STRCMP('a', NULL) AS n" ); + $this->assertNull( $result[0]->n ); + } + + public function testFindInSetFunction(): void { + $result = $this->assertQuery( "SELECT FIND_IN_SET('b', 'a,b,c') AS p" ); + $this->assertSame( '2', $result[0]->p ); + + // Missing values return 0. + $result = $this->assertQuery( "SELECT FIND_IN_SET('d', 'a,b,c') AS p" ); + $this->assertSame( '0', $result[0]->p ); + + // The needle must match a whole element. + $result = $this->assertQuery( "SELECT FIND_IN_SET('b', 'abc') AS p" ); + $this->assertSame( '0', $result[0]->p ); + + // NULL input returns NULL. + $result = $this->assertQuery( "SELECT FIND_IN_SET(NULL, 'a,b') AS p" ); + $this->assertNull( $result[0]->p ); + + $result = $this->assertQuery( "SELECT FIND_IN_SET('a', NULL) AS p" ); + $this->assertNull( $result[0]->p ); + } + + public function testFindInSetFunctionWithUserVariable(): void { + $this->assertQuery( "SET @csv = 'a,b,c'" ); + + $result = $this->assertQuery( "SELECT FIND_IN_SET('b', @csv) AS p" ); + $this->assertSame( '2', $result[0]->p ); + + $result = $this->assertQuery( "SELECT FIND_IN_SET('d', @csv) AS p" ); + $this->assertSame( '0', $result[0]->p ); + } + + public function testEltFunction(): void { + $result = $this->assertQuery( "SELECT ELT(2, 'a', 'b', 'c') AS s" ); + $this->assertSame( 'b', $result[0]->s ); + + // Out-of-range positions return NULL. + $result = $this->assertQuery( "SELECT ELT(0, 'a', 'b') AS s" ); + $this->assertNull( $result[0]->s ); + + $result = $this->assertQuery( "SELECT ELT(3, 'a', 'b') AS s" ); + $this->assertNull( $result[0]->s ); + + // NULL input returns NULL. + $result = $this->assertQuery( "SELECT ELT(NULL, 'a', 'b') AS s" ); + $this->assertNull( $result[0]->s ); + } + + public function testMakeSetFunction(): void { + $result = $this->assertQuery( "SELECT MAKE_SET(1 | 4, 'a', 'b', 'c') AS s" ); + $this->assertSame( 'a,c', $result[0]->s ); + + // No bits set returns an empty string. + $result = $this->assertQuery( "SELECT MAKE_SET(0, 'a', 'b') AS s" ); + $this->assertSame( '', $result[0]->s ); + + // NULL strings are skipped. + $result = $this->assertQuery( "SELECT MAKE_SET(7, 'a', NULL, 'c') AS s" ); + $this->assertSame( 'a,c', $result[0]->s ); + + // NULL input returns NULL. + $result = $this->assertQuery( "SELECT MAKE_SET(NULL, 'a', 'b') AS s" ); + $this->assertNull( $result[0]->s ); + } + + public function testExportSetFunction(): void { + $result = $this->assertQuery( "SELECT EXPORT_SET(5, 'Y', 'N', ',', 4) AS s" ); + $this->assertSame( 'Y,N,Y,N', $result[0]->s ); + + $result = $this->assertQuery( "SELECT EXPORT_SET(5, 'Y', 'N', '|', 2) AS s" ); + $this->assertSame( 'Y|N', $result[0]->s ); + + // The default separator is a comma and the default bit count is 64. + $result = $this->assertQuery( "SELECT EXPORT_SET(1, 'Y', 'N', ',', 1) AS s" ); + $this->assertSame( 'Y', $result[0]->s ); + + // NULL input returns NULL. + $result = $this->assertQuery( "SELECT EXPORT_SET(NULL, 'Y', 'N') AS s" ); + $this->assertNull( $result[0]->s ); + + $result = $this->assertQuery( "SELECT EXPORT_SET(5, NULL, 'N') AS s" ); + $this->assertNull( $result[0]->s ); + } + + public function testSoundexFunction(): void { + $result = $this->assertQuery( "SELECT SOUNDEX('Euler') AS s" ); + $this->assertSame( 'E460', $result[0]->s ); + + $result = $this->assertQuery( "SELECT SOUNDEX('Ellery') AS s" ); + $this->assertSame( 'E460', $result[0]->s ); + + $result = $this->assertQuery( "SELECT SOUNDEX('Tymczak') AS s" ); + $this->assertSame( 'T522', $result[0]->s ); + + // NULL input returns NULL. + $result = $this->assertQuery( 'SELECT SOUNDEX(NULL) AS s' ); + $this->assertNull( $result[0]->s ); + } + + public function testFormatFunction(): void { + // Regression test: this used to return "1234567.89" without the + // thousands separators, because SQLite's printf-style format() + // was used instead of MySQL's FORMAT(). + $result = $this->assertQuery( 'SELECT FORMAT(1234567.89, 2) AS s' ); + $this->assertSame( '1,234,567.89', $result[0]->s ); + + $result = $this->assertQuery( 'SELECT FORMAT(1234.5, 0) AS s' ); + $this->assertSame( '1,235', $result[0]->s ); + + // Rounding is half away from zero, like MySQL. + $result = $this->assertQuery( 'SELECT FORMAT(-2.5, 0) AS s' ); + $this->assertSame( '-3', $result[0]->s ); + + $result = $this->assertQuery( 'SELECT FORMAT(123456789.123, 2) AS s' ); + $this->assertSame( '123,456,789.12', $result[0]->s ); + + // NULL input returns NULL. + $result = $this->assertQuery( 'SELECT FORMAT(NULL, 2) AS s' ); + $this->assertNull( $result[0]->s ); + + $result = $this->assertQuery( 'SELECT FORMAT(1234.5, NULL) AS s' ); + $this->assertNull( $result[0]->s ); + } } 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..a10f172f4 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 @@ -1778,6 +1778,142 @@ public function testConcatFunction(): void { ); } + public function testTruncateFunction(): void { + // TRUNCATE() delegates to a UDF: SQLite's TRUNC() takes one argument + // and POW() is missing from older supported SQLite builds. + $this->assertQuery( + 'SELECT truncate(123.456, 1) AS `TRUNCATE(123.456, 1)`', + 'SELECT TRUNCATE(123.456, 1)' + ); + + $this->assertQuery( + 'SELECT truncate(123.456, 0) AS `TRUNCATE(123.456)`', + 'SELECT TRUNCATE(123.456)' + ); + } + + public function testRightFunctionTranslation(): void { + // RIGHT is a join keyword in newer SQLite versions, so it cannot be + // called as a function; it maps to a non-reserved UDF name. + $this->assertQuery( + "SELECT right_str('abc', 1) AS `RIGHT('abc', 1)`", + "SELECT RIGHT('abc', 1)" + ); + } + + public function testLcaseUcaseFunctions(): void { + // LCASE() and UCASE() map to SQLite LOWER() and UPPER(). They used + // to resolve to UDFs returning the literal strings "lower(...)" + // and "upper(...)" instead of computing a value. + $this->assertQuery( + "SELECT LOWER('AbC') AS `LCASE('AbC')`", + "SELECT LCASE('AbC')" + ); + + $this->assertQuery( + "SELECT UPPER('AbC') AS `UCASE('AbC')`", + "SELECT UCASE('AbC')" + ); + } + + public function testPositionFunction(): void { + $this->assertQuery( + "SELECT locate('b', 'abc') AS `POSITION('b' IN 'abc')`", + "SELECT POSITION('b' IN 'abc')" + ); + } + + public function testExtractFunction(): void { + $this->assertQuery( + "SELECT year('2024-05-06') AS `EXTRACT(YEAR FROM '2024-05-06')`", + "SELECT EXTRACT(YEAR FROM '2024-05-06')" + ); + + $this->assertQuery( + "SELECT CAST(((CAST(STRFTIME('%m', '2024-05-06') AS INTEGER) + 2) / 3) AS INTEGER) AS `EXTRACT(QUARTER FROM '2024-05-06')`", + "SELECT EXTRACT(QUARTER FROM '2024-05-06')" + ); + + $this->assertQuery( + "SELECT month('2024-05-06') AS `EXTRACT(MONTH FROM '2024-05-06')`", + "SELECT EXTRACT(MONTH FROM '2024-05-06')" + ); + + $this->assertQuery( + "SELECT week('2024-05-06', 0) AS `EXTRACT(WEEK FROM '2024-05-06')`", + "SELECT EXTRACT(WEEK FROM '2024-05-06')" + ); + + $this->assertQuery( + "SELECT day('2024-05-06') AS `EXTRACT(DAY FROM '2024-05-06')`", + "SELECT EXTRACT(DAY FROM '2024-05-06')" + ); + + $this->assertQuery( + "SELECT hour('2024-05-06 10:11:12') AS `EXTRACT(HOUR FROM '2024-05-06 10:11:12')`", + "SELECT EXTRACT(HOUR FROM '2024-05-06 10:11:12')" + ); + + $this->assertQuery( + "SELECT minute('2024-05-06 10:11:12') AS `EXTRACT(MINUTE FROM '2024-05-06 10:11:12')`", + "SELECT EXTRACT(MINUTE FROM '2024-05-06 10:11:12')" + ); + + $this->assertQuery( + "SELECT second('2024-05-06 10:11:12') AS `EXTRACT(SECOND FROM '2024-05-06 10:11:12')`", + "SELECT EXTRACT(SECOND FROM '2024-05-06 10:11:12')" + ); + + $this->assertQuery( + "SELECT CASE WHEN ('2024-05-06 10:00:00.5') IS NULL THEN NULL WHEN INSTR(('2024-05-06 10:00:00.5'), '.') > 0 THEN CAST(SUBSTR(('2024-05-06 10:00:00.5') || '000000', INSTR(('2024-05-06 10:00:00.5'), '.') + 1, 6) AS INTEGER) ELSE 0 END AS `EXTRACT(MICROSECOND FROM '2024-05-06 10:00:00.5')`", + "SELECT EXTRACT(MICROSECOND FROM '2024-05-06 10:00:00.5')" + ); + } + + public function testTrimExtendedForms(): void { + $this->assertQuery( + "SELECT TRIM(' a ')", + "SELECT TRIM(' a ')" + ); + + $this->assertQuery( + "SELECT TRIM(' a ', ' ') AS `TRIM(BOTH ' ' FROM ' a ')`", + "SELECT TRIM(BOTH ' ' FROM ' a ')" + ); + + $this->assertQuery( + "SELECT TRIM('xxabxx', 'x') AS `TRIM('x' FROM 'xxabxx')`", + "SELECT TRIM('x' FROM 'xxabxx')" + ); + + $this->assertQuery( + "SELECT LTRIM(' a ') AS `TRIM(LEADING FROM ' a ')`", + "SELECT TRIM(LEADING FROM ' a ')" + ); + + $this->assertQuery( + "SELECT LTRIM('xxabx', 'x') AS `TRIM(LEADING 'x' FROM 'xxabx')`", + "SELECT TRIM(LEADING 'x' FROM 'xxabx')" + ); + + $this->assertQuery( + "SELECT RTRIM(' a ') AS `TRIM(TRAILING FROM ' a ')`", + "SELECT TRIM(TRAILING FROM ' a ')" + ); + + $this->assertQuery( + "SELECT RTRIM('xabxx', 'x') AS `TRIM(TRAILING 'x' FROM 'xabxx')`", + "SELECT TRIM(TRAILING 'x' FROM 'xabxx')" + ); + } + + public function testStringInsertFunction(): void { + $this->assertQuery( + "SELECT insert_str('Quadratic', 3, 4, 'What') AS `INSERT('Quadratic', 3, 4, 'What')`", + "SELECT INSERT('Quadratic', 3, 4, 'What')" + ); + } + public function testIntervalArithmeticInParentheses(): void { // TODO: With LALR(1), also test these expressions without parentheses. // Parentheses prevent the parser from treating this as a prefix interval.