You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Current MySQL/MariaDB/postgres nested JSON operations make it impossible to distinguish between the JSON null/true and a JSON string containing "null"/"true" #15238
breaking changeFor issues and PRs. Changes that break compatibility and require a major version increment.dialect: mariadbFor issues and PRs. Things that involve MariaDB (and do not involve all dialects).dialect: mysqlFor issues and PRs. Things that involve MySQL (and do not involve all dialects).dialect: postgresFor issues and PRs. Things that involve PostgreSQL (and do not involve all dialects).type: bugDEPRECATED: replace with the "bug" issue type
It's trying to find all users who don't have a last name set. The last name is stored in a JSON field. Unfortunately it's returning all users whose last name is "null".
The root of the problem is json_unquote. Because of json_unquote, it's impossible to distinguish between null an "null", because they both become null when passed to json_unquote.
This is crazy because it's exactly what MySQL recommends. They even added the ->> operator as a shorthand for JSON_UNQUOTE(JSON_EXTRACT), but it's completely broken.
We have the same issue with true and "true", 1 and "1", etc.
This json_unquote must go away. Instead we must call JSON.stringify on the value provided by the user.
SELECT`id`, `json`FROM`Tests`AS`Test`WHERE json_extract(`Test`.`json`,'$.\"name\"') ='"John"'-- <- notice the quotes around the string
This would be a breaking change because literals are going to be affected. replacements and bind parameters would also break, which is a huge caveat that will need to be documented :/ (the user will need to call JSON.stringify on these values)
Environment
Sequelize version: 6.25.1, ^7.0.0-alpha.16
Node.js version: 16.17.1
If TypeScript related: TypeScript version: N/A
Database & Version: MySQL 8.0.32
Connector library & Version: mysql2 - 2.3.3
Would you be willing to resolve this issue by submitting a Pull Request?
Yes, I have the time and I know how to start.
Indicate your interest in the resolution of this issue by adding the 👍 reaction. Comments such as "+1" will be removed.
changed the title [-]Current MySQL nested JSON operations make it impossible to distinguish between the JSON `null` and a JSON string containing `"null"`[/-][+]Current MySQL/MariaDB nested JSON operations make it impossible to distinguish between the JSON `null` and a JSON string containing `"null"`[/+]on Nov 5, 2022
Maybe we should put this behaviour as an option so it's not enabled by default? I think that replacements and bind parameters should work in the most cases possible
I don't think we should put it behind an option. If we do, no one is going to realize the issue during development and won't realize their code has bugs until it crashes in production :/
If we look at the possible scenarios, only one is impacted, the first one:
🔶 Scenario 1: Bind params or replacements in Model methods
This is the only scenario where the user would have do something differently from what they do today: If they try to use a bind parameter of replacement with a model method (such as findAll), we're currently unable to know what the type of the replacement is, and we won't be able to call JSON.stringify on it:
Or, once we support #14410, by specifying the type of their replacement:
Test.findAll({where: {json: {name: literal('$name'),},},replacements: {name: 'John',},// really not set on how to specify themreplacementTypes: {name: DataTypes.JSON,},})
both of which would produce
SELECT`id`, `json`FROM`Tests`AS`Test`WHERE json_extract(`Test`.`json`,'$.\"name\"') ='"John"'-- <- notice the quotes around the string
🟩 Scenario 2: Raw Queries
The query is already raw so it's already up to the user whether they use json_unquote or not. No changes there.
🟩 Scenario 3: Typical model method calls (replacements)
Say the user writes the following:
Test.findAll({where: {json: {name: 'John',},},})
We know json is a JSON DataType, so we can stringify the value accordingly. No change for the user. We'll transparently produce the following query
🟩 Scenario 4: Typical model method calls (bind params)
Some methods, like Model.update use bind parameters instead of replacements. But the same concept applies. We're responsible for generating these bind parameters so we can stringify them ourselves.
SELECT
json#>>ARRAY['null'] as "null",
json#>>ARRAY['nullStr'] as "nullStr",
json#>>ARRAY['bool'] as "bool",
json#>>ARRAY['boolStr'] as "boolStr",
json#>>ARRAY['num'] as "num",
json#>>ARRAY['numStr'] as "numStr",
json#>>ARRAY['array'] as "array",
json#>>ARRAY['arrayStr'] as "arrayStr",
json#>>ARRAY['object'] as "object",
json#>>ARRAY['objectStr'] as "objectStr"
FROM "Users";
And it resulted in the following output:
Notice how, expect for null, all string versions are identical to the non-string version. This could be the source of many bugs.
Now if I use #> instead:
SELECT
json#>ARRAY['null'] as "null",
json#>ARRAY['nullStr'] as "nullStr",
json#>ARRAY['bool'] as "bool",
json#>ARRAY['boolStr'] as "boolStr",
json#>ARRAY['num'] as "num",
json#>ARRAY['numStr'] as "numStr",
json#>ARRAY['array'] as "array",
json#>ARRAY['arrayStr'] as "arrayStr",
json#>ARRAY['object'] as "object",
json#>ARRAY['objectStr'] as "objectStr"FROM"Users";
I get this, which is much better:
They're all of type json. Now, it's not possible to compare json to anything. The following will fail because there is no operator json IS boolean.
json#>ARRAY['bool'] IS true
results in:
It's fine because we can cast the left-hand side based on the right hand side.
The following will work ✅:
(json#>ARRAY['bool'])::text::boolean IS true
And it's safe because it will only work with JSON fields that actually contain a boolean. Say it contains the string 'true' then it'll try to convert "true" to a boolean which will fail:
This needs a complete rework where we go through all JSON type and the different possible operators and we check what happens:
boolean: use #>, cast json to text then boolean
number: use #>, cast json to text then number
null: either:
use #>> (which will return a postgres null instead of a json null) - preferred
or use #> and compare to the string 'null' without casting.
string, array and object: use #> cast left side to text and the right-hand value must be text that went through JSON.stringify?
Must not forget that some operators such as @> and <@ expect JSON, when these operators are used we cannot cast either side to text.
I'm not going to lie @frostzt, this last part is going to be difficult. It's a non-trivial amount of work and is going to need a good updated test suite. The more I think about this the more edge-cases I find. Just look at this post's edit history lol
changed the title [-]Current MySQL/MariaDB nested JSON operations make it impossible to distinguish between the JSON `null` and a JSON string containing `"null"`[/-][+]Current MySQL/MariaDB/postgres nested JSON operations make it impossible to distinguish between the JSON `null` and a JSON string containing `"null"`[/+]on Nov 9, 2022
changed the title [-]Current MySQL/MariaDB/postgres nested JSON operations make it impossible to distinguish between the JSON `null` and a JSON string containing `"null"`[/-][+]Current MySQL/MariaDB/postgres nested JSON operations make it impossible to distinguish between the JSON `null`/`true` and a JSON string containing `"null"`/`"true"`[/+]on Nov 9, 2022
Hey @ephys yeah seems like this is gonna be a hard one, but someday will have to start on hard ones right :p do you think I would be able to take this on? Like maybe you and Rik can also guide me (ofc only when you have time) and I will also keep working on it post work?
They'll need to be updated. They can be regrouped in the same test file (such as json.test.ts (note the ts extension)). Then for each one possible value we need to decide what the behavior should be.
But again just for one dialect this is going to be a lot of work. This long post is just about postgres
⚠️ but even this needs more research: casting text to boolean will fail if the value is not a number. When comparing we don't want it to fail. So maybe when the = or <> operator is used, we do this instead:
("jsonAttr")::text = '12'
and if another operator is used:
testSql({jsonAttr: {[Op.gt]: 12},});
then we do this:
("jsonAttr")::text::decimal > 12
boolean
testSql({jsonAttr: true,});
produces:
("jsonAttr")::text = 'true'
null
testSql({jsonAttr: null,});
produces:
("jsonAttr") IS null
testSql({'jsonAttr.nested': null,});
produces:
("jsonAttr"->>'nested') IS null
⚠️ notice how this time I used ->> instead of -> so both JSON null and postgres null are normalized to a postgres null, which can then be compared using IS
array and objects
Unsure how to handle these. I'd say JSON.stringify. But that means any spacing difference makes it fail:
testSql({jsonAttr: [1,2,3],});
produces?:
("jsonAttr")::text = '[1, 2, 3]'
Then there are the JSON operators, such as @>:
testSql({jsonAttr: {[Op.contains]: [1,2,3]},});
which must produce:
("jsonAttr") @> '[1, 2, 3]'::jsonb
Alternative
ℹ️ this would IMO be the better solution, but we'd need to create that function at some point.
That's one approach, but we can also do it the other way around:
Sequelize could add a postgres function to the database sequelize_json_to_native or something. That method would use the built-in method json_typeof.
It would convert the json input based on the return value of json_typeof:
number: cast to decimal
boolean: cast to boolean
null: return native null
text: parse as JSON so we get the unquoted text
array & object: throw an error
Methods would then do this:
testSql({jsonAttr: null,});
produces:
sequelize_json_to_native("jsonAttr")ISnull
testSql({jsonAttr: {[Op.gt]: 10},});
produces:
sequelize_json_to_native("jsonAttr")>10
JSON operators would continue to not do any casting:
testSql({jsonAttr: {[Op.contains]: [1,2,3]},});
produces:
("jsonAttr") @> '[1, 2, 3]'::jsonb
and users could also do explicit casting to bypass the issue with arrays & objects not being strictly comparable:
breaking changeFor issues and PRs. Changes that break compatibility and require a major version increment.dialect: mariadbFor issues and PRs. Things that involve MariaDB (and do not involve all dialects).dialect: mysqlFor issues and PRs. Things that involve MySQL (and do not involve all dialects).dialect: postgresFor issues and PRs. Things that involve PostgreSQL (and do not involve all dialects).type: bugDEPRECATED: replace with the "bug" issue type
Activity
[-]Current MySQL nested JSON operations make it impossible to distinguish between the JSON `null` and a JSON string containing `"null"`[/-][+]Current MySQL/MariaDB nested JSON operations make it impossible to distinguish between the JSON `null` and a JSON string containing `"null"`[/+]frostzt commentedon Nov 9, 2022
Hey @ephys can I pick this up? Would love to have your advice on how to go about it.
WikiRik commentedon Nov 9, 2022
Maybe we should put this behaviour as an option so it's not enabled by default? I think that replacements and bind parameters should work in the most cases possible
ephys commentedon Nov 9, 2022
I don't think we should put it behind an option. If we do, no one is going to realize the issue during development and won't realize their code has bugs until it crashes in production :/
If we look at the possible scenarios, only one is impacted, the first one:
🔶 Scenario 1: Bind params or replacements in Model methods
This is the only scenario where the user would have do something differently from what they do today: If they try to use a bind parameter of replacement with a model method (such as
findAll), we're currently unable to know what the type of the replacement is, and we won't be able to callJSON.stringifyon it:would produce
That condition will always be false, making it very likely that the developer will notice the issue during development, and be able to fix it.
The fix is also very simple since the user can simply JSON stringify the parameter:
Or, once we support #14410, by specifying the type of their replacement:
both of which would produce
🟩 Scenario 2: Raw Queries
The query is already raw so it's already up to the user whether they use
json_unquoteor not. No changes there.🟩 Scenario 3: Typical model method calls (replacements)
Say the user writes the following:
We know
jsonis aJSONDataType, so we can stringify the value accordingly. No change for the user. We'll transparently produce the following queryInstead of this broken one:
🟩 Scenario 4: Typical model method calls (bind params)
Some methods, like
Model.updateuse bind parameters instead of replacements. But the same concept applies. We're responsible for generating these bind parameters so we can stringify them ourselves.will produce this:
with bind parameters
Whereas before it would have been this:
with bind parameters
ephys commentedon Nov 9, 2022
For sure! I'll edit this post with all the information I have.
There are two main places to update:
_toJSONValue. Instead of the current logic, it should just callJSON.stringifyon all inputsjsonPathExtractionQuerywhich should not have a call tojson_unquoteAnd as a test we can use the very first example in the first post of this thread
WikiRik commentedon Nov 9, 2022
If we're updating
jsonPathExtractionQueryit might be nice to merge this PR first; #15236ephys commentedon Nov 9, 2022
I'll go take a look at it :)
ephys commentedon Nov 9, 2022
We have the same issue in postgres with boolean & numeric keys, here is a failing test:
This is because we use
#>>in postgres which has the same issues asjson_unquote. I inserted the following JSON:{ "nullStr":"null", "null":null, "boolStr":"true", "bool":true, "numStr":"0", "num":0, "array":["a","b","c"], "arrayStr":"[\"a\",\"b\",\"c\"]", "object":{"a":"a"}, "objectStr":"{\"a\":\"a\"}" }Then ran the following query:
And it resulted in the following output:
Notice how, expect for null, all string versions are identical to the non-string version. This could be the source of many bugs.
Now if I use
#>instead:I get this, which is much better:
They're all of type
json. Now, it's not possible to compare json to anything. The following will fail because there is no operatorjson IS boolean.results in:
It's fine because we can cast the left-hand side based on the right hand side.
The following will work ✅:
And it's safe because it will only work with JSON fields that actually contain a boolean. Say it contains the string 'true' then it'll try to convert
"true"to a boolean which will fail:results in
TL;DR: For Postgres, we need to drop
#>>here: https://github.com/sequelize/sequelize/blob/main/src/dialects/postgres/query-generator.js#L1037, but we also need to case in operations based on the right-hand side:This needs a complete rework where we go through all JSON type and the different possible operators and we check what happens:
boolean: use#>, cast json to text then booleannumber: use#>, cast json to text then number#>>(which will return a postgres null instead of a json null) - preferred#>and compare to the string'null'without casting.#>cast left side to text and the right-hand value must be text that went throughJSON.stringify?Must not forget that some operators such as
@>and<@expect JSON, when these operators are used we cannot cast either side to text.I'm not going to lie @frostzt, this last part is going to be difficult. It's a non-trivial amount of work and is going to need a good updated test suite. The more I think about this the more edge-cases I find. Just look at this post's edit history lol
[-]Current MySQL/MariaDB nested JSON operations make it impossible to distinguish between the JSON `null` and a JSON string containing `"null"`[/-][+]Current MySQL/MariaDB/postgres nested JSON operations make it impossible to distinguish between the JSON `null` and a JSON string containing `"null"`[/+][-]Current MySQL/MariaDB/postgres nested JSON operations make it impossible to distinguish between the JSON `null` and a JSON string containing `"null"`[/-][+]Current MySQL/MariaDB/postgres nested JSON operations make it impossible to distinguish between the JSON `null`/`true` and a JSON string containing `"null"`/`"true"`[/+]WikiRik commentedon Nov 10, 2022
On the postgres topic; we have #14066 and associated PR #14099 to keep in mind as well
frostzt commentedon Nov 10, 2022
Hey @ephys yeah seems like this is gonna be a hard one, but someday will have to start on hard ones right :p do you think I would be able to take this on? Like maybe you and Rik can also guide me (ofc only when you have time) and I will also keep working on it post work?
ephys commentedon Nov 10, 2022
@WikiRik good opportunity to handle it at the same time. The same logic applies too, we should use
->and not->>@frostzt I honestly don't know. You can give it a try but it's definitely a complicated one
If you want to work on it I'd propose to do it in two steps: first write/update the unit tests, then we can look into implementing the code
We already have unit tests for JSON operations here:
https://github.com/sequelize/sequelize/blob/main/test/unit/sql/where.test.ts#L2134
https://github.com/sequelize/sequelize/blob/main/test/unit/sql/json.test.js#L98
https://github.com/sequelize/sequelize/blob/main/test/unit/sql/json.test.js#L167
They'll need to be updated. They can be regrouped in the same test file (such as
json.test.ts(note the ts extension)). Then for each one possible value we need to decide what the behavior should be.But again just for one dialect this is going to be a lot of work. This long post is just about postgres
There are multiple things to test such as:
how the json path is generated:
produces:
or
produce
or
produces
or
produces
how each JSON type is compared:
string
produces:
number
produces:
=or<>operator is used, we do this instead:and if another operator is used:
then we do this:
boolean
produces:
null
produces:
produces:
->>instead of->so both JSON null and postgres null are normalized to a postgres null, which can then be compared usingISarray and objects
Unsure how to handle these. I'd say JSON.stringify. But that means any spacing difference makes it fail:
produces?:
Then there are the JSON operators, such as
@>:which must produce:
Alternative
ℹ️ this would IMO be the better solution, but we'd need to create that function at some point.
That's one approach, but we can also do it the other way around:
Sequelize could add a postgres function to the database
sequelize_json_to_nativeor something. That method would use the built-in methodjson_typeof.It would convert the json input based on the return value of
json_typeof:Methods would then do this:
produces:
produces:
JSON operators would continue to not do any casting:
produces:
and users could also do explicit casting to bypass the issue with arrays & objects not being strictly comparable:
produces:
produces:
I think that's about it, but this is just postgres 😅
frostzt commentedon Nov 10, 2022
damn thanks a lot @ephys I'll give it a shot!
feat: rewrite the part of QueryGenerator responsible for WHERE (#15598)