Details
-
Bug
-
Status: Closed (View Workflow)
-
Major
-
Resolution: Won't Fix
-
10.6.12
-
None
Description
If you create a table using the JSON data-type, it actually creates a LONGTEXT with a CHECK constraint to ensure only valid JSON is entered (https://mariadb.com/kb/en/json-data-type/).
Although I don't believe it is documented anyway, If the CHECK constraint is left exactly as is, JSON functions (at least JSON_OBJECT & JSON_ARRAY) treat the contents of the string as JSON (you don't need to use a function like JSON_COMPACT to stop it being escaped. However if the CHECK constraint is changed in any way (including being made more specific), this breaks.
Example:
CREATE OR REPLACE TABLE `jsonTest`( |
`s` JSON,
|
`s2` LONGTEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin CHECK(JSON_VALID(`s2`) AND JSON_TYPE(`s2`) = "object") |
);
|
INSERT INTO `jsonTest` VALUES('{"x":"y"}', '{"x":"y"}'); |
SELECT JSON_PRETTY(JSON_OBJECT('a', `s`, 'b', `s2`, 'c', JSON_COMPACT(`s2`))) FROM `jsonTest`; |
/* JSON_PRETTY for ease of output only. The SELECT produces:
|
{
|
"a":
|
{
|
"x": "y"
|
},
|
"b": "{\"x\":\"y\"}",
|
"c":
|
{
|
"x": "y"
|
}
|
}
|
*/
|
/*
|
Not needing to manually use JSON_COMPACT is great, however if you have code that is expecting an escaped string when selecting the column, this causes significant confusion (in my case I had added a new column and not changed the constraint; and then existing code using the new column broke. Ideally the JSON data type would be a true data type, or if not possible then I feel the behaviour with JSON_VALID in the constraint should be consistent.