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..48f2c6642 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 @@ -39,51 +39,65 @@ public static function register_for( $pdo ): self { * @var array */ private $functions = array( - 'throw' => 'throw', - 'month' => 'month', - 'monthnum' => 'month', - 'year' => 'year', - 'day' => 'day', - 'hour' => 'hour', - 'minute' => 'minute', - 'second' => 'second', - 'week' => 'week', - 'weekday' => 'weekday', - 'dayofweek' => 'dayofweek', - 'dayofmonth' => 'dayofmonth', - 'unix_timestamp' => 'unix_timestamp', - 'now' => 'now', - 'md5' => 'md5', - 'curdate' => 'curdate', - 'rand' => 'rand', - 'from_unixtime' => 'from_unixtime', - 'localtime' => 'now', - 'localtimestamp' => 'now', - 'isnull' => 'isnull', - 'regexp' => 'regexp', - 'field' => 'field', - 'log' => 'log', - 'least' => 'least', - 'greatest' => 'greatest', - 'get_lock' => 'get_lock', - 'release_lock' => 'release_lock', - 'ucase' => 'ucase', - 'lcase' => 'lcase', - 'unhex' => 'unhex', - 'from_base64' => 'from_base64', - 'to_base64' => 'to_base64', - 'inet_ntoa' => 'inet_ntoa', - 'inet_aton' => 'inet_aton', - 'datediff' => 'datediff', - 'locate' => 'locate', - 'utc_date' => 'utc_date', - 'utc_time' => 'utc_time', - 'utc_timestamp' => 'utc_timestamp', - 'version' => 'version', - 'reverse' => 'reverse', + 'throw' => 'throw', + 'month' => 'month', + 'monthnum' => 'month', + 'year' => 'year', + 'day' => 'day', + 'hour' => 'hour', + 'minute' => 'minute', + 'second' => 'second', + 'week' => 'week', + 'weekday' => 'weekday', + 'dayofweek' => 'dayofweek', + 'dayofmonth' => 'dayofmonth', + 'unix_timestamp' => 'unix_timestamp', + 'now' => 'now', + 'md5' => 'md5', + 'curdate' => 'curdate', + 'rand' => 'rand', + 'from_unixtime' => 'from_unixtime', + 'localtime' => 'now', + 'localtimestamp' => 'now', + 'isnull' => 'isnull', + 'regexp' => 'regexp', + 'field' => 'field', + 'log' => 'log', + 'least' => 'least', + 'greatest' => 'greatest', + 'get_lock' => 'get_lock', + 'release_lock' => 'release_lock', + 'ucase' => 'ucase', + 'lcase' => 'lcase', + 'unhex' => 'unhex', + 'from_base64' => 'from_base64', + 'to_base64' => 'to_base64', + 'inet_ntoa' => 'inet_ntoa', + 'inet_aton' => 'inet_aton', + 'datediff' => 'datediff', + 'locate' => 'locate', + 'utc_date' => 'utc_date', + 'utc_time' => 'utc_time', + 'utc_timestamp' => 'utc_timestamp', + 'version' => 'version', + 'reverse' => 'reverse', + 'json_array_append' => 'json_array_append', + 'json_array_insert' => 'json_array_insert', + 'json_contains_path' => 'json_contains_path', + 'json_depth' => 'json_depth', + 'json_keys' => 'json_keys', + 'json_merge' => 'json_merge', + 'json_overlaps' => 'json_overlaps', + 'json_pretty' => 'json_pretty', + 'json_schema_valid' => 'json_schema_valid', + 'json_schema_validation_report' => 'json_schema_validation_report', + 'json_search' => 'json_search', + 'json_storage_free' => 'json_storage_free', + 'json_storage_size' => 'json_storage_size', + 'json_value' => 'json_value', // Internal helper functions. - '_helper_like_to_glob_pattern' => '_helper_like_to_glob_pattern', + '_helper_like_to_glob_pattern' => '_helper_like_to_glob_pattern', ); /** @@ -927,6 +941,1323 @@ public function reverse( $str ) { return strrev( $str ); } + /** + * Decode a JSON document argument into a PHP value. + * + * JSON objects decode to stdClass instances so that empty objects + * remain distinguishable from empty arrays. JSON scalars passed as + * native PHP values (e.g. a SQL number used as a JSON document) + * are accepted as-is. + * + * @param mixed $doc The UDF argument. + * @param mixed $value Set to the decoded value on success. + * @return bool True when $doc is valid JSON. + */ + private function json_decode_document( $doc, &$value ) { + if ( is_int( $doc ) || is_float( $doc ) || is_bool( $doc ) ) { + $value = $doc; + return true; + } + if ( ! is_string( $doc ) ) { + return false; + } + $value = json_decode( $doc ); + return JSON_ERROR_NONE === json_last_error(); + } + + /** + * Encode a PHP value as compact JSON text. + * + * @param mixed $value The value to encode. + * @return string|null The JSON text, or NULL when it cannot be encoded. + */ + private function json_encode_compact( $value ) { + $json = json_encode( $value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); + if ( false === $json ) { + return null; + } + return $json; + } + + /** + * Parse a MySQL JSON path expression into a list of segments. + * + * Supports "$", ".member", '."quoted member"', "$['quoted']", + * '$["quoted"]', "[N]", and "[*]". Each segment is an array whose + * first element is one of "member", "index", or "wildcard". + * + * Wildcards are parsed but left for the caller to reject: wildcard + * traversal is out of scope and documented on each function. + * + * @param mixed $path The path expression. + * @param array $segments Set to the parsed segments on success. + * @return bool True when $path is a syntactically valid path. + */ + private function json_parse_path( $path, &$segments ) { + $segments = array(); + if ( ! is_string( $path ) ) { + return false; + } + $length = strlen( $path ); + if ( 0 === $length || '$' !== $path[0] ) { + return false; + } + $pos = 1; + while ( $pos < $length ) { + if ( '.' === $path[ $pos ] ) { + ++$pos; + if ( $pos >= $length ) { + return false; + } + if ( '"' === $path[ $pos ] ) { + $name = ''; + $closed = false; + ++$pos; + while ( $pos < $length ) { + $char = $path[ $pos ]; + if ( '\\' === $char && $pos + 1 < $length ) { + $name .= $path[ $pos + 1 ]; + $pos += 2; + continue; + } + if ( '"' === $char ) { + $closed = true; + ++$pos; + break; + } + $name .= $char; + ++$pos; + } + if ( ! $closed ) { + return false; + } + $segments[] = array( 'member', $name ); + } else { + $start = $pos; + while ( $pos < $length && 1 === preg_match( '/[A-Za-z0-9_$]/', $path[ $pos ] ) ) { + ++$pos; + } + if ( $pos === $start ) { + return false; + } + $segments[] = array( 'member', substr( $path, $start, $pos - $start ) ); + } + } elseif ( '[' === $path[ $pos ] ) { + $close = strpos( $path, ']', $pos ); + if ( false === $close ) { + return false; + } + $inside = substr( $path, $pos + 1, $close - $pos - 1 ); + if ( '*' === $inside ) { + $segments[] = array( 'wildcard' ); + } elseif ( 1 === preg_match( '/^\d+$/', $inside ) ) { + $segments[] = array( 'index', (int) $inside ); + } elseif ( + strlen( $inside ) >= 2 && + ( '"' === $inside[0] || '\'' === $inside[0] ) && + substr( $inside, -1 ) === $inside[0] + ) { + $quote = $inside[0]; + $inner = substr( $inside, 1, -1 ); + $name = ''; + $valid = true; + $j = 0; + $len = strlen( $inner ); + while ( $j < $len ) { + if ( '\\' === $inner[ $j ] && $j + 1 < $len ) { + $name .= $inner[ $j + 1 ]; + $j += 2; + continue; + } + if ( $quote === $inner[ $j ] ) { + $valid = false; + break; + } + $name .= $inner[ $j ]; + ++$j; + } + if ( ! $valid ) { + return false; + } + $segments[] = array( 'member', $name ); + } else { + return false; + } + $pos = $close + 1; + } else { + return false; + } + } + return true; + } + + /** + * Check whether parsed path segments contain a wildcard. + * + * @param array $segments Parsed path segments. + * @return bool True when any segment is a wildcard. + */ + private function json_path_has_wildcard( $segments ) { + foreach ( $segments as $segment ) { + if ( 'wildcard' === $segment[0] ) { + return true; + } + } + return false; + } + + /** + * Render parsed path segments in canonical "$.a[0]" form. + * + * @param array $segments Parsed path segments. + * @return string The canonical path. + */ + private function json_canonical_path( $segments ) { + $path = '$'; + foreach ( $segments as $segment ) { + if ( 'index' === $segment[0] ) { + $path .= '[' . $segment[1] . ']'; + } elseif ( 1 === preg_match( '/^[A-Za-z_][A-Za-z0-9_]*$/', $segment[1] ) ) { + $path .= '.' . $segment[1]; + } else { + $path .= '."' + . str_replace( + array( '\\', '"' ), + array( '\\\\', '\\"' ), + $segment[1] + ) + . '"'; + } + } + return $path; + } + + /** + * Fetch the value at a parsed path within a decoded JSON value. + * + * @param mixed $value The decoded JSON value. + * @param array $segments Parsed path segments (no wildcards). + * @param bool $found Set to true when the path exists. + * @return mixed The selected value, or NULL when it does not exist. + */ + private function json_path_get( $value, $segments, &$found ) { + $found = true; + $node = $value; + foreach ( $segments as $segment ) { + if ( 'member' === $segment[0] ) { + if ( ! ( $node instanceof stdClass ) || ! property_exists( $node, $segment[1] ) ) { + $found = false; + return null; + } + $node = $node->{$segment[1]}; + } elseif ( 'index' === $segment[0] ) { + if ( ! is_array( $node ) || ! array_key_exists( $segment[1], $node ) ) { + $found = false; + return null; + } + $node = $node[ $segment[1] ]; + } else { + $found = false; + return null; + } + } + return $node; + } + + /** + * Compute the maximum depth of a decoded JSON value. + * + * An empty array, an empty object, or a scalar all have depth 1. + * Otherwise the depth is one plus the depth of the deepest child. + * + * @param mixed $value The decoded JSON value. + * @return int The depth. + */ + private function json_value_depth( $value ) { + if ( $value instanceof stdClass ) { + $vars = get_object_vars( $value ); + if ( 0 === count( $vars ) ) { + return 1; + } + $max = 1; + foreach ( $vars as $child ) { + $child_depth = $this->json_value_depth( $child ) + 1; + if ( $child_depth > $max ) { + $max = $child_depth; + } + } + return $max; + } + if ( is_array( $value ) ) { + if ( 0 === count( $value ) ) { + return 1; + } + $max = 1; + foreach ( $value as $child ) { + $child_depth = $this->json_value_depth( $child ) + 1; + if ( $child_depth > $max ) { + $max = $child_depth; + } + } + return $max; + } + return 1; + } + + /** + * Compare two JSON scalars for equality. + * + * Numbers compare across int and float, strings compare byte-wise, + * and values of different JSON types are never equal. + * + * @param mixed $a First value. + * @param mixed $b Second value. + * @return bool True when the scalars are equal. + */ + private function json_scalars_equal( $a, $b ) { + if ( null === $a || null === $b ) { + return null === $a && null === $b; + } + if ( is_bool( $a ) || is_bool( $b ) ) { + return is_bool( $a ) && is_bool( $b ) && $a === $b; + } + if ( ( is_int( $a ) || is_float( $a ) ) && ( is_int( $b ) || is_float( $b ) ) ) { + if ( is_int( $a ) && is_int( $b ) ) { + return $a === $b; + } + return (float) $a === (float) $b; + } + if ( is_string( $a ) && is_string( $b ) ) { + return $a === $b; + } + return false; + } + + /** + * Compare two decoded JSON values for deep equality. + * + * Object key order is insignificant, array element order matters, + * and numbers compare across int and float. + * + * @param mixed $a First value. + * @param mixed $b Second value. + * @return bool True when the values are equal. + */ + private function json_values_equal( $a, $b ) { + if ( $a instanceof stdClass && $b instanceof stdClass ) { + $vars_a = get_object_vars( $a ); + $vars_b = get_object_vars( $b ); + if ( count( $vars_a ) !== count( $vars_b ) ) { + return false; + } + foreach ( $vars_a as $key => $child_a ) { + if ( ! array_key_exists( $key, $vars_b ) ) { + return false; + } + if ( ! $this->json_values_equal( $child_a, $vars_b[ $key ] ) ) { + return false; + } + } + return true; + } + if ( is_array( $a ) && is_array( $b ) ) { + if ( count( $a ) !== count( $b ) ) { + return false; + } + foreach ( $a as $index => $child_a ) { + if ( ! array_key_exists( $index, $b ) ) { + return false; + } + if ( ! $this->json_values_equal( $child_a, $b[ $index ] ) ) { + return false; + } + } + return true; + } + if ( $a instanceof stdClass || $b instanceof stdClass || is_array( $a ) || is_array( $b ) ) { + return false; + } + return $this->json_scalars_equal( $a, $b ); + } + + /** + * Check whether two decoded JSON values overlap, per MySQL rules. + * + * Top-level arrays share an element when a deep-equality comparison + * matches one of their elements, and a top-level non-array value is + * treated as a one-element array. Top-level objects share a + * key-value pair when the member values are deeply equal. Below the + * top level no further overlap recursion happens: array elements + * and object member values are compared for equality only. + * + * @param mixed $a First value. + * @param mixed $b Second value. + * @return bool True when the values overlap. + */ + private function json_values_overlap( $a, $b ) { + if ( ! is_array( $a ) && is_array( $b ) ) { + $swap = $a; + $a = $b; + $b = $swap; + } + if ( is_array( $a ) ) { + $list_b = is_array( $b ) ? $b : array( $b ); + foreach ( $list_b as $child_b ) { + foreach ( $a as $child_a ) { + if ( $this->json_values_equal( $child_a, $child_b ) ) { + return true; + } + } + } + return false; + } + if ( $a instanceof stdClass && $b instanceof stdClass ) { + $vars_b = get_object_vars( $b ); + foreach ( get_object_vars( $a ) as $key => $child_a ) { + if ( + array_key_exists( $key, $vars_b ) && + $this->json_values_equal( $child_a, $vars_b[ $key ] ) + ) { + return true; + } + } + return false; + } + if ( $a instanceof stdClass || $b instanceof stdClass ) { + return false; + } + return $this->json_scalars_equal( $a, $b ); + } + + /** + * Render a decoded JSON value in MySQL JSON_PRETTY() format. + * + * Objects and arrays expand one value per line with two-space + * indentation, while empty objects and arrays stay inline. + * + * @param mixed $value The decoded JSON value. + * @param int $indent The current indentation level. + * @return string The pretty-printed JSON. + */ + private function json_pretty_print( $value, $indent ) { + if ( $value instanceof stdClass ) { + $vars = get_object_vars( $value ); + if ( 0 === count( $vars ) ) { + return '{}'; + } + $pad = str_repeat( ' ', $indent + 1 ); + $lines = array(); + foreach ( $vars as $key => $child ) { + $lines[] = $pad + . json_encode( (string) $key, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) + . ': ' . $this->json_pretty_print( $child, $indent + 1 ); + } + return "{\n" . implode( ",\n", $lines ) . "\n" . str_repeat( ' ', $indent ) . '}'; + } + if ( is_array( $value ) ) { + if ( 0 === count( $value ) ) { + return '[]'; + } + $pad = str_repeat( ' ', $indent + 1 ); + $lines = array(); + foreach ( $value as $child ) { + $lines[] = $pad . $this->json_pretty_print( $child, $indent + 1 ); + } + return "[\n" . implode( ",\n", $lines ) . "\n" . str_repeat( ' ', $indent ) . ']'; + } + $scalar = json_encode( $value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); + if ( false === $scalar ) { + return 'null'; + } + return $scalar; + } + + /** + * Build a regular expression from a JSON_SEARCH() LIKE pattern. + * + * "%" matches any sequence, "_" matches a single character, and + * the escape character quotes the next character literally. + * Matching is case-sensitive, like MySQL JSON document comparison. + * + * @param string $pattern The search string. + * @param string $escape The escape character, or '' for none. + * @return string The regular expression. + */ + private function json_like_to_regex( $pattern, $escape ) { + $regex = ''; + $length = strlen( $pattern ); + for ( $i = 0; $i < $length; ++$i ) { + $char = $pattern[ $i ]; + if ( '' !== $escape && $char === $escape && $i + 1 < $length ) { + $regex .= preg_quote( $pattern[ $i + 1 ], '/' ); + ++$i; + continue; + } + if ( '%' === $char ) { + $regex .= '.*'; + } elseif ( '_' === $char ) { + $regex .= '.'; + } else { + $regex .= preg_quote( $char, '/' ); + } + } + return '/^' . $regex . '$/su'; + } + + /** + * Collect paths of string values matching a JSON_SEARCH() pattern. + * + * Only JSON strings are matched; numbers, booleans, and null never + * match. Traversal is depth-first in document order. + * + * @param mixed $node The decoded JSON value. + * @param array $segments Path segments leading to $node. + * @param string $regex The search pattern as a regular expression. + * @param string $mode "one" stops after the first match. + * @param array $matches Collected canonical paths. + * @return bool True when mode is "one" and a match was found. + */ + private function json_search_values( $node, $segments, $regex, $mode, &$matches ) { + if ( is_string( $node ) ) { + if ( 1 === preg_match( $regex, $node ) ) { + $matches[] = $this->json_canonical_path( $segments ); + if ( 'one' === $mode ) { + return true; + } + } + return false; + } + if ( $node instanceof stdClass ) { + foreach ( get_object_vars( $node ) as $key => $child ) { + $segments[] = array( 'member', (string) $key ); + $stop = $this->json_search_values( $child, $segments, $regex, $mode, $matches ); + array_pop( $segments ); + if ( $stop ) { + return true; + } + } + return false; + } + if ( is_array( $node ) ) { + foreach ( $node as $index => $child ) { + $segments[] = array( 'index', $index ); + $stop = $this->json_search_values( $child, $segments, $regex, $mode, $matches ); + array_pop( $segments ); + if ( $stop ) { + return true; + } + } + } + return false; + } + + /** + * Interpret a JSON modification function argument as a JSON value. + * + * Like MySQL, a string argument that parses as JSON is stored as + * the parsed value (so '2' becomes the number 2 and '{"a": 1}' + * becomes an object), while any other string stays a JSON string. + * + * @param mixed $val The UDF argument. + * @return mixed The JSON value to store. + */ + private function json_parse_candidate( $val ) { + if ( null === $val || is_int( $val ) || is_float( $val ) || is_bool( $val ) ) { + return $val; + } + if ( ! is_string( $val ) ) { + return null; + } + $decoded = json_decode( $val ); + if ( JSON_ERROR_NONE === json_last_error() ) { + return $decoded; + } + return $val; + } + + /** + * Append a value at a parsed path, per JSON_ARRAY_APPEND() rules. + * + * Appends to arrays and autowraps existing scalars and objects in a + * new array. Pairs whose path does not identify an existing value + * are ignored like MySQL, so a missing object key is never created. + * + * @param mixed $node The (sub)document to modify, by reference. + * @param array $segments Remaining path segments (no wildcards). + * @param mixed $val The decoded value to append. + * @return bool True when the document was modified. + */ + private function json_append_value( &$node, $segments, $val ) { + if ( 0 === count( $segments ) ) { + if ( is_array( $node ) ) { + $node[] = $val; + } else { + $node = array( $node, $val ); + } + return true; + } + $leg = $segments[0]; + $rest = array_slice( $segments, 1 ); + if ( 'member' === $leg[0] ) { + if ( ! ( $node instanceof stdClass ) || ! property_exists( $node, $leg[1] ) ) { + return false; + } + return $this->json_append_value( $node->{$leg[1]}, $rest, $val ); + } + if ( 'index' === $leg[0] ) { + if ( ! is_array( $node ) || ! array_key_exists( $leg[1], $node ) ) { + return false; + } + return $this->json_append_value( $node[ $leg[1] ], $rest, $val ); + } + return false; + } + + /** + * Insert a value at a parsed path, per JSON_ARRAY_INSERT() rules. + * + * The path must end in an array index; the value is inserted before + * that index, or appended when the index is past the end. Paths + * that do not resolve to an existing array are ignored like MySQL. + * + * @param mixed $node The (sub)document to modify, by reference. + * @param array $segments Remaining path segments (no wildcards). + * @param mixed $val The decoded value to insert. + * @return bool True when the document was modified. + */ + private function json_insert_value( &$node, $segments, $val ) { + $count = count( $segments ); + if ( 0 === $count ) { + return false; + } + $leg = $segments[0]; + $last = 1 === $count; + if ( 'member' === $leg[0] ) { + if ( ! ( $node instanceof stdClass ) || ! property_exists( $node, $leg[1] ) || $last ) { + return false; + } + return $this->json_insert_value( $node->{$leg[1]}, array_slice( $segments, 1 ), $val ); + } + if ( 'index' === $leg[0] ) { + if ( ! is_array( $node ) ) { + return false; + } + if ( ! $last ) { + if ( ! array_key_exists( $leg[1], $node ) ) { + return false; + } + return $this->json_insert_value( $node[ $leg[1] ], array_slice( $segments, 1 ), $val ); + } + $index = $leg[1]; + if ( $index > count( $node ) ) { + $index = count( $node ); + } + array_splice( $node, $index, 0, array( $val ) ); + return true; + } + return false; + } + + /** + * Merge two decoded JSON values, per JSON_MERGE_PRESERVE() rules. + * + * Two objects merge key by key (shared keys merge recursively), + * two arrays concatenate, and a non-array operand is autowrapped + * as a one-element array before concatenating. Used by the + * deprecated JSON_MERGE() alias. + * + * @param mixed $a First value. + * @param mixed $b Second value. + * @return mixed The merged value. + */ + private function json_merge_preserve_values( $a, $b ) { + if ( $a instanceof stdClass && $b instanceof stdClass ) { + $merged = clone $a; + foreach ( get_object_vars( $b ) as $key => $child_b ) { + if ( property_exists( $merged, $key ) ) { + $merged->{$key} = $this->json_merge_preserve_values( $merged->{$key}, $child_b ); + } else { + $merged->{$key} = $child_b; + } + } + return $merged; + } + $list_a = is_array( $a ) ? $a : array( $a ); + $list_b = is_array( $b ) ? $b : array( $b ); + return array_merge( $list_a, $list_b ); + } + + /** + * Check whether a decoded value matches a JSON Schema type name. + * + * An "integer" is any number with a zero fractional part, so 1.0 + * matches both "integer" and "number". + * + * @param mixed $type The type name. + * @param mixed $value The decoded JSON value. + * @return bool True when the value has the named type. + */ + private function json_schema_type_matches( $type, $value ) { + if ( ! is_string( $type ) ) { + return false; + } + switch ( $type ) { + case 'null': + return null === $value; + case 'boolean': + return is_bool( $value ); + case 'object': + return $value instanceof stdClass; + case 'array': + return is_array( $value ); + case 'string': + return is_string( $value ); + case 'number': + return is_int( $value ) || is_float( $value ); + case 'integer': + return is_int( $value ) || ( + is_float( $value ) && + is_finite( $value ) && + floor( $value ) === $value + ); + default: + return false; + } + } + + /** + * Validate a decoded value against a decoded JSON Schema. + * + * Implements the documented subset: "type" (a name or an array of + * names), "properties", "required", "items" (a schema, or an array + * of positional schemas with extra elements allowed), and "enum". + * Unknown keywords are ignored per the JSON Schema specification. + * Keywords like "$ref", "patternProperties", "allOf", and remote + * schemas are not supported and silently ignored. + * + * @param mixed $schema The decoded schema (must be an object). + * @param mixed $value The decoded value to validate. + * @param array $segments Path segments leading to $value, for messages. + * @param string $reason Set to a description when validation fails. + * @return bool True when the value is valid. + */ + private function json_schema_validate( $schema, $value, $segments, &$reason ) { + $location = $this->json_canonical_path( $segments ); + if ( ! ( $schema instanceof stdClass ) ) { + $reason = sprintf( 'The schema at %s is not an object.', $location ); + return false; + } + if ( property_exists( $schema, 'type' ) ) { + $types = $schema->type; + if ( ! is_array( $types ) ) { + $types = array( $types ); + } + $matched = false; + foreach ( $types as $type ) { + if ( $this->json_schema_type_matches( $type, $value ) ) { + $matched = true; + break; + } + } + if ( ! $matched ) { + $reason = sprintf( 'The value at %s does not match the required type.', $location ); + return false; + } + } + if ( $value instanceof stdClass ) { + if ( property_exists( $schema, 'required' ) && is_array( $schema->required ) ) { + foreach ( $schema->required as $required ) { + if ( ! is_string( $required ) ) { + continue; + } + if ( ! property_exists( $value, $required ) ) { + $reason = sprintf( + 'The object at %s is missing required property "%s".', + $location, + $required + ); + return false; + } + } + } + if ( property_exists( $schema, 'properties' ) && $schema->properties instanceof stdClass ) { + foreach ( get_object_vars( $schema->properties ) as $key => $subschema ) { + if ( ! property_exists( $value, $key ) ) { + continue; + } + $segments[] = array( 'member', (string) $key ); + $valid = $this->json_schema_validate( $subschema, $value->{$key}, $segments, $reason ); + array_pop( $segments ); + if ( ! $valid ) { + return false; + } + } + } + } + if ( is_array( $value ) && property_exists( $schema, 'items' ) ) { + $items = $schema->items; + if ( $items instanceof stdClass ) { + foreach ( $value as $index => $child ) { + $segments[] = array( 'index', $index ); + $valid = $this->json_schema_validate( $items, $child, $segments, $reason ); + array_pop( $segments ); + if ( ! $valid ) { + return false; + } + } + } elseif ( is_array( $items ) ) { + foreach ( $items as $index => $subschema ) { + if ( ! array_key_exists( $index, $value ) ) { + break; + } + $segments[] = array( 'index', $index ); + $valid = $this->json_schema_validate( $subschema, $value[ $index ], $segments, $reason ); + array_pop( $segments ); + if ( ! $valid ) { + return false; + } + } + } + } + if ( property_exists( $schema, 'enum' ) && is_array( $schema->enum ) ) { + foreach ( $schema->enum as $allowed ) { + if ( $this->json_values_equal( $allowed, $value ) ) { + return true; + } + } + $reason = sprintf( 'The value at %s is not one of the allowed enum values.', $location ); + return false; + } + return true; + } + + /** + * Method to emulate MySQL JSON_CONTAINS_PATH() function. + * + * Returns 1 when any path exists ("one") or when all paths exist + * ("all"), and 0 otherwise. Returns NULL when any argument is NULL, + * when the document is not valid JSON, when the mode is not "one" + * or "all", or when a path is not a valid path expression. + * + * Wildcard segments ("[*]") are not supported; a path containing + * one makes the result NULL. + * + * @return int|null 1 or 0, or NULL on invalid input. + */ + public function json_contains_path() { + $args = func_get_args(); + $count = count( $args ); + if ( $count < 3 ) { + return null; + } + $doc = $args[0]; + $mode = $args[1]; + if ( null === $doc || null === $mode ) { + return null; + } + $mode = strtolower( (string) $mode ); + if ( 'one' !== $mode && 'all' !== $mode ) { + return null; + } + if ( ! $this->json_decode_document( $doc, $value ) ) { + return null; + } + $paths = array_slice( $args, 2 ); + foreach ( $paths as $path ) { + if ( null === $path ) { + return null; + } + if ( ! $this->json_parse_path( $path, $segments ) ) { + return null; + } + if ( $this->json_path_has_wildcard( $segments ) ) { + return null; + } + $this->json_path_get( $value, $segments, $found ); + if ( 'one' === $mode && $found ) { + return 1; + } + if ( 'all' === $mode && ! $found ) { + return 0; + } + } + return 'one' === $mode ? 0 : 1; + } + + /** + * Method to emulate MySQL JSON_DEPTH() function. + * + * An empty object, an empty array, or a scalar all have depth 1. + * Returns NULL when the argument is NULL or is not valid JSON. + * + * @param mixed $doc The JSON document. + * @return int|null The depth, or NULL on invalid input. + */ + public function json_depth( $doc ) { + if ( null === $doc ) { + return null; + } + if ( ! $this->json_decode_document( $doc, $value ) ) { + return null; + } + return $this->json_value_depth( $value ); + } + + /** + * Method to emulate MySQL JSON_KEYS() function. + * + * Returns the top-level keys of an object as a JSON array, or the + * keys of the object selected by the optional path. When the + * document or the selected value is not an object, or the path + * does not exist, returns NULL to match MySQL. Returns NULL when + * any argument is NULL, when the document is not valid JSON, or + * when the path is not a valid path expression. + * + * Wildcard segments ("[*]") are not supported; a path containing + * one makes the result NULL. + * + * @param mixed $doc The JSON document. + * @param mixed|null $path Optional JSON path selecting an object. + * @return string|null The keys as a JSON array, or NULL. + */ + public function json_keys( $doc, $path = null ) { + if ( null === $doc ) { + return null; + } + if ( ! $this->json_decode_document( $doc, $value ) ) { + return null; + } + $target = $value; + if ( null !== $path ) { + if ( ! $this->json_parse_path( $path, $segments ) ) { + return null; + } + if ( $this->json_path_has_wildcard( $segments ) ) { + return null; + } + $target = $this->json_path_get( $value, $segments, $found ); + if ( ! $found ) { + return null; + } + } + if ( ! ( $target instanceof stdClass ) ) { + return null; + } + return $this->json_encode_compact( array_map( 'strval', array_keys( get_object_vars( $target ) ) ) ); + } + + /** + * Method to emulate MySQL JSON_OVERLAPS() function. + * + * Returns 1 when two documents share any key-value pair or array + * element. Array elements and object member values compare by deep + * equality; only top-level values are autowrapped as a one-element + * array when the other argument is an array. Returns NULL when any + * argument is NULL or when either document is not valid JSON. + * + * @return int|null 1 or 0, or NULL on invalid input. + */ + public function json_overlaps() { + $args = func_get_args(); + if ( count( $args ) < 2 ) { + return null; + } + if ( null === $args[0] || null === $args[1] ) { + return null; + } + if ( ! $this->json_decode_document( $args[0], $a ) ) { + return null; + } + if ( ! $this->json_decode_document( $args[1], $b ) ) { + return null; + } + return $this->json_values_overlap( $a, $b ) ? 1 : 0; + } + + /** + * Method to emulate MySQL JSON_PRETTY() function. + * + * Returns a human-readable rendering of the document with one + * value per line and two-space indentation. Returns NULL when the + * argument is NULL or is not valid JSON. + * + * @param mixed $doc The JSON document. + * @return string|null The pretty-printed JSON, or NULL on invalid input. + */ + public function json_pretty( $doc ) { + if ( null === $doc ) { + return null; + } + if ( ! $this->json_decode_document( $doc, $value ) ) { + return null; + } + return $this->json_pretty_print( $value, 0 ); + } + + /** + * Method to emulate MySQL JSON_SEARCH() function. + * + * Returns the path to the first matching string value ("one") as a + * string, or all matching paths ("all") as a JSON array. Only JSON + * strings are matched; numbers, booleans, and null never match. + * Matching is case-sensitive. The search string supports "%" and + * "_" wildcards like the LIKE operator; the escape character + * defaults to backslash when it is missing or NULL, and an empty + * escape disables escaping. + * + * Optional path arguments restrict the search to those subtrees, + * while the returned paths are still rooted at "$". Returns NULL + * when there is no match, when the document, mode, or search string + * is NULL, when the document is not valid JSON, when the mode is not + * "one" or "all", or when a path is not a valid path expression. + * + * Wildcard segments ("[*]") are not supported; a scope path with + * one simply matches nothing. + * + * @return string|null A path, a JSON array of paths, or NULL. + */ + public function json_search( $doc = null, $one_or_all = null, $search = null, $escape = null ) { + $arg_count = func_num_args(); + if ( $arg_count < 3 ) { + return null; + } + if ( null === $doc || null === $one_or_all || null === $search ) { + return null; + } + if ( $arg_count >= 4 ) { + if ( null === $escape ) { + $escape = '\\'; + } elseif ( ! is_string( $escape ) || strlen( $escape ) > 1 ) { + return null; + } + } else { + $escape = '\\'; + } + $mode = strtolower( (string) $one_or_all ); + if ( 'one' !== $mode && 'all' !== $mode ) { + return null; + } + if ( ! $this->json_decode_document( $doc, $value ) ) { + return null; + } + $regex = $this->json_like_to_regex( (string) $search, $escape ); + $scopes = array_slice( func_get_args(), 4 ); + if ( 0 === count( $scopes ) ) { + $scopes = array( '$' ); + } + $matches = array(); + foreach ( $scopes as $scope ) { + if ( null === $scope ) { + return null; + } + if ( ! $this->json_parse_path( $scope, $segments ) ) { + return null; + } + if ( $this->json_path_has_wildcard( $segments ) ) { + continue; + } + $target = $this->json_path_get( $value, $segments, $found ); + if ( ! $found ) { + continue; + } + if ( $this->json_search_values( $target, $segments, $regex, $mode, $matches ) ) { + break; + } + } + if ( 0 === count( $matches ) ) { + return null; + } + if ( 'one' === $mode ) { + return $matches[0]; + } + return $this->json_encode_compact( $matches ); + } + + /** + * Method to emulate MySQL JSON_VALUE() function. + * + * Extracts the scalar at the given path and returns it as an + * unquoted value: strings as-is, numbers as-is, booleans as + * "true" or "false", and JSON null as SQL NULL. Objects and arrays + * cannot be converted to a scalar, so they return NULL (MySQL + * raises an error in that case). Returns NULL when any argument + * is NULL, when the document is not valid JSON, when the path is + * not valid, or when the path does not exist. + * + * @param mixed $doc The JSON document. + * @param mixed|null $path The JSON path selecting a scalar. + * @return mixed The scalar value, or NULL. + */ + public function json_value( $doc, $path = null ) { + if ( null === $doc || null === $path ) { + return null; + } + if ( ! $this->json_decode_document( $doc, $value ) ) { + return null; + } + if ( ! $this->json_parse_path( $path, $segments ) ) { + return null; + } + if ( $this->json_path_has_wildcard( $segments ) ) { + return null; + } + $target = $this->json_path_get( $value, $segments, $found ); + if ( ! $found ) { + return null; + } + if ( $target instanceof stdClass || is_array( $target ) ) { + return null; + } + if ( is_bool( $target ) ) { + return $target ? 'true' : 'false'; + } + return $target; + } + + /** + * Method to emulate MySQL JSON_ARRAY_APPEND() function. + * + * Takes the document followed by path-value pairs evaluated left + * to right. Like MySQL, a string value that parses as JSON is + * stored as the parsed value, while any other string stays a JSON + * string. Pairs whose path does not identify an existing value are + * ignored. Wildcard paths are not supported and such pairs are + * ignored. + * + * Returns NULL when the document is NULL or not valid JSON, when + * a path is NULL or invalid, or when the arguments do not form + * complete path-value pairs. + * + * @return string|null The updated document, or NULL on invalid input. + */ + public function json_array_append() { + $args = func_get_args(); + $count = count( $args ); + if ( $count < 3 || 0 === $count % 2 ) { + return null; + } + if ( null === $args[0] ) { + return null; + } + if ( ! $this->json_decode_document( $args[0], $value ) ) { + return null; + } + for ( $i = 1; $i < $count; $i += 2 ) { + $path = $args[ $i ]; + if ( null === $path ) { + return null; + } + if ( ! $this->json_parse_path( $path, $segments ) ) { + return null; + } + if ( $this->json_path_has_wildcard( $segments ) ) { + continue; + } + $this->json_append_value( + $value, + $segments, + $this->json_parse_candidate( $args[ $i + 1 ] ) + ); + } + return $this->json_encode_compact( $value ); + } + + /** + * Method to emulate MySQL JSON_ARRAY_INSERT() function. + * + * Takes the document followed by path-value pairs evaluated left + * to right. Each path must end in an array index; the value is + * inserted before that index, or appended when the index is past + * the end. String values follow the same JSON auto-parsing as + * JSON_ARRAY_APPEND(). Paths that do not resolve to an existing + * array are ignored, like MySQL. Wildcard paths are not supported + * and such pairs are ignored. + * + * Returns NULL when the document is NULL or not valid JSON, when + * a path is NULL or invalid, or when the arguments do not form + * complete path-value pairs. + * + * @return string|null The updated document, or NULL on invalid input. + */ + public function json_array_insert() { + $args = func_get_args(); + $count = count( $args ); + if ( $count < 3 || 0 === $count % 2 ) { + return null; + } + if ( null === $args[0] ) { + return null; + } + if ( ! $this->json_decode_document( $args[0], $value ) ) { + return null; + } + for ( $i = 1; $i < $count; $i += 2 ) { + $path = $args[ $i ]; + if ( null === $path ) { + return null; + } + if ( ! $this->json_parse_path( $path, $segments ) ) { + return null; + } + if ( $this->json_path_has_wildcard( $segments ) ) { + continue; + } + $this->json_insert_value( + $value, + $segments, + $this->json_parse_candidate( $args[ $i + 1 ] ) + ); + } + return $this->json_encode_compact( $value ); + } + + /** + * Method to emulate MySQL JSON_STORAGE_FREE() function. + * + * The driver never does partial in-place updates of JSON values, + * so no storage is ever freed and this always returns 0. Returns + * NULL when the argument is NULL or is not valid JSON. + * + * @param mixed $doc The JSON document. + * @return int|null 0, or NULL on invalid input. + */ + public function json_storage_free( $doc ) { + if ( null === $doc ) { + return null; + } + if ( ! $this->json_decode_document( $doc, $value ) ) { + return null; + } + return 0; + } + + /** + * Method to emulate MySQL JSON_STORAGE_SIZE() function. + * + * Returns the byte size (an OCTET_LENGTH equivalent) of the + * normalized compact form of the document. Returns NULL when the + * argument is NULL or is not valid JSON. + * + * @param mixed $doc The JSON document. + * @return int|null The byte size, or NULL on invalid input. + */ + public function json_storage_size( $doc ) { + if ( null === $doc ) { + return null; + } + if ( ! $this->json_decode_document( $doc, $value ) ) { + return null; + } + $json = $this->json_encode_compact( $value ); + if ( null === $json ) { + return null; + } + return strlen( $json ); + } + + /** + * Method to emulate MySQL JSON_SCHEMA_VALID() function. + * + * Returns 1 when the document validates against the schema and 0 + * when it does not. Only the documented subset is enforced: type, + * properties, required, items, and enum. Unknown keywords are + * ignored; $ref, patternProperties, boolean combinators, and + * remote schemas are not supported. Returns NULL when any argument + * is NULL, when either argument is not valid JSON, or when the + * schema is not a JSON object. + * + * @param mixed $schema The JSON Schema document. + * @param mixed $doc The JSON document to validate. + * @return int|null 1 or 0, or NULL on invalid input. + */ + public function json_schema_valid( $schema, $doc ) { + if ( null === $schema || null === $doc ) { + return null; + } + if ( ! $this->json_decode_document( $schema, $schema_value ) ) { + return null; + } + if ( ! $this->json_decode_document( $doc, $value ) ) { + return null; + } + if ( ! ( $schema_value instanceof stdClass ) ) { + return null; + } + $reason = ''; + return $this->json_schema_validate( $schema_value, $value, array(), $reason ) ? 1 : 0; + } + + /** + * Method to emulate MySQL JSON_SCHEMA_VALIDATION_REPORT() function. + * + * Returns a JSON object with a "valid" boolean and, when invalid, + * a "reason" string describing the first failure. The same schema + * subset and NULL rules as JSON_SCHEMA_VALID() apply. + * + * @param mixed $schema The JSON Schema document. + * @param mixed $doc The JSON document to validate. + * @return string|null The JSON report, or NULL on invalid input. + */ + public function json_schema_validation_report( $schema, $doc ) { + if ( null === $schema || null === $doc ) { + return null; + } + if ( ! $this->json_decode_document( $schema, $schema_value ) ) { + return null; + } + if ( ! $this->json_decode_document( $doc, $value ) ) { + return null; + } + if ( ! ( $schema_value instanceof stdClass ) ) { + return null; + } + $reason = ''; + if ( $this->json_schema_validate( $schema_value, $value, array(), $reason ) ) { + return $this->json_encode_compact( array( 'valid' => true ) ); + } + return $this->json_encode_compact( + array( + 'valid' => false, + 'reason' => $reason, + ) + ); + } + + /** + * Method to emulate MySQL JSON_MERGE() function. + * + * JSON_MERGE() is a deprecated alias of JSON_MERGE_PRESERVE(): two + * objects merge key by key (shared keys merge recursively), while + * arrays concatenate after autowrapping a non-array operand as a + * one-element array. Returns NULL when any argument is NULL or when + * any document is not valid JSON. + * + * @return string|null The merged document, or NULL on invalid input. + */ + public function json_merge() { + $args = func_get_args(); + if ( 0 === count( $args ) ) { + return null; + } + $merged = null; + $first = true; + foreach ( $args as $doc ) { + if ( null === $doc ) { + return null; + } + if ( ! $this->json_decode_document( $doc, $value ) ) { + return null; + } + if ( $first ) { + $merged = $value; + $first = false; + } else { + $merged = $this->json_merge_preserve_values( $merged, $value ); + } + } + return $this->json_encode_compact( $merged ); + } + /** * 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..49faf5f39 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,494 @@ public function testReverseFunction(): void { $result = $this->assertQuery( 'SELECT REVERSE(NULL) AS reversed' ); $this->assertNull( $result[0]->reversed ); } + + public function testJsonContainsPathFunction(): void { + $doc = "'{\"a\": {\"b\": 1}, \"c\": [1, 2]}'"; + + // "one" returns 1 when any path exists. + $result = $this->assertQuery( "SELECT JSON_CONTAINS_PATH($doc, 'one', '$.a.b', '$.x') AS m" ); + $this->assertSame( '1', $result[0]->m ); + + // "one" returns 0 when no path exists. + $result = $this->assertQuery( "SELECT JSON_CONTAINS_PATH($doc, 'one', '$.x', '$.y') AS m" ); + $this->assertSame( '0', $result[0]->m ); + + // "all" returns 1 when every path exists. + $result = $this->assertQuery( "SELECT JSON_CONTAINS_PATH($doc, 'all', '$.a.b', '$.c[1]') AS m" ); + $this->assertSame( '1', $result[0]->m ); + + // "all" returns 0 when any path is missing. + $result = $this->assertQuery( "SELECT JSON_CONTAINS_PATH($doc, 'all', '$.a.b', '$.x') AS m" ); + $this->assertSame( '0', $result[0]->m ); + + // Mode matching is case-insensitive. + $result = $this->assertQuery( "SELECT JSON_CONTAINS_PATH($doc, 'ONE', '$.a') AS m" ); + $this->assertSame( '1', $result[0]->m ); + + // Quoted keys with spaces resolve. + $result = $this->assertQuery( 'SELECT JSON_CONTAINS_PATH(\'{"a b": 1}\', \'one\', \'$."a b"\' ) AS m' ); + $this->assertSame( '1', $result[0]->m ); + + // Root path always exists in a valid document. + $result = $this->assertQuery( "SELECT JSON_CONTAINS_PATH($doc, 'one', '$') AS m" ); + $this->assertSame( '1', $result[0]->m ); + + // Invalid mode returns NULL. + $result = $this->assertQuery( "SELECT JSON_CONTAINS_PATH($doc, 'any', '$.a') AS m" ); + $this->assertNull( $result[0]->m ); + + // Invalid path returns NULL. + $result = $this->assertQuery( "SELECT JSON_CONTAINS_PATH($doc, 'one', '$.a.') AS m" ); + $this->assertNull( $result[0]->m ); + + // Invalid JSON returns NULL. + $result = $this->assertQuery( "SELECT JSON_CONTAINS_PATH('{oops', 'one', '$.a') AS m" ); + $this->assertNull( $result[0]->m ); + + // NULL argument returns NULL. + $result = $this->assertQuery( 'SELECT JSON_CONTAINS_PATH(NULL, \'one\', \'$.a\') AS m' ); + $this->assertNull( $result[0]->m ); + $result = $this->assertQuery( "SELECT JSON_CONTAINS_PATH($doc, NULL, '$.a') AS m" ); + $this->assertNull( $result[0]->m ); + $result = $this->assertQuery( "SELECT JSON_CONTAINS_PATH($doc, 'one', NULL) AS m" ); + $this->assertNull( $result[0]->m ); + + // Missing path arguments return NULL. + $result = $this->assertQuery( "SELECT JSON_CONTAINS_PATH($doc, 'one') AS m" ); + $this->assertNull( $result[0]->m ); + } + + public function testJsonDepthFunction(): void { + // Scalars and empty containers have depth 1. + $result = $this->assertQuery( 'SELECT JSON_DEPTH(\'"hello"\') AS d' ); + $this->assertSame( '1', $result[0]->d ); + $result = $this->assertQuery( 'SELECT JSON_DEPTH(10) AS d' ); + $this->assertSame( '1', $result[0]->d ); + $result = $this->assertQuery( "SELECT JSON_DEPTH('{}') AS d" ); + $this->assertSame( '1', $result[0]->d ); + $result = $this->assertQuery( "SELECT JSON_DEPTH('[]') AS d" ); + $this->assertSame( '1', $result[0]->d ); + + // Nested documents. + $result = $this->assertQuery( 'SELECT JSON_DEPTH(\'{"a": {"b": [1, 2, {"c": null}]}}\') AS d' ); + $this->assertSame( '5', $result[0]->d ); + $result = $this->assertQuery( "SELECT JSON_DEPTH('[1, {\"a\": []}]') AS d" ); + $this->assertSame( '3', $result[0]->d ); + + // NULL input returns NULL. + $result = $this->assertQuery( 'SELECT JSON_DEPTH(NULL) AS d' ); + $this->assertNull( $result[0]->d ); + + // Invalid JSON returns NULL. + $result = $this->assertQuery( "SELECT JSON_DEPTH('{oops') AS d" ); + $this->assertNull( $result[0]->d ); + } + + public function testJsonKeysFunction(): void { + // Top-level keys of an object. + $result = $this->assertQuery( 'SELECT JSON_KEYS(\'{"a": 1, "b": 2}\') AS k' ); + $this->assertSame( '["a","b"]', $result[0]->k ); + + // Keys of a nested object selected by path. + $result = $this->assertQuery( 'SELECT JSON_KEYS(\'{"a": {"x": 1, "y": 2}}\', \'$.a\') AS k' ); + $this->assertSame( '["x","y"]', $result[0]->k ); + + // Numeric-looking keys stay strings, like MySQL. + $result = $this->assertQuery( 'SELECT JSON_KEYS(\'{"0": 1, "a": 2}\') AS k' ); + $this->assertSame( '["0","a"]', $result[0]->k ); + + // Empty object has no keys. + $result = $this->assertQuery( "SELECT JSON_KEYS('{}') AS k" ); + $this->assertSame( '[]', $result[0]->k ); + + // A top-level array is not an object, so NULL. + $result = $this->assertQuery( "SELECT JSON_KEYS('[1, 2]') AS k" ); + $this->assertNull( $result[0]->k ); + + // A path selecting a non-object returns NULL. + $result = $this->assertQuery( 'SELECT JSON_KEYS(\'{"a": [1]}\', \'$.a\') AS k' ); + $this->assertNull( $result[0]->k ); + + // A missing path returns NULL. + $result = $this->assertQuery( 'SELECT JSON_KEYS(\'{"a": 1}\', \'$.x\') AS k' ); + $this->assertNull( $result[0]->k ); + + // NULL input returns NULL. + $result = $this->assertQuery( 'SELECT JSON_KEYS(NULL) AS k' ); + $this->assertNull( $result[0]->k ); + + // Invalid JSON returns NULL. + $result = $this->assertQuery( "SELECT JSON_KEYS('{oops') AS k" ); + $this->assertNull( $result[0]->k ); + } + + public function testJsonOverlapsFunction(): void { + // Arrays sharing an element overlap. + $result = $this->assertQuery( "SELECT JSON_OVERLAPS('[1, 2, 3]', '[3, 4]') AS o" ); + $this->assertSame( '1', $result[0]->o ); + $result = $this->assertQuery( "SELECT JSON_OVERLAPS('[1, 2]', '[3, 4]') AS o" ); + $this->assertSame( '0', $result[0]->o ); + + // Objects sharing a key-value pair overlap. + $result = $this->assertQuery( 'SELECT JSON_OVERLAPS(\'{"a": 1}\', \'{"a": 1, "b": 2}\') AS o' ); + $this->assertSame( '1', $result[0]->o ); + $result = $this->assertQuery( 'SELECT JSON_OVERLAPS(\'{"a": 1}\', \'{"a": 2}\') AS o' ); + $this->assertSame( '0', $result[0]->o ); + + // Nested values compare by equality, not partial overlap. + $result = $this->assertQuery( 'SELECT JSON_OVERLAPS(\'[[1, 2], [3, 4], 5]\', \'[1, [2, 3], [4, 5]]\') AS o' ); + $this->assertSame( '0', $result[0]->o ); + $result = $this->assertQuery( 'SELECT JSON_OVERLAPS(\'{"a": [1, 2]}\', \'{"a": [2, 3]}\') AS o' ); + $this->assertSame( '0', $result[0]->o ); + $result = $this->assertQuery( 'SELECT JSON_OVERLAPS(\'{"a": [1, 2]}\', \'{"a": [2, 3], "b": 9}\') AS o' ); + $this->assertSame( '0', $result[0]->o ); + $result = $this->assertQuery( 'SELECT JSON_OVERLAPS(\'{"a": [1, 2]}\', \'{"a": [1, 2], "b": 9}\') AS o' ); + $this->assertSame( '1', $result[0]->o ); + + // Top-level array elements overlap only when they are deeply equal. + $result = $this->assertQuery( 'SELECT JSON_OVERLAPS(\'[[1, 2], [3, 4]]\', \'[[3, 4], 9]\') AS o' ); + $this->assertSame( '1', $result[0]->o ); + + // Scalar against array uses element comparison. + $result = $this->assertQuery( "SELECT JSON_OVERLAPS('2', '[2, 3]') AS o" ); + $this->assertSame( '1', $result[0]->o ); + $result = $this->assertQuery( "SELECT JSON_OVERLAPS('1', '[2, 3]') AS o" ); + $this->assertSame( '0', $result[0]->o ); + + // Scalar against object never overlaps. + $result = $this->assertQuery( 'SELECT JSON_OVERLAPS(\'1\', \'{"a": 1}\') AS o' ); + $this->assertSame( '0', $result[0]->o ); + + // Type-sensitive scalar comparison: 1.0 equals 1, "1" does not. + $result = $this->assertQuery( "SELECT JSON_OVERLAPS('1', '1.0') AS o" ); + $this->assertSame( '1', $result[0]->o ); + $result = $this->assertQuery( 'SELECT JSON_OVERLAPS(\'1\', \'"1"\') AS o' ); + $this->assertSame( '0', $result[0]->o ); + $result = $this->assertQuery( 'SELECT JSON_OVERLAPS(\'true\', \'1\') AS o' ); + $this->assertSame( '0', $result[0]->o ); + + // NULL argument returns NULL. + $result = $this->assertQuery( "SELECT JSON_OVERLAPS(NULL, '[1]') AS o" ); + $this->assertNull( $result[0]->o ); + + // Invalid JSON returns NULL. + $result = $this->assertQuery( "SELECT JSON_OVERLAPS('{oops', '[1]') AS o" ); + $this->assertNull( $result[0]->o ); + } + + public function testJsonPrettyFunction(): void { + // Exact MySQL-style output shape: two-space indent, one value per line. + $result = $this->assertQuery( 'SELECT JSON_PRETTY(\'{"b": 2, "a": [1, 2]}\') AS p' ); + $this->assertSame( "{\n \"b\": 2,\n \"a\": [\n 1,\n 2\n ]\n}", $result[0]->p ); + + // Empty containers stay inline. + $result = $this->assertQuery( 'SELECT JSON_PRETTY(\'{"a": {}, "b": []}\') AS p' ); + $this->assertSame( "{\n \"a\": {},\n \"b\": []\n}", $result[0]->p ); + + // Scalars pass through. + $result = $this->assertQuery( 'SELECT JSON_PRETTY(\'"x"\') AS p' ); + $this->assertSame( '"x"', $result[0]->p ); + + // Output is valid JSON decoding to the input value. + $result = $this->assertQuery( 'SELECT JSON_EXTRACT(JSON_PRETTY(\'{"a": [1, {"b": true}]}\'), \'$.a[1].b\') AS v' ); + $this->assertSame( '1', $result[0]->v ); + + // NULL input returns NULL. + $result = $this->assertQuery( 'SELECT JSON_PRETTY(NULL) AS p' ); + $this->assertNull( $result[0]->p ); + + // Invalid JSON returns NULL. + $result = $this->assertQuery( "SELECT JSON_PRETTY('{oops') AS p" ); + $this->assertNull( $result[0]->p ); + } + + public function testJsonSearchFunction(): void { + $doc = '\'["abc", "abcd", "ab"]\''; + + // "one" returns the first matching path. + $result = $this->assertQuery( "SELECT JSON_SEARCH($doc, 'one', 'abc') AS s" ); + $this->assertSame( '$[0]', $result[0]->s ); + + // "all" returns every matching path as a JSON array. + $result = $this->assertQuery( "SELECT JSON_SEARCH($doc, 'all', 'abc%') AS s" ); + $this->assertSame( '["$[0]","$[1]"]', $result[0]->s ); + + // "_" matches a single character. + $result = $this->assertQuery( "SELECT JSON_SEARCH($doc, 'one', 'ab_') AS s" ); + $this->assertSame( '$[0]', $result[0]->s ); + + // An escaped wildcard matches literally: nothing ends in a literal "%". + $result = $this->assertQuery( "SELECT JSON_SEARCH($doc, 'one', 'abc\\%', '\\\\') AS s" ); + $this->assertNull( $result[0]->s ); + + // A NULL escape falls back to the backslash default. + $result = $this->assertQuery( 'SELECT JSON_SEARCH(\'{"a": "x"}\', \'one\', \'x\', NULL, \'$.a\') AS s' ); + $this->assertSame( '$.a', $result[0]->s ); + $result = $this->assertQuery( "SELECT JSON_SEARCH('{\"a\": \"100%\"}', 'one', '100\\%', NULL) AS s" ); + $this->assertSame( '$.a', $result[0]->s ); + + // Non-string values never match, so '1' skips the number 1. + $result = $this->assertQuery( "SELECT JSON_SEARCH('[1, \"1\"]', 'one', '1') AS s" ); + $this->assertSame( '$[1]', $result[0]->s ); + + // No match returns NULL. + $result = $this->assertQuery( "SELECT JSON_SEARCH($doc, 'one', 'zzz') AS s" ); + $this->assertNull( $result[0]->s ); + + // A scope path restricts the search but results stay root-relative. + $result = $this->assertQuery( 'SELECT JSON_SEARCH(\'{"x": {"v": "hit"}, "y": "hit"}\', \'one\', \'hit\', \'\\\\\', \'$.x\') AS s' ); + $this->assertSame( '$.x.v', $result[0]->s ); + + // A missing scope path finds nothing. + $result = $this->assertQuery( 'SELECT JSON_SEARCH(\'{"x": 1}\', \'one\', \'hit\', \'\\\\\', \'$.missing\') AS s' ); + $this->assertNull( $result[0]->s ); + + // Invalid mode returns NULL. + $result = $this->assertQuery( "SELECT JSON_SEARCH($doc, 'any', 'abc') AS s" ); + $this->assertNull( $result[0]->s ); + + // NULL argument returns NULL. + $result = $this->assertQuery( 'SELECT JSON_SEARCH(NULL, \'one\', \'abc\') AS s' ); + $this->assertNull( $result[0]->s ); + + // Invalid JSON returns NULL. + $result = $this->assertQuery( "SELECT JSON_SEARCH('{oops', 'one', 'abc') AS s" ); + $this->assertNull( $result[0]->s ); + } + + public function testJsonValueFunction(): void { + // Scalars extract as unquoted values. + $result = $this->assertQuery( 'SELECT JSON_VALUE(\'{"a": {"b": 42}, "c": "hi"}\', \'$.a.b\') AS v' ); + $this->assertSame( '42', $result[0]->v ); + $result = $this->assertQuery( 'SELECT JSON_VALUE(\'{"a": {"b": 42}, "c": "hi"}\', \'$.c\') AS v' ); + $this->assertSame( 'hi', $result[0]->v ); + $result = $this->assertQuery( 'SELECT JSON_VALUE(\'{"a": 1.5}\', \'$.a\') AS v' ); + $this->assertSame( '1.5', $result[0]->v ); + + // Booleans render as true/false. + $result = $this->assertQuery( 'SELECT JSON_VALUE(\'{"t": true, "f": false}\', \'$.t\') AS v' ); + $this->assertSame( 'true', $result[0]->v ); + $result = $this->assertQuery( 'SELECT JSON_VALUE(\'{"t": true, "f": false}\', \'$.f\') AS v' ); + $this->assertSame( 'false', $result[0]->v ); + + // JSON null becomes SQL NULL. + $result = $this->assertQuery( 'SELECT JSON_VALUE(\'{"a": null}\', \'$.a\') AS v' ); + $this->assertNull( $result[0]->v ); + + // Objects and arrays cannot be scalars, so NULL. + $result = $this->assertQuery( 'SELECT JSON_VALUE(\'{"a": {"b": 1}}\', \'$.a\') AS v' ); + $this->assertNull( $result[0]->v ); + $result = $this->assertQuery( 'SELECT JSON_VALUE(\'{"a": [1]}\', \'$.a\') AS v' ); + $this->assertNull( $result[0]->v ); + + // Interplay: extract from a value built by JSON_ARRAY_APPEND(). + $result = $this->assertQuery( 'SELECT JSON_VALUE(JSON_ARRAY_APPEND(\'{"a": [1]}\', \'$.a\', 2), \'$.a[1]\') AS v' ); + $this->assertSame( '2', $result[0]->v ); + + // Missing path returns NULL. + $result = $this->assertQuery( 'SELECT JSON_VALUE(\'{"a": 1}\', \'$.x\') AS v' ); + $this->assertNull( $result[0]->v ); + + // NULL argument returns NULL. + $result = $this->assertQuery( 'SELECT JSON_VALUE(NULL, \'$.a\') AS v' ); + $this->assertNull( $result[0]->v ); + + // Invalid JSON returns NULL. + $result = $this->assertQuery( "SELECT JSON_VALUE('{oops', '$.a') AS v" ); + $this->assertNull( $result[0]->v ); + } + + public function testJsonArrayAppendFunction(): void { + // Append to an existing array. + $result = $this->assertQuery( 'SELECT JSON_ARRAY_APPEND(\'{"a": [1], "b": 2}\', \'$.a\', 3) AS j' ); + $this->assertSame( '{"a":[1,3],"b":2}', $result[0]->j ); + + // Append autowraps an existing scalar. + $result = $this->assertQuery( 'SELECT JSON_ARRAY_APPEND(\'{"b": 2}\', \'$.b\', 3) AS j' ); + $this->assertSame( '{"b":[2,3]}', $result[0]->j ); + + // A missing object key is ignored: the pair creates nothing. + $result = $this->assertQuery( 'SELECT JSON_ARRAY_APPEND(\'{"a": 1}\', \'$.c\', \'"x"\') AS j' ); + $this->assertSame( '{"a":1}', $result[0]->j ); + + // String values that parse as JSON are stored parsed. + $result = $this->assertQuery( 'SELECT JSON_ARRAY_APPEND(\'[]\', \'$\', \'{"x": 1}\') AS j' ); + $this->assertSame( '[{"x":1}]', $result[0]->j ); + $result = $this->assertQuery( 'SELECT JSON_ARRAY_APPEND(\'[]\', \'$\', \'"abc"\') AS j' ); + $this->assertSame( '["abc"]', $result[0]->j ); + + // Multiple pairs evaluate left to right. + $result = $this->assertQuery( 'SELECT JSON_ARRAY_APPEND(\'{"a": [1]}\', \'$.a\', 2, \'$.a\', 3) AS j' ); + $this->assertSame( '{"a":[1,2,3]}', $result[0]->j ); + + // A pair with a missing intermediate path is ignored. + $result = $this->assertQuery( 'SELECT JSON_ARRAY_APPEND(\'{"a": 1}\', \'$.x.y\', 1) AS j' ); + $this->assertSame( '{"a":1}', $result[0]->j ); + + // NULL document returns NULL. + $result = $this->assertQuery( "SELECT JSON_ARRAY_APPEND(NULL, '$.a', 1) AS j" ); + $this->assertNull( $result[0]->j ); + + // Invalid JSON returns NULL. + $result = $this->assertQuery( "SELECT JSON_ARRAY_APPEND('{oops', '$.a', 1) AS j" ); + $this->assertNull( $result[0]->j ); + + // An incomplete pair returns NULL. + $result = $this->assertQuery( "SELECT JSON_ARRAY_APPEND('[1]', '$[0]') AS j" ); + $this->assertNull( $result[0]->j ); + } + + public function testJsonArrayInsertFunction(): void { + // Insert before an index. + $result = $this->assertQuery( 'SELECT JSON_ARRAY_INSERT(\'["a", "c"]\', \'$[1]\', \'"b"\') AS j' ); + $this->assertSame( '["a","b","c"]', $result[0]->j ); + + // Insert into a nested array selected by path. + $result = $this->assertQuery( 'SELECT JSON_ARRAY_INSERT(\'{"a": [1, 3]}\', \'$.a[1]\', 2) AS j' ); + $this->assertSame( '{"a":[1,2,3]}', $result[0]->j ); + + // An index past the end appends. + $result = $this->assertQuery( "SELECT JSON_ARRAY_INSERT('[1]', '$[5]', 2) AS j" ); + $this->assertSame( '[1,2]', $result[0]->j ); + + // A path not ending in an index is ignored. + $result = $this->assertQuery( "SELECT JSON_ARRAY_INSERT('[1]', '$', 2) AS j" ); + $this->assertSame( '[1]', $result[0]->j ); + + // A path through a non-array is ignored. + $result = $this->assertQuery( 'SELECT JSON_ARRAY_INSERT(\'{"a": 1}\', \'$.a[0]\', 2) AS j' ); + $this->assertSame( '{"a":1}', $result[0]->j ); + + // NULL document returns NULL. + $result = $this->assertQuery( "SELECT JSON_ARRAY_INSERT(NULL, '$[0]', 1) AS j" ); + $this->assertNull( $result[0]->j ); + + // Invalid JSON returns NULL. + $result = $this->assertQuery( "SELECT JSON_ARRAY_INSERT('[oops', '$[0]', 1) AS j" ); + $this->assertNull( $result[0]->j ); + } + + public function testJsonStorageFunctions(): void { + // No storage is ever freed. + $result = $this->assertQuery( 'SELECT JSON_STORAGE_FREE(\'{"a": 1}\') AS f' ); + $this->assertSame( '0', $result[0]->f ); + + // Size is the byte length of the normalized compact document. + $result = $this->assertQuery( 'SELECT JSON_STORAGE_SIZE(\'{"a": 1}\') AS s' ); + $this->assertSame( '7', $result[0]->s ); + $result = $this->assertQuery( "SELECT JSON_STORAGE_SIZE('[1, 2]') AS s" ); + $this->assertSame( '5', $result[0]->s ); + + // NULL input returns NULL. + $result = $this->assertQuery( 'SELECT JSON_STORAGE_FREE(NULL) AS f' ); + $this->assertNull( $result[0]->f ); + $result = $this->assertQuery( 'SELECT JSON_STORAGE_SIZE(NULL) AS s' ); + $this->assertNull( $result[0]->s ); + + // Invalid JSON returns NULL. + $result = $this->assertQuery( "SELECT JSON_STORAGE_FREE('{oops') AS f" ); + $this->assertNull( $result[0]->f ); + $result = $this->assertQuery( "SELECT JSON_STORAGE_SIZE('{oops') AS s" ); + $this->assertNull( $result[0]->s ); + } + + public function testJsonSchemaValidFunction(): void { + $schema = '\'{"type": "object", "properties": {"a": {"type": "integer"}}, "required": ["a"]}\''; + + $result = $this->assertQuery( "SELECT JSON_SCHEMA_VALID($schema, '{\"a\": 1}') AS v" ); + $this->assertSame( '1', $result[0]->v ); + $result = $this->assertQuery( "SELECT JSON_SCHEMA_VALID($schema, '{\"a\": \"x\"}') AS v" ); + $this->assertSame( '0', $result[0]->v ); + $result = $this->assertQuery( "SELECT JSON_SCHEMA_VALID($schema, '{}') AS v" ); + $this->assertSame( '0', $result[0]->v ); + + // Enum membership. + $result = $this->assertQuery( 'SELECT JSON_SCHEMA_VALID(\'{"enum": [1, "two", null]}\', \'"two"\') AS v' ); + $this->assertSame( '1', $result[0]->v ); + $result = $this->assertQuery( 'SELECT JSON_SCHEMA_VALID(\'{"enum": [1, "two", null]}\', \'"three"\') AS v' ); + $this->assertSame( '0', $result[0]->v ); + + // Array items. + $result = $this->assertQuery( 'SELECT JSON_SCHEMA_VALID(\'{"type": "array", "items": {"type": "integer"}}\', \'[1, 2]\') AS v' ); + $this->assertSame( '1', $result[0]->v ); + $result = $this->assertQuery( 'SELECT JSON_SCHEMA_VALID(\'{"type": "array", "items": {"type": "integer"}}\', \'[1, "x"]\') AS v' ); + $this->assertSame( '0', $result[0]->v ); + + // A non-object schema returns NULL. + $result = $this->assertQuery( 'SELECT JSON_SCHEMA_VALID(\'[1]\', \'[1]\') AS v' ); + $this->assertNull( $result[0]->v ); + + // NULL argument returns NULL. + $result = $this->assertQuery( "SELECT JSON_SCHEMA_VALID(NULL, '{}') AS v" ); + $this->assertNull( $result[0]->v ); + + // Invalid JSON returns NULL. + $result = $this->assertQuery( "SELECT JSON_SCHEMA_VALID('{oops', '{}') AS v" ); + $this->assertNull( $result[0]->v ); + $result = $this->assertQuery( "SELECT JSON_SCHEMA_VALID('{}', '{oops') AS v" ); + $this->assertNull( $result[0]->v ); + } + + public function testJsonSchemaValidationReportFunction(): void { + $schema = '\'{"type": "object", "required": ["a"]}\''; + + // A valid document reports valid without a reason. + $result = $this->assertQuery( "SELECT JSON_SCHEMA_VALIDATION_REPORT($schema, '{\"a\": 1}') AS r" ); + $this->assertSame( '{"valid":true}', $result[0]->r ); + + // An invalid document reports valid false with a reason. + $result = $this->assertQuery( "SELECT JSON_SCHEMA_VALIDATION_REPORT($schema, '{}') AS r" ); + $this->assertSame( + '{"valid":false,"reason":"The object at $ is missing required property \\"a\\"."}', + $result[0]->r + ); + + // Interplay: the report is machine-readable via JSON_EXTRACT(). + $result = $this->assertQuery( "SELECT JSON_EXTRACT(JSON_SCHEMA_VALIDATION_REPORT($schema, '{}'), '$.valid') AS v" ); + $this->assertSame( '0', $result[0]->v ); + + // NULL argument returns NULL. + $result = $this->assertQuery( "SELECT JSON_SCHEMA_VALIDATION_REPORT(NULL, '{}') AS r" ); + $this->assertNull( $result[0]->r ); + + // Invalid JSON returns NULL. + $result = $this->assertQuery( "SELECT JSON_SCHEMA_VALIDATION_REPORT('{oops', '{}') AS r" ); + $this->assertNull( $result[0]->r ); + } + + public function testJsonMergeFunction(): void { + // JSON_MERGE() aliases merge-preserve semantics: shared keys combine. + $result = $this->assertQuery( 'SELECT JSON_MERGE(\'{"a": 1, "b": 2}\', \'{"a": 3}\') AS j' ); + $this->assertSame( '{"a":[1,3],"b":2}', $result[0]->j ); + + // Arrays concatenate; non-array operands autowrap first. + $result = $this->assertQuery( "SELECT JSON_MERGE('[1, 2]', '[3]') AS j" ); + $this->assertSame( '[1,2,3]', $result[0]->j ); + $result = $this->assertQuery( "SELECT JSON_MERGE('[1, 2]', '3') AS j" ); + $this->assertSame( '[1,2,3]', $result[0]->j ); + $result = $this->assertQuery( 'SELECT JSON_MERGE(\'{"a": 1}\', \'[1]\') AS j' ); + $this->assertSame( '[{"a":1},1]', $result[0]->j ); + $result = $this->assertQuery( 'SELECT JSON_MERGE(\'{"a": [1]}\', \'{"a": 2}\') AS j' ); + $this->assertSame( '{"a":[1,2]}', $result[0]->j ); + + // Nested objects merge recursively. + $result = $this->assertQuery( 'SELECT JSON_MERGE(\'{"a": {"x": 1}}\', \'{"a": {"y": 2}}\') AS j' ); + $this->assertSame( '{"a":{"x":1,"y":2}}', $result[0]->j ); + + // More than two documents fold left to right. + $result = $this->assertQuery( "SELECT JSON_MERGE('[1]', '[2]', '[3]') AS j" ); + $this->assertSame( '[1,2,3]', $result[0]->j ); + + // Interplay: merged keys are readable via JSON_KEYS(). + $result = $this->assertQuery( 'SELECT JSON_KEYS(JSON_MERGE(\'{"a": 1}\', \'{"b": 2}\')) AS k' ); + $this->assertSame( '["a","b"]', $result[0]->k ); + + // A NULL argument returns NULL. + $result = $this->assertQuery( 'SELECT JSON_MERGE(\'{"a": 1}\', NULL) AS j' ); + $this->assertNull( $result[0]->j ); + + // Invalid JSON returns NULL. + $result = $this->assertQuery( "SELECT JSON_MERGE('{oops', '{}') AS j" ); + $this->assertNull( $result[0]->j ); + } }