Details
-
Bug
-
Status: In Review (View Workflow)
-
Major
-
Resolution: Unresolved
-
10.11, 13.2
Description
Problem
JSON_EQUALS(NULL, x) and JSON_EQUALS(x, NULL) evaluate to NULL when selected, but a WHERE condition, IF() or CASE WHEN treats them as TRUE. A row for which the condition is NULL is therefore returned by WHERE cond and also by WHERE cond IS NULL, which breaks SQL three-valued logic.
How to repeat
CREATE TABLE t (id INT PRIMARY KEY, j JSON NOT NULL); |
INSERT INTO t VALUES (1,'{"k0":1}'),(2,'{}'),(3,'{"a":[1,2]}'); |
 |
SELECT id, JSON_EQUALS(NULL, j) AS p, JSON_EQUALS(NULL, j) IS NULL AS p_is_null FROM t; |
SELECT id FROM t WHERE JSON_EQUALS(NULL, j); |
SELECT id FROM t WHERE NOT JSON_EQUALS(NULL, j); |
SELECT id FROM t WHERE JSON_EQUALS(NULL, j) IS NULL; |
SELECT id, IF(JSON_EQUALS(NULL, j), 'T', 'F') AS iff FROM t; |
SELECT 'row' WHERE JSON_EQUALS(NULL, '{}'); |
Actual result
| statement | actual | expected |
|---|---|---|
| projection of JSON_EQUALS(NULL, j) | NULL for every row, IS NULL is 1 | same |
| WHERE JSON_EQUALS(NULL, j) | rows 1, 2, 3 | no rows |
| WHERE NOT JSON_EQUALS(NULL, j) | no rows | no rows |
| WHERE JSON_EQUALS(NULL, j) IS NULL | rows 1, 2, 3 | rows 1, 2, 3 |
| IF(JSON_EQUALS(NULL, j), 'T', 'F') | T for every row (same for CASE WHEN) | F |
| SELECT 'row' WHERE JSON_EQUALS(NULL, '{}') | returns one row | no rows |
The same happens when the NULL comes from the second argument or from an expression such as NULLIF(j, j).
Analysis
Item_func_json_equals::val_bool() in sql/item_jsonfunc.cc sets null_value and then returns 1 on every NULL / error path:
String *a= args[0]->val_json(&a_tmp);
|
if ((null_value= a == nullptr || args[0]->null_value)) |
return 1; |
String *b= args[1]->val_json(&b_tmp);
|
if ((null_value= b == nullptr || args[1]->null_value)) |
return 1; |
// ... and two more "null_value= 1; return 1;" for init_dynamic_string() failures
|
Condition evaluation (WHERE, IF, CASE) uses the value returned by val_bool() and does not look at null_value, so the payload 1 is taken as TRUE, while the select-list path checks null_value and shows NULL. Item_func_json_schema_valid::val_bool() returns 0 together with null_value= 1 and behaves correctly (JSON_SCHEMA_VALID(NULL, '{}') is filtered out), as do JSON_CONTAINS, JSON_OVERLAPS and JSON_EXISTS with a NULL first argument.
Suggested fix: return 0 instead of 1 on those four paths. I did not build or test a patch.
The function code is identical on current main (checked against 52391ebe4feb56c8ccbbf33a29ea3acbb7b7cea7). This was found by a ternary-logic-partitioning (TLP) check in a fuzzer.