Skip to content

mysql json type filter true and null has some problem #15237

Closed

Description

@lyf-coder

Issue Creation Checklist

  • I understand that my issue will be automatically closed if I don't fill in the requested information
  • I have read the contribution guidelines

Bug Description

when I find data through json type field use Op on json data's boolean attribute or no attribute (use null filter), others are ok but mysql is not.

it seems that the problem is caused by mysql query-generator.js _toJSONValue method

when query mysql true or null is converted to string 'true' or 'null' , Generally, there is no problem but in mysql json datatype, null is null,not 'null' . and also true is true not 'true',So it caused this problem

image

Reproducible Example

Here is the link to the SSCCE for this issue:
https://github.com/sequelize/sequelize-sscce/actions/runs/3400701706/jobs/5655301066

What do you expect to happen?

SELECT `id`, `name`, `schoolInfo` FROM `Foos` AS `Foo` WHERE json_unquote(json_extract(`Foo`.`schoolInfo`,'$.\"isRegister\"')) IS null; 

What is actually happening?

SELECT `id`, `name`, `schoolInfo` FROM `Foos` AS `Foo` WHERE json_unquote(json_extract(`Foo`.`schoolInfo`,'$.\"isRegister\"')) IS 'null';

{ Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''null'' at line 1

Environment

  • Sequelize version: 6.x
  • Node.js version: 16.x
  • If TypeScript related: TypeScript version:
  • Database & Version: mysql 5.7
  • Connector library & Version:

Would you be willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time and I know how to start.
  • Yes, I have the time but I will need guidance.
  • No, I don't have the time, but my company or I are supporting Sequelize through donations on OpenCollective.
  • No, I don't have the time, and I understand that I will need to wait until someone from the community or maintainers is interested in resolving my issue.

Indicate your interest in the resolution of this issue by adding the 👍 reaction. Comments such as "+1" will be removed.

Activity

  1. WikiRik commented on Nov 5, 2022

    @WikiRik
    Member

    For the person that will look into this:

    We have a test that is related to this behaviour, but it doesn't use operators;

    it('should be possible to query a nested null value', async function () {
    await Promise.all([this.Event.create({
    data: {
    name: {
    first: 'Homer',
    last: 'Simpson',
    },
    employment: 'Nuclear Safety Inspector',
    },
    }), this.Event.create({
    data: {
    name: {
    first: 'Marge',
    last: 'Simpson',
    },
    employment: null,
    },
    })]);
    const events = await this.Event.findAll({
    where: {
    data: {
    employment: null,
    },
    },
    });
    expect(events.length).to.equal(1);
    expect(events[0].get('data')).to.eql({
    name: {
    first: 'Marge',
    last: 'Simpson',
    },
    employment: null,
    });
    });

  2. ephys commented on Nov 5, 2022

    @ephys
    Member

    This is "normal" and not caused by _toJSONValue.
    In MySQL, the JSON column and JSON functions just return text. It's not a true null nor boolean value. This can be demonstrated by running the following SQL:

    CREATE TABLE test (
      json JSON NOT NULL
    );
    
    INSERT INTO test (json) VALUES ('{"a": null, "b": true}');
    
    SELECT json_unquote(json_extract(json, '$.a')) IS null AS a_is_null, -- false
           json_unquote(json_extract(json, '$.b')) IS true AS b_is_true -- false
    FROM test;
    
    SELECT json_unquote(json_extract(json, '$.a')) = 'null' AS a_is_null, -- true
           json_unquote(json_extract(json, '$.b')) = 'true' AS b_is_true -- true
    FROM test;

    You can't use Op.is in nested JSON in MySQL

    If we need to fix something, it's replacing Op.is with = in MySQL when using JSON (but I don't think we should. This should be documented instead)

  3. lyf-coder commented on Nov 6, 2022

    @lyf-coder
    Author

    For the person that will look into this:

    We have a test that is related to this behaviour, but it doesn't use operators;

    it('should be possible to query a nested null value', async function () {
    await Promise.all([this.Event.create({
    data: {
    name: {
    first: 'Homer',
    last: 'Simpson',
    },
    employment: 'Nuclear Safety Inspector',
    },
    }), this.Event.create({
    data: {
    name: {
    first: 'Marge',
    last: 'Simpson',
    },
    employment: null,
    },
    })]);
    const events = await this.Event.findAll({
    where: {
    data: {
    employment: null,
    },
    },
    });
    expect(events.length).to.equal(1);
    expect(events[0].get('data')).to.eql({
    name: {
    first: 'Marge',
    last: 'Simpson',
    },
    employment: null,
    });
    });

    Thanks for your reply,My expression is not very accurate. I mean null because this attribute is not stored, such as in your example,I insert data:

    { 
         data: { 
           name: { 
             first: 'Marge1', 
             last: 'Simpson1', 
           }, 
         }, 
       }
    

    It's not have employment attribute, I want to find out the records that do not contain this attribute,Is there any way to do it ? @WikiRik

  4. lyf-coder commented on Nov 6, 2022

    @lyf-coder
    Author

    This is "normal" and not caused by _toJSONValue. In MySQL, the JSON column and JSON functions just return text. It's not a true null nor boolean value. This can be demonstrated by running the following SQL:

    CREATE TABLE test (
      json JSON NOT NULL
    );
    
    INSERT INTO test (json) VALUES ('{"a": null, "b": true}');
    
    SELECT json_unquote(json_extract(json, '$.a')) IS null AS a_is_null, -- false
           json_unquote(json_extract(json, '$.b')) IS true AS b_is_true -- false
    FROM test;
    
    SELECT json_unquote(json_extract(json, '$.a')) = 'null' AS a_is_null, -- true
           json_unquote(json_extract(json, '$.b')) = 'true' AS b_is_true -- true
    FROM test;

    You can't use Op.is in nested JSON in MySQL

    If we need to fix something, it's replacing Op.is with = in MySQL when using JSON

    @ephys Thanks for your reply,

    // first record
    INSERT INTO test (json) VALUES ('{"a": null, "b": true}');
    // second record.  b is false
    INSERT INTO test (json) VALUES ('{"a": null, "b": false}');
    // third record.  not contain 'b' attribute
    INSERT INTO test (json) VALUES ('{"a": null}');

    I want to find second and third records through attribute 'b' , Is there any way to do it ?

  5. ephys commented on Nov 6, 2022

    @ephys
    Member

    I want to find second and third records through attribute 'b' , Is there any way to do it ?

    Use Op.eq instead of Op.is

  6. lyf-coder commented on Nov 6, 2022

    @lyf-coder
    Author

    I want to find second and third records through attribute 'b' , Is there any way to do it ?

    Use Op.eq instead of Op.is

    @ephys thanks again!
    but when use Op.eq,
    sql is : SELECT * FROM test WHERE json_unquote(json_extract(json,'$.\"b\"')) = 'null'; it can't find third record: {"a": null}
    I need sql is :SELECT * FROM test WHERE json_unquote(json_extract(json,'$.\"b\"')) is null; At present, it seems that no operator can do it. 😂

  7. ephys commented on Nov 6, 2022

    @ephys
    Member

    Ah yes sorry I misread that. Do this:

    const results = await Test.findAll({
      where: {
        json: {
          name: { [Op.is]: literal('null') },
        },
      },
    });

    It will bypass the JSON serialization and produce

    SELECT `id`, `json` FROM `Tests` AS `Test` 
    WHERE json_unquote(json_extract(`Test`.`json`,'$."name"')) IS null;

    instead of

    SELECT `id`, `json` FROM `Tests` AS `Test` 
    WHERE json_unquote(json_extract(`Test`.`json`,'$."name"')) IS 'null';

    If you want to catch both MySQL's null and JSON's null:

    const results = await Test.findAll({
      where: or({
        json: {
          // MySQL null value (which is returned when "name" is not present in the JSON object)
          name: { [Op.is]: literal('null') },
        },
      }, {
        json: {
          // JSON null value (which is returned when "name" is present in the JSON object, but is null)
          name: null,
        },
      }),
    });

    Which will produce this:

    SELECT `id`, `json` FROM `Tests` AS `Test` 
    WHERE (
          json_unquote(json_extract(`Test`.`json`,'$."name"')) IS null 
       OR json_unquote(json_extract(`Test`.`json`,'$."name"')) = 'null'
    );

    MySQL's support for JSON is a bit poor imo 😬

  8. added
    docs
    on Nov 6, 2022
  9. ephys commented on Nov 6, 2022

    @ephys
    Member

    I'm labelling this as docs, we'll need to document this caveat

  10. lyf-coder commented on Nov 7, 2022

    @lyf-coder
    Author

    @ephys Thank you very much. It was solved,👍👍👍

  11. reopened this on Nov 7, 2022
  12. ephys commented on Nov 7, 2022

    @ephys
    Member

    I'll keep this open a little bit longer to remind us to document this :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    docs

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions