Skip to content

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

Closed

Description

@ephys

Bug Description

Take the following example:

const Test = sequelize.define('Test', {
  json: DataTypes.JSON,
});

await sequelize.sync({ force: true });

await Test.create({
  json: { name: 'null' },
});

const results = await Test.findAll({
  where: {
    json: {
      name: null,
    },
  },
});

expect(results).to.have.lengthOf(0);

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".

This is the query it's using:

SELECT `id`, `json` FROM `Tests` AS `Test`
WHERE json_unquote(json_extract(`Test`.`json`,'$.\"name\"')) = '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.

If we take a query like this:

const results = await Test.findAll({
  where: {
    json: {
      name: "john",
    },
  },
});

Instead of producing this query:

SELECT `id`, `json` FROM `Tests` AS `Test`
WHERE json_unquote(json_extract(`Test`.`json`,'$.\"name\"')) = 'john'

It must produce this query:

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.

Activity

  1. added
    type: bug
    dialect: mysql
    breaking change
    dialect: mariadb
    on Nov 5, 2022
  2. 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
  3. frostzt commented on Nov 9, 2022

    @frostzt
    Member

    Hey @ephys can I pick this up? Would love to have your advice on how to go about it.

  4. WikiRik commented on Nov 9, 2022

    @WikiRik
    Member

    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

  5. ephys commented on Nov 9, 2022

    @ephys
    MemberAuthor

    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:

    Test.findAll({
      where: {
        json: {
          name: literal('$name'),
        },
      },
      replacements: {
        name: 'John',
      },
    })

    would produce

    SELECT `id`, `json` FROM `Tests` AS `Test`
    WHERE json_extract(`Test`.`json`,'$.\"name\"') = 'John'

    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:

    Test.findAll({
      where: {
        json: {
          name: literal('$name'),
        },
      },
      replacements: {
        name: JSON.stringify('John'),
      },
    })

    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 them
      replacementTypes: {
        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

    SELECT `id`, `json` FROM `Tests` AS `Test`
    WHERE json_extract(`Test`.`json`,'$.\"name\"') = '"John"'

    Instead of this broken one:

    SELECT `id`, `json` FROM `Tests` AS `Test`
    WHERE json_unquote(json_extract(`Test`.`json`,'$.\"name\"')) = 'John'

    🟩 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.

    Test.update({ password: null }, {
      where: {
        json: {
          name: 'John',
        },
      },
    })

    will produce this:

    UPDATE `Tests` SET `password` = ?
    WHERE json_extract(`Test`.`json`,'$.\"name\"') = ?

    with bind parameters

    // note how the second bind parameter has been JSON.stringify-ed by Sequelize
    [null, '"John"']

    Whereas before it would have been this:

    UPDATE `Tests` SET `password` = ?
    WHERE json_unquote(json_extract(`Test`.`json`,'$.\"name\"')) = ?

    with bind parameters

    // note how the second parameter isn't stringified because of the use of json_unquote
    [null, 'John']
  6. ephys commented on Nov 9, 2022

    @ephys
    MemberAuthor

    Hey @ephys can I pick this up? Would love to have your advice on how to go about it.

    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 call JSON.stringify on all inputs
    • Then there is jsonPathExtractionQuery which should not have a call to json_unquote

    And as a test we can use the very first example in the first post of this thread

  7. WikiRik commented on Nov 9, 2022

    @WikiRik
    Member

    If we're updating jsonPathExtractionQuery it might be nice to merge this PR first; #15236

  8. ephys commented on Nov 9, 2022

    @ephys
    MemberAuthor

    I'll go take a look at it :)

  9. ephys commented on Nov 9, 2022

    @ephys
    MemberAuthor

    We have the same issue in postgres with boolean & numeric keys, here is a failing test:

    await User.create({
      json: {
        name: 'true',
      }
    })
    
    const data = await User.findAll({
      where: {
        json: {
          name: true,
        }
      }
    });
      
    expect(data).to.have.length(0);

    This is because we use #>> in postgres which has the same issues as json_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:

    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:

    image

    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:

    image

    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:

    image


    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:

    (json#>ARRAY['boolStr'])::text::boolean IS true
    

    results in

    image


    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:

    (json#>ARRAY['boolStr'])::text::boolean IS true
    

    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

  10. 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
  11. 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
  12. added
    dialect: postgres
    on Nov 9, 2022
  13. WikiRik commented on Nov 10, 2022

    @WikiRik
    Member

    On the postgres topic; we have #14066 and associated PR #14099 to keep in mind as well

  14. frostzt commented on Nov 10, 2022

    @frostzt
    Member

    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?

  15. ephys commented on Nov 10, 2022

    @ephys
    MemberAuthor

    @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:

    testSql({
      jsonAttr: 'myString',
    });

    produces:

    "jsonAttr" = '"myString"'
    

    testSql({
      'jsonAttr.nested': 'myString',
    });

    or

    testSql({
      'jsonAttr': {
        nested: 'myString',
      },
    });

    produce

    "jsonAttr"->'nested' = '"myString"'
    

    testSql({
      'jsonAttr.0': 'myString',
    });

    or

    testSql({
      'jsonAttr': {
        0: 'myString',
      },
    });

    produces

    "jsonAttr"->0 = '"myString"'
    

    testSql({
      'jsonAttr.nested.twice': 'myString',
    });

    or

    testSql({
      'jsonAttr': {
        nested: {
          twice: 'myString',
        }
      },
    });

    produces

    ("jsonAttr"#>ARRAY['nested', 'twice']) = '"myString"'
    

    how each JSON type is compared:

    string

    testSql({
      jsonAttr: 'myString',
    });

    produces:

    "jsonAttr" = '"myString"'
    

    number

    testSql({
      jsonAttr: 12,
    });

    produces:

    ("jsonAttr")::text::decimal = 12
    

    ⚠️ 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") IS null

    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:

    testSql(where(cast(col("jsonAttr"), 'integer') Op.eq, 10))

    produces:

    ("jsonAttr")::integer = 10
    -- sequelize_json_to_native is not used because the value is already cast? Could be difficult 

    testSql(where(cast(col("jsonAttr"), 'text') Op.eq, JSON.stringify([1,2,3]))

    produces:

    ("jsonAttr")::text = '[1, 2, 3]'
    -- sequelize_json_to_native is not used because the value is already cast? Could be difficult 

    I think that's about it, but this is just postgres 😅

  16. frostzt commented on Nov 10, 2022

    @frostzt
    Member

    damn thanks a lot @ephys I'll give it a shot!

  17. self-assigned this
    on Jan 26, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

breaking changedialect: mariadbdialect: mysqldialect: postgrestype: bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions