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 ce49a9bc0..19cacd0f0 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 @@ -4602,6 +4602,9 @@ private function translate_token( WP_MySQL_Token $token ): ?string { return $value; case WP_MySQL_Lexer::AUTO_INCREMENT_SYMBOL: return 'AUTOINCREMENT'; + case WP_MySQL_Lexer::NULL_SAFE_EQUAL_OPERATOR: + // The MySQL null-safe equality "<=>" is "IS" in SQLite. + return 'IS'; case WP_MySQL_Lexer::BINARY_SYMBOL: /* * "BINARY expr" is translated in "translate_simple_expr_body()". @@ -5360,6 +5363,15 @@ private function translate_function_call( WP_Parser_Node $node ): string { return sprintf( 'CAST(STRFTIME(%s, %s) AS FLOAT)', $format, $date ); } return sprintf( 'STRFTIME(%s, %s)', $format, $date ); + case 'JSON_UNQUOTE': + $argument_nodes = isset( $nodes[1] ) ? $nodes[1]->get_child_nodes() : array(); + if ( 1 === count( $argument_nodes ) ) { + $json_extract_args = $this->get_direct_function_call_arguments( $argument_nodes[0], 'JSON_EXTRACT' ); + if ( is_array( $json_extract_args ) && count( $json_extract_args ) >= 2 ) { + return sprintf( '_helper_json_unquote_extract(%s)', implode( ', ', $json_extract_args ) ); + } + } + return $this->translate_sequence( $node->get_children() ); case 'CHAR_LENGTH': // @TODO LENGTH and CHAR_LENGTH aren't always the same in MySQL for utf8 characters. return 'LENGTH(' . $args[0] . ')'; @@ -5388,6 +5400,39 @@ private function translate_function_call( WP_Parser_Node $node ): string { } } + /** + * Get the arguments to a function call when it is the entire expression. + * + * @param WP_Parser_Node $expression The expression to inspect. + * @param string $function_name The expected function name. + * @return array|null The translated arguments, or NULL when the expression differs. + */ + private function get_direct_function_call_arguments( WP_Parser_Node $expression, string $function_name ): ?array { + $node = $expression; + while ( 'functionCall' !== $node->rule_name ) { + $children = $node->get_children(); + if ( 1 !== count( $children ) || ! $children[0] instanceof WP_Parser_Node ) { + return null; + } + $node = $children[0]; + } + + $function_nodes = $node->get_child_nodes(); + if ( ! isset( $function_nodes[0] ) || ! isset( $function_nodes[1] ) ) { + return null; + } + $name = strtoupper( $this->unquote_sqlite_identifier( $this->translate( $function_nodes[0] ) ) ); + if ( $function_name !== $name ) { + return null; + } + + $args = array(); + foreach ( $function_nodes[1]->get_child_nodes() as $argument ) { + $args[] = $this->translate( $argument ); + } + return $args; + } + /** * 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..3177fbc6d 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 @@ -81,8 +81,13 @@ public static function register_for( $pdo ): self { 'utc_timestamp' => 'utc_timestamp', 'version' => 'version', 'reverse' => 'reverse', + 'json_unquote' => 'json_unquote', + 'json_contains' => 'json_contains', + 'json_length' => 'json_length', + 'json_merge_patch' => 'json_merge_patch', // Internal helper functions. + '_helper_json_unquote_extract' => 'json_unquote_extract', '_helper_like_to_glob_pattern' => '_helper_like_to_glob_pattern', ); @@ -927,6 +932,428 @@ public function reverse( $str ) { return strrev( $str ); } + /** + * Method to emulate MySQL JSON_UNQUOTE() function. + * + * A value that starts and ends with a double quote is decoded as a JSON string. + * Any other value is returned unchanged, as MySQL does. + * + * SQLite's json_extract() already returns strings unquoted, whereas MySQL's + * JSON_EXTRACT() returns them quoted. So JSON_UNQUOTE( JSON_EXTRACT( ... ) ) + * is translated to an internal helper that preserves extracted strings, + * including strings that begin and end with literal double quotes. + * + * @param string|null $json The JSON string literal to unquote. + * + * @throws Exception When the value looks like a JSON string but is not valid JSON. + * @return string|null The unquoted string, or NULL. + */ + public function json_unquote( $json ) { + if ( null === $json ) { + return null; + } + $json = (string) $json; + if ( strlen( $json ) < 2 || '"' !== $json[0] || '"' !== substr( $json, -1 ) ) { + return $json; + } + $decoded = json_decode( $json ); + if ( JSON_ERROR_NONE !== json_last_error() || ! is_string( $decoded ) ) { + throw new Exception( 'Invalid JSON text in argument 1 to function json_unquote.' ); + } + return $decoded; + } + + /** + * Emulate JSON_UNQUOTE(JSON_EXTRACT(document, path...)) without losing quotes + * that are part of an extracted JSON string. + * + * @param string|null $json The JSON document. + * @param string|null ...$paths The JSON paths to extract. + * + * @throws Exception When the document or path is invalid or unsupported. + * @return string|null The extracted value, or NULL when no path matches or an argument is NULL. + */ + public function json_unquote_extract( $json ) { + $arguments = func_get_args(); + if ( count( $arguments ) < 2 || null === $arguments[0] ) { + return null; + } + + $document = $this->json_decode_argument( $arguments[0], 1, 'json_extract' ); + $paths = array_slice( $arguments, 1 ); + foreach ( $paths as $path ) { + if ( null === $path ) { + return null; + } + } + + if ( 1 === count( $paths ) ) { + $result = $this->json_find_path( $document, $paths[0], 'json_extract' ); + if ( ! $result[0] ) { + return null; + } + $value = $result[1]; + } else { + $values = array(); + foreach ( $paths as $path ) { + $result = $this->json_find_path( $document, $path, 'json_extract' ); + if ( $result[0] ) { + $values[] = $result[1]; + } + } + return empty( $values ) ? null : $this->json_encode_value( $values ); + } + + if ( is_string( $value ) ) { + return $value; + } + if ( is_bool( $value ) ) { + return $value ? 'true' : 'false'; + } + if ( null === $value ) { + return 'null'; + } + if ( is_array( $value ) || is_object( $value ) ) { + return $this->json_encode_value( $value ); + } + return (string) $value; + } + + /** + * Method to emulate MySQL JSON_CONTAINS() function. + * + * @param string|null $target The JSON document to search. + * @param string|null $candidate The JSON value to look for. + * @param string|null $path Optional path to the part of the target to search. + * + * @throws Exception When an argument is not valid JSON or the path is not supported. + * @return int|null 1 if the candidate is contained, 0 if not, NULL if an argument is NULL + * or the path does not exist. + */ + public function json_contains( $target, $candidate, $path = null ) { + if ( null === $target || null === $candidate || ( func_num_args() > 2 && null === $path ) ) { + return null; + } + $target_value = $this->json_decode_argument( $target, 1, 'json_contains' ); + $candidate_value = $this->json_decode_argument( $candidate, 2, 'json_contains' ); + + if ( func_num_args() > 2 ) { + $target_value = $this->json_find_path( $target_value, $path, 'json_contains' ); + if ( ! $target_value[0] ) { + return null; + } + $target_value = $target_value[1]; + } + return $this->json_value_contains( $target_value, $candidate_value ) ? 1 : 0; + } + + /** + * Method to emulate MySQL JSON_LENGTH() function. + * + * @param string|null $json The JSON document. + * @param string|null $path Optional path to the part of the document to measure. + * + * @throws Exception When the document is not valid JSON or the path is not supported. + * @return int|null The number of elements of an array or object, 1 for a scalar, + * or NULL if an argument is NULL or the path does not exist. + */ + public function json_length( $json, $path = null ) { + if ( null === $json || ( func_num_args() > 1 && null === $path ) ) { + return null; + } + $value = $this->json_decode_argument( $json, 1, 'json_length' ); + + if ( func_num_args() > 1 ) { + $value = $this->json_find_path( $value, $path, 'json_length' ); + if ( ! $value[0] ) { + return null; + } + $value = $value[1]; + } + if ( is_array( $value ) ) { + return count( $value ); + } + if ( is_object( $value ) ) { + return count( get_object_vars( $value ) ); + } + return 1; + } + + /** + * Method to emulate MySQL JSON_MERGE_PATCH() function (RFC 7396). + * + * @param string|null ...$documents Two or more JSON documents; later ones patch earlier ones. + * + * @throws Exception When an argument is not valid JSON. + * @return string|null The merged document, or NULL if a SQL NULL is followed only by object patches. + */ + public function json_merge_patch() { + $documents = func_get_args(); + if ( count( $documents ) < 2 ) { + throw new Exception( 'Incorrect parameter count in the call to native function \'json_merge_patch\'.' ); + } + $result = null; + $has_result = false; + $is_unknown = false; + foreach ( $documents as $index => $document ) { + if ( null === $document ) { + $result = null; + $has_result = true; + $is_unknown = true; + continue; + } + + $value = $this->json_decode_argument( $document, $index + 1, 'json_merge_patch' ); + if ( ! $has_result ) { + $result = $value; + $has_result = true; + continue; + } + if ( ! is_object( $value ) ) { + $result = $value; + $is_unknown = false; + continue; + } + if ( ! $is_unknown ) { + $result = $this->json_apply_patch( $result, $value ); + } + } + return $is_unknown ? null : $this->json_encode_value( $result ); + } + + /** + * Decode a JSON function argument, failing the way MySQL does on invalid input. + * + * @param string $json The JSON text. + * @param int $position The 1-based argument position, for the error message. + * @param string $function_name The function name, for the error message. + * + * @throws Exception When the text is not valid JSON. + * @return mixed The decoded value. + */ + private function json_decode_argument( $json, int $position, string $function_name ) { + $value = json_decode( (string) $json ); + if ( null === $value && JSON_ERROR_NONE !== json_last_error() ) { + throw new Exception( + sprintf( 'Invalid JSON text in argument %d to function %s.', $position, $function_name ) + ); + } + return $value; + } + + /** + * Whether a candidate JSON value is contained in a target value, per the MySQL rules: + * a candidate array needs each of its elements contained in some target element; + * a candidate object needs each key present with a contained value; a candidate scalar + * must equal the target scalar, or be contained in some element of a target array. + * + * @param mixed $target The decoded target value. + * @param mixed $candidate The decoded candidate value. + * + * @return bool + */ + private function json_value_contains( $target, $candidate ): bool { + if ( is_array( $target ) ) { + if ( is_array( $candidate ) ) { + foreach ( $candidate as $candidate_element ) { + $found = false; + foreach ( $target as $target_element ) { + if ( $this->json_value_contains( $target_element, $candidate_element ) ) { + $found = true; + break; + } + } + if ( ! $found ) { + return false; + } + } + return true; + } + foreach ( $target as $target_element ) { + if ( $this->json_value_contains( $target_element, $candidate ) ) { + return true; + } + } + return false; + } + if ( is_object( $target ) ) { + if ( ! is_object( $candidate ) ) { + return false; + } + $target_members = get_object_vars( $target ); + foreach ( get_object_vars( $candidate ) as $key => $candidate_member ) { + if ( ! array_key_exists( $key, $target_members ) + || ! $this->json_value_contains( $target_members[ $key ], $candidate_member ) ) { + return false; + } + } + return true; + } + if ( is_array( $candidate ) || is_object( $candidate ) ) { + return false; + } + return $this->json_scalars_equal( $target, $candidate ); + } + + /** + * Compare two JSON scalars. Numbers compare by value, and a number never equals a + * string or a boolean. + * + * @param mixed $a A decoded scalar. + * @param mixed $b A decoded scalar. + * + * @return bool + */ + private function json_scalars_equal( $a, $b ): bool { + if ( is_bool( $a ) || is_bool( $b ) || is_string( $a ) || is_string( $b ) ) { + return $a === $b; + } + if ( null === $a || null === $b ) { + return $a === $b; + } + return $a == $b; // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual -- int and float compare by value. + } + + /** + * Apply an RFC 7396 merge patch to a decoded value. + * + * @param mixed $target The decoded target. + * @param mixed $patch The decoded patch. + * + * @return mixed The patched value. + */ + private function json_apply_patch( $target, $patch ) { + if ( ! is_object( $patch ) ) { + return $patch; + } + $members = is_object( $target ) ? get_object_vars( $target ) : array(); + foreach ( get_object_vars( $patch ) as $key => $patch_member ) { + if ( null === $patch_member ) { + unset( $members[ $key ] ); + } else { + $members[ $key ] = $this->json_apply_patch( + array_key_exists( $key, $members ) ? $members[ $key ] : null, + $patch_member + ); + } + } + return (object) $members; + } + + /** + * Encode a decoded value in MySQL's canonical JSON form: ", " and ": " separators, + * object keys ordered by length and then by bytes, no escaping of Unicode or slashes. + * + * @param mixed $value The decoded value. + * + * @return string The JSON text. + */ + private function json_encode_value( $value ): string { + if ( is_array( $value ) ) { + $items = array(); + foreach ( $value as $element ) { + $items[] = $this->json_encode_value( $element ); + } + return '[' . implode( ', ', $items ) . ']'; + } + if ( is_object( $value ) ) { + $members = array(); + foreach ( get_object_vars( $value ) as $key => $member ) { + $members[ (string) $key ] = $member; + } + uksort( + $members, + function ( $a, $b ) { + $by_length = strlen( $a ) - strlen( $b ); + return 0 !== $by_length ? $by_length : strcmp( $a, $b ); + } + ); + $items = array(); + foreach ( $members as $key => $member ) { + $items[] = $this->json_encode_value( (string) $key ) . ': ' . $this->json_encode_value( $member ); + } + return '{' . implode( ', ', $items ) . '}'; + } + return json_encode( $value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION ); + } + + /** + * Resolve a JSON path against a decoded document. + * + * Supports "$", ".key", ".\"quoted key\"", "[n]", "[last]" and "[last-n]". As in MySQL, + * an array index applied to a non-array treats the value as a one-element array. + * Wildcards ("*", "**", "[*]") are not supported and raise an error rather than + * silently returning a wrong answer. + * + * @param mixed $document The decoded document. + * @param string $path The path expression. + * @param string $function_name The function name, for error messages. + * + * @throws Exception When the path is invalid or uses an unsupported wildcard. + * @return array{0: bool, 1: mixed} Whether the path exists, and the value found. + */ + private function json_find_path( $document, $path, string $function_name ): array { + $path = (string) $path; + $length = strlen( $path ); + if ( 0 === $length || '$' !== $path[0] ) { + throw new Exception( sprintf( 'Invalid JSON path expression in function %s.', $function_name ) ); + } + $current = $document; + $position = 1; + while ( $position < $length ) { + $char = $path[ $position ]; + if ( '.' === $char ) { + ++$position; + if ( $position < $length && '"' === $path[ $position ] ) { + if ( ! preg_match( '/\G"((?:[^"\\\\]|\\\\.)*)"/', $path, $match, 0, $position ) ) { + throw new Exception( sprintf( 'Invalid JSON path expression in function %s.', $function_name ) ); + } + $key = json_decode( '"' . $match[1] . '"' ); + $position += strlen( $match[0] ); + } elseif ( preg_match( '/\G[A-Za-z_$][A-Za-z0-9_$]*/', $path, $match, 0, $position ) ) { + $key = $match[0]; + $position += strlen( $match[0] ); + } elseif ( $position < $length && '*' === $path[ $position ] ) { + throw new Exception( sprintf( 'Wildcards in a JSON path are not supported in function %s.', $function_name ) ); + } else { + throw new Exception( sprintf( 'Invalid JSON path expression in function %s.', $function_name ) ); + } + if ( ! is_object( $current ) ) { + return array( false, null ); + } + $members = get_object_vars( $current ); + if ( ! array_key_exists( $key, $members ) ) { + return array( false, null ); + } + $current = $members[ $key ]; + } elseif ( '[' === $char ) { + if ( ! preg_match( '/\G\[\s*(?:(\d+)|last(?:\s*-\s*(\d+))?)\s*\]/', $path, $match, 0, $position ) ) { + if ( preg_match( '/\G\[\s*\*\s*\]/', $path, $wildcard, 0, $position ) ) { + throw new Exception( sprintf( 'Wildcards in a JSON path are not supported in function %s.', $function_name ) ); + } + throw new Exception( sprintf( 'Invalid JSON path expression in function %s.', $function_name ) ); + } + $position += strlen( $match[0] ); + $elements = is_array( $current ) ? $current : array( $current ); + if ( isset( $match[1] ) && '' !== $match[1] ) { + $index = (int) $match[1]; + } else { + // "last" and "last-N": the groups after it are absent when not matched. + $index = count( $elements ) - 1 - ( isset( $match[2] ) ? (int) $match[2] : 0 ); + } + if ( $index < 0 || $index >= count( $elements ) ) { + return array( false, null ); + } + $current = $elements[ $index ]; + } elseif ( '*' === $char ) { + throw new Exception( sprintf( 'Wildcards in a JSON path are not supported in function %s.', $function_name ) ); + } else { + throw new Exception( sprintf( 'Invalid JSON path expression in function %s.', $function_name ) ); + } + } + return array( true, $current ); + } + /** * 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_Query_Tests.php b/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Query_Tests.php index 15e4fb447..29e5bfcc2 100644 --- a/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Query_Tests.php +++ b/packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Query_Tests.php @@ -339,6 +339,217 @@ public function testSubstringSimple() { $this->assertEquals( 0, count( $actual ) ); } + /** + * @return array + */ + public static function jsonUnquoteCases(): array { + return array( + 'quoted string' => array( "SELECT JSON_UNQUOTE(CHAR(34) || 'abc' || CHAR(34)) AS result", 'abc' ), + 'already unquoted string' => array( "SELECT JSON_UNQUOTE('abc') AS result", 'abc' ), + 'null input' => array( 'SELECT JSON_UNQUOTE(NULL) AS result', null ), + 'string extraction' => array( "SELECT JSON_UNQUOTE(JSON_EXTRACT(JSON_OBJECT('a', 'abc'), '$.a')) AS result", 'abc' ), + 'extracted string containing quotes' => array( + "SELECT JSON_UNQUOTE(JSON_EXTRACT(JSON_OBJECT('a', CONCAT(CHAR(34), 'quoted', CHAR(34))), '$.a')) AS result", + '"quoted"', + ), + 'numeric extraction' => array( "SELECT JSON_UNQUOTE(JSON_EXTRACT(JSON_OBJECT('a', 12), '$.a')) AS result", '12' ), + 'boolean extraction' => array( "SELECT JSON_UNQUOTE(JSON_EXTRACT(JSON_OBJECT('a', json('true')), '$.a')) AS result", 'true' ), + 'JSON null extraction' => array( "SELECT JSON_UNQUOTE(JSON_EXTRACT(JSON_OBJECT('a', json('null')), '$.a')) AS result", 'null' ), + 'array extraction' => array( "SELECT JSON_UNQUOTE(JSON_EXTRACT(JSON_ARRAY(1, 2), '$')) AS result", '[1, 2]' ), + 'object extraction' => array( "SELECT JSON_UNQUOTE(JSON_EXTRACT(JSON_OBJECT('bb', 1, 'a', 2), '$')) AS result", '{"a": 2, "bb": 1}' ), + 'multiple-path extraction' => array( + "SELECT JSON_UNQUOTE(JSON_EXTRACT(JSON_OBJECT('a', 1, 'b', 'two'), '$.a', '$.b')) AS result", + '[1, "two"]', + ), + 'multiple-path extraction skips missing paths' => array( + "SELECT JSON_UNQUOTE(JSON_EXTRACT(JSON_OBJECT('a', 1), '$.a', '$.missing')) AS result", + '[1]', + ), + 'missing extraction path' => array( "SELECT JSON_UNQUOTE(JSON_EXTRACT(JSON_OBJECT('a', 12), '$.missing')) AS result", null ), + ); + } + + /** + * @dataProvider jsonUnquoteCases + * + * @param string $query The query to execute. + * @param string|null $expected The expected result. + */ + public function testJsonUnquote( $query, $expected ) { + $this->assertQuery( $query ); + $actual = $this->last_result[0]->result; + if ( null === $expected ) { + $this->assertNull( $actual ); + return; + } + $this->assertSame( $expected, $actual ); + } + + /** + * @return array + */ + public static function jsonContainsCases(): array { + return array( + 'scalar in array' => array( "SELECT JSON_CONTAINS(JSON_ARRAY(3, 5, 9), '5') AS result", '1' ), + 'scalar not in array' => array( "SELECT JSON_CONTAINS(JSON_ARRAY(3, 5, 9), '4') AS result", '0' ), + 'object candidate' => array( "SELECT JSON_CONTAINS(JSON_OBJECT('a', 1, 'b', 2), JSON_OBJECT('a', 1)) AS result", '1' ), + 'nested array candidate' => array( 'SELECT JSON_CONTAINS(JSON_ARRAY(JSON_ARRAY(1, 2), JSON_ARRAY(3, 4)), JSON_ARRAY(JSON_ARRAY(1, 2))) AS result', '1' ), + 'nested candidate does not match across target elements' => array( 'SELECT JSON_CONTAINS(JSON_ARRAY(JSON_ARRAY(1, 3), JSON_ARRAY(2, 4)), JSON_ARRAY(JSON_ARRAY(1, 2))) AS result', '0' ), + 'nested object candidate' => array( + "SELECT JSON_CONTAINS(JSON_OBJECT('a', JSON_OBJECT('b', 1, 'c', 2)), JSON_OBJECT('a', JSON_OBJECT('b', 1))) AS result", + '1', + ), + 'path match' => array( "SELECT JSON_CONTAINS(JSON_OBJECT('a', 1), '1', '$.a') AS result", '1' ), + 'missing path' => array( "SELECT JSON_CONTAINS(JSON_OBJECT('a', 1), '1', '$.missing') AS result", null ), + ); + } + + /** + * @dataProvider jsonContainsCases + * + * @param string $query The query to execute. + * @param string|null $expected The expected result. + */ + public function testJsonContains( $query, $expected ) { + $this->assertQuery( $query ); + $actual = $this->last_result[0]->result; + if ( null === $expected ) { + $this->assertNull( $actual ); + return; + } + $this->assertSame( $expected, $actual ); + } + + /** + * @return array + */ + public static function invalidJsonFunctionCases(): array { + return array( + 'invalid quoted JSON string' => array( + "SELECT JSON_UNQUOTE(CHAR(34) || 'not-json' || CHAR(34) || 'suffix' || CHAR(34))", + 'Invalid JSON text in argument 1 to function json_unquote.', + ), + 'invalid JSON target' => array( + "SELECT JSON_CONTAINS('not-json', '1')", + 'Invalid JSON text in argument 1 to function json_contains.', + ), + 'invalid JSON extraction' => array( + "SELECT JSON_UNQUOTE(JSON_EXTRACT('not-json', '$.a'))", + 'Invalid JSON text in argument 1 to function json_extract.', + ), + 'invalid JSON candidate' => array( + "SELECT JSON_CONTAINS('[1]', 'not-json')", + 'Invalid JSON text in argument 2 to function json_contains.', + ), + 'invalid path' => array( + "SELECT JSON_CONTAINS(JSON_OBJECT('a', JSON_OBJECT('b', 1)), '1', '$.a.b[')", + 'Invalid JSON path expression in function json_contains.', + ), + 'wildcard path' => array( + "SELECT JSON_CONTAINS(JSON_ARRAY(1), '1', '$[*]')", + 'Wildcards in a JSON path are not supported in function json_contains.', + ), + ); + } + + /** + * @dataProvider invalidJsonFunctionCases + * + * @param string $query The query to execute. + * @param string $expectedMessage The expected exception message. + */ + public function testJsonFunctionsRejectInvalidInput( $query, $expected_message ) { + $this->expectException( WP_MySQL_On_SQLite_Exception::class ); + $this->expectExceptionMessage( $expected_message ); + $this->assertQuery( $query ); + } + + public function testJsonFunctionsOverTableRows() { + $this->assertQuery( + "INSERT INTO wp_options (option_name, option_value, autoload) VALUES ('_json_probe_ids', '[3,5,9]', 'no');" + ); + $this->assertQuery( + "INSERT INTO wp_options (option_name, option_value, autoload) VALUES ('_json_probe_quotes', JSON_OBJECT('source', CONCAT(CHAR(34), 'quoted', CHAR(34))), 'no');" + ); + $query = <<<'QUERY' +SELECT option_name FROM wp_options +WHERE JSON_CONTAINS(option_value, '5') AND option_name = '_json_probe_ids' +QUERY; + + $this->assertQuery( $query ); + $actual = $this->last_result; + $this->assertEquals( 1, count( $actual ) ); + $this->assertEquals( '_json_probe_ids', $actual[0]->option_name ); + + $query = <<<'QUERY' +SELECT JSON_UNQUOTE(JSON_EXTRACT(option_value, '$.source')) AS source +FROM wp_options WHERE option_name = '_json_probe_quotes' +QUERY; + $this->assertQuery( $query ); + $this->assertSame( '"quoted"', $this->last_result[0]->source ); + } + + public function testJsonLengthAndMergePatch() { + $query = <<<'QUERY' +SELECT JSON_LENGTH('[1,2,3]') AS array_length, + JSON_LENGTH('{"a":1,"bb":2}') AS object_length, + JSON_LENGTH('"scalar"') AS scalar_length, + JSON_LENGTH('{"items":[1,2]}', '$.items') AS nested_length, + JSON_LENGTH('{"items":[1]}', '$.missing') AS missing_length, + JSON_LENGTH(NULL) AS null_document +QUERY; + + $this->assertQuery( $query ); + $actual = $this->last_result[0]; + $this->assertSame( 3, (int) $actual->array_length ); + $this->assertSame( 2, (int) $actual->object_length ); + $this->assertSame( 1, (int) $actual->scalar_length ); + $this->assertSame( 2, (int) $actual->nested_length ); + $this->assertNull( $actual->missing_length ); + $this->assertNull( $actual->null_document ); + + $query = <<<'QUERY' +SELECT JSON_MERGE_PATCH( + '{"a":1,"nested":{"keep":2,"remove":3}}', + '{"a":null,"nested":{"remove":null,"add":4}}' + ) AS merged, + JSON_MERGE_PATCH('{"items":[1,2]}', '{"items":[3]}', '{"extra":true}') AS multiple_patch, + JSON_MERGE_PATCH('{"a":1}', NULL) AS null_patch, + JSON_MERGE_PATCH(NULL, '{}') AS null_then_object, + JSON_MERGE_PATCH(NULL, '[1,2,3]') AS null_then_array, + JSON_MERGE_PATCH('{"a":"b"}', NULL, '[1,2,3]', '{"c":null,"d":"e"}') AS null_then_array_then_object +QUERY; + + $this->assertQuery( $query ); + $actual = $this->last_result[0]; + $this->assertSame( '{"nested": {"add": 4, "keep": 2}}', $actual->merged ); + $this->assertSame( '{"extra": true, "items": [3]}', $actual->multiple_patch ); + $this->assertNull( $actual->null_patch ); + $this->assertNull( $actual->null_then_object ); + $this->assertSame( '[1, 2, 3]', $actual->null_then_array ); + $this->assertSame( '{"d": "e"}', $actual->null_then_array_then_object ); + } + + public function testNullSafeEqual() { + $query = <<<'QUERY' +SELECT NULL <=> NULL AS null_null, + NULL <=> 1 AS null_value, + 1 <=> NULL AS value_null, + 1 <=> 1 AS equal_values, + 1 <=> 2 AS different_values +QUERY; + + $this->assertQuery( $query ); + $actual = $this->last_result[0]; + $this->assertSame( 1, (int) $actual->null_null ); + $this->assertNotNull( $actual->null_value ); + $this->assertSame( 0, (int) $actual->null_value ); + $this->assertNotNull( $actual->value_null ); + $this->assertSame( 0, (int) $actual->value_null ); + $this->assertSame( 1, (int) $actual->equal_values ); + $this->assertSame( 0, (int) $actual->different_values ); + } + public function testCharLengthComplex() { $query = <<<'QUERY' SELECT option_name,