Skip to content

Add support for MySQL JSON data type - #7106

Merged
sushantdhiman merged 31 commits into
sequelize:masterfrom
rundef:mysql_json_datatype
Oct 26, 2017
Merged

sushantdhiman merged 31 commits into
sequelize:masterfrom
rundef:mysql_json_datatype

Conversation

@rundef

@rundef rundef commented Jan 13, 2017 •

Copy link
Copy Markdown
Contributor

Pull Request check-list

  • Does npm run test or npm run test-DIALECT pass with this change (including linting)?
  • Does your issue contain a link to existing issue (Closes MySQL JSON Data Type #4727) or a description of the issue you are solving?
  • Have you added new tests to prevent regressions?
  • Is a documentation update included (if this change modifies existing APIs, or introduces new ones)?
  • Have you added an entry under Future in the changelog?

Description of change

Add support for MySQL JSON data type

@codecov-io

codecov-io commented Jan 13, 2017 •

Copy link
Copy Markdown

Codecov Report

Merging #7106 into master will increase coverage by 0.09%.
The diff coverage is 95.14%.

Comment thread lib/dialects/mysql/query-generator.js Outdated
// A recursive parser for nested where conditions
parseConditionObject(_conditions, path) {
path = path || [];
return Utils._.reduce(_conditions, (r, v, k) => { // result, key, value

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the comment is wrong.

Comment thread lib/dialects/mysql/query-generator.js Outdated
},

// A recursive parser for nested where conditions
parseConditionObject(_conditions, path) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this method copied? If yes, you might wanna add it to AbstractQueryGenerator

Comment thread lib/dialects/mysql/query-generator.js Outdated
return str;
}
} else {
return AbstractQueryGenerator.handleSequelizeMethod.call(this, smth, tableName, factory, options, prepend);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

super.handleSequelizeMethod()

Comment thread lib/dialects/mysql/query-generator.js Outdated
}
}

if (_.isPlainObject(value) && fieldType instanceof DataTypes.JSON) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not allow class instances?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No reason in particular, I inspired myself from the AbstractQueryGenerator. I'll remove it.

Comment thread lib/dialects/mysql/query-generator.js Outdated
}
}

return AbstractQueryGenerator.whereItemQuery.call(this, key, value, options);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

super

@felixfbecker felixfbecker added type: feature DEPRECATED: replace with the "feature" issue type dialect: mysql For issues and PRs. Things that involve MySQL (and do not involve all dialects). labels Feb 11, 2017
@rundef

rundef commented Feb 14, 2017

Copy link
Copy Markdown
Contributor Author

Thanks for the feedback @felixfbecker , I updated the code accordingly.

@Sneagan

Sneagan commented Feb 16, 2017

Copy link
Copy Markdown

Delighted that this is coming in! I'm testing some behavior in my own application and I'm seeing an error using findOne with an object with a few levels. Running findOne with an object structured like the one below as the only argument results in a warning about using the where property of the options argument, but it appears to work as expected anyway.

{
    JSON_TYPED_PROP: {
        oneSet: [
            {
                code: "CODE_ONE",
                members: [
                    "AAAA"
                ]
            },
            {
                code: "CODE_TWO",
                members: [
                    "BBBB",
                    "CCCC"
                ]
            }
        ],
        oneObj: {
            DDDD: {
                code: "DDDD",
                specific: false
            },
            FFFF: {
                code: "GGGG",
                specific: false
            }
        }
    },
    effectiveDate: "2017-02-26T01:21:10.594Z"
}

However, placing this object into the where property of the options argument throws the following error:

Error: Invalid value [object Object]
 at escape (node_modules/sequelize/lib/sql-string.js:59:11)
 at wrapper (node_modules/lodash/lodash.js:5232:19)
 at Array.map (native)
 at Object.escape (node_modules/sequelize/lib/sql-string.js:55:16)
 at Object.escape (node_modules/sequelize/lib/dialects/abstract/query-generator.js:738:22)
 at Object.whereItemQuery (node_modules/sequelize/lib/dialects/abstract/query-generator.js:2120:22)
 at Object.whereItemQuery (node_modules/sequelize/lib/dialects/mysql/query-generator.js:281:50)
 at traverse (node_modules/sequelize/lib/dialects/mysql/query-generator.js:257:29)
 at _.forOwn (node_modules/sequelize/lib/dialects/mysql/query-generator.js:269:11)
 at node_modules/lodash/lodash.js:4944:15
 at baseForOwn (node_modules/lodash/lodash.js:3001:24)
 at Function.forOwn (node_modules/lodash/lodash.js:13002:24)
 at Object.whereItemQuery (node_modules/sequelize/lib/dialects/mysql/query-generator.js:261:11)
 at _.forOwn (node_modules/sequelize/lib/dialects/abstract/query-generator.js:1769:25)
 at node_modules/lodash/lodash.js:4944:15
 at baseForOwn (node_modules/lodash/lodash.js:3001:24)
 at Function.forOwn (node_modules/lodash/lodash.js:13002:24)
 at Object.whereItemsQuery (node_modules/sequelize/lib/dialects/abstract/query-generator.js:1768:9)
 at Object.getWhereConditions (node_modules/sequelize/lib/dialects/abstract/query-generator.js:2186:19)
 at Object.selectQuery (node_modules/sequelize/lib/dialects/abstract/query-generator.js:944:28)
 at QueryInterface.select (node_modules/sequelize/lib/query-interface.js:635:27)
 at Promise.try.then.then.then (node_modules/sequelize/lib/model.js:1513:34)

Some of the lines in this trace are part of the PR, though I have to admit I'm not currently familiar enough with the inner workings of Sequelize to know for sure that the edits are the cause. I'm willing to dig deeper and write a test case if you folks think the error might be related.

For reference, here's the definition of the model:

function theModel(sequelize, DataTypes) {
    return sequelize.define('theModel',
        {
            JSON_TYPED_PROP: {
                type: DataTypes.JSON
            },
            effectiveDate: {
                type: DataTypes.DATE(3),
                unique: true,
                reqired: true
            }
        },
        {
            freezeTableName: true,
            classMethods: {}
        }
    );
}

@rundef

rundef commented Feb 16, 2017 •

Copy link
Copy Markdown
Contributor Author

Hi,

Currently, passing array structures to search within a JSON field doesn't work.

In your example, I think that sequelize should end up generating a query like this:

/* search object properties -> supported */
WHERE `prop`->>'$.oneObj.DDDD.code' = 'DDDD' 
AND `prop`->>'$.oneObj.DDDD.specific' = false
AND `prop`->>'$.oneObj.FFFF.code' = 'GGGG' 
AND `prop`->>'$.oneObj.FFFF.specific' = false

/* search in arrays -> currently unsupported */
AND JSON_SEARCH(prop->>'$.oneSet', 'one', 'AAAA', NULL, '$[*].members[*]') IS NOT NULL
AND JSON_SEARCH(prop->>'$.oneSet', 'one', 'BBBB', NULL, '$[*].members[*]') IS NOT NULL
AND JSON_SEARCH(prop->>'$.oneSet', 'one', 'CCCC', NULL, '$[*].members[*]') IS NOT NULL
AND JSON_SEARCH(prop->>'$.oneSet', 'one', 'CODE_ONE', NULL, '$[*].code') IS NOT NULL
AND JSON_SEARCH(prop->>'$.oneSet', 'one', 'CODE_TWO', NULL, '$[*].code') IS NOT NULL

Can you confirm that this is indeed the expected behaviour ?

Thank you

@janmeier

Copy link
Copy Markdown
Member

Probably needs to be rebased / repurposed on top of the changes from #7094, so we don't have too much duplicated code

@rundef

rundef commented Feb 21, 2017

Copy link
Copy Markdown
Contributor Author

@janmeier , I updated the PR accordingly

Comment thread test/integration/model/json.test.js Outdated
where: {
data: {
employment: null
employment: current.dialect.name === 'mysql' ? 'null' : null

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems wrong to me - We are inserting literal null, but querying for the string null. Is this because it is actually inserted as the JSON value null, and not as a database null? What does postgres do in this case?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, it seems wrong to me too, but unfortunately, MySQL returns null as a string, rather than the null value.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we are inserting a SQL NULL we will get actual NULL back, our JSON processing is somehow turning null to 'null'. If we fix that this problem will not appear

@rundef rundef Mar 13, 2017 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not the sequelize JSON processing that is returning 'null' as a string. Let's say we have the following JSON data:

{ "test": null }

In that case, MySQL returns 'null' as a string when we run the following query:

SELECT data->>'$.test' FROM table

MySQL only returns NULL when the property doesn't exist in the JSON document.
I'm thinking about using the JSON_TYPE function because, in that case, it returns 'NULL' (rather than 'STRING').
So the final query would be something similiar to this:

SELECT * FROM table WHERE (data->>'$.test' IS NULL OR JSON_TYPE(data->>'$.test') = 'NULL')

return `ALTER TABLE ${this.quoteTable(tableName)} CHANGE ${attrString.join(', ')};`;
},

handleSequelizeMethod(smth, tableName, factory, options, prepend) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems at least partly duplicated from abstract query-generator. What's changed here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added code to handle MySQL JSON queries. It's pretty similar to the sqlite query-generator.

Comment thread docs/docs/models-definition.md Outdated
Sequelize.ARRAY(Sequelize.TEXT) // Defines an array. PostgreSQL only.

Sequelize.JSON // JSON column. PostgreSQL only.
Sequelize.JSON // JSON column. PostgreSQL and MySQL only.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add SQLite as well

Comment thread docs/api/sequelize.md Outdated
@@ -984,7 +984,7 @@ An OR query
## `json(conditions, [value])` -> `Sequelize.json`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove all changes from this file, its auto generated, change actual comments in same file sequelize.js

Comment thread docs/api/datatypes.md Outdated
@@ -179,7 +179,7 @@ A key / value column. Only available in postgres.
## `JSON()`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Change the actual file, its datatypes.js

Comment thread test/integration/model/json.test.js Outdated
where: {
data: {
employment: null
employment: current.dialect.name === 'mysql' ? 'null' : null

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we are inserting a SQL NULL we will get actual NULL back, our JSON processing is somehow turning null to 'null'. If we fix that this problem will not appear

Comment thread test/unit/sql/json.test.js Outdated
// Notice: [] will be replaced by dialect specific tick/quote character when there is not dialect specific expectation but only a default expectation

if (current.dialect.supports.JSON) {
const type = DataTypes[current.dialect.name].JSON ?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why this need special treatment for MySQL, it seems to work with Postgres and SQLite ?

Comment thread test/unit/sql/json.test.js Outdated
test('json function', function () {
expectsql(sql.handleSequelizeMethod(Sequelize.json(`json('{"profile":{"name":"david"}}')`)), {
default: `json('{"profile":{"name":"david"}}')`
if (current.dialect.name !== 'mysql') {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why these tests ignored for MySQL ?

@chrishutchinson

Copy link
Copy Markdown

What needs to be done to help get this across the line? Would be keen to see this be released officially soon as I have a few use cases :)

@sushantdhiman

Copy link
Copy Markdown
Contributor

@rundef PR will be merged after #8068. At that point PR may need rebase and bit rework. Hopefully Sequelize will have MySQL JSON support in 2 weeks

@sushantdhiman

Copy link
Copy Markdown
Contributor

@rundef Please rebase

@nytr0gen

Copy link
Copy Markdown

@rundef any updates?

@rundef

rundef commented Sep 28, 2017

Copy link
Copy Markdown
Contributor Author

@sushantdhiman @nytr0gen It's ready to be merged.

@antl3x

antl3x commented Sep 30, 2017

Copy link
Copy Markdown

Can you guys merge, please?

@sushantdhiman

Copy link
Copy Markdown
Contributor

Can you guys merge, please?

^ Conflicts

},

handleSequelizeMethod(smth, tableName, factory, options, prepend) {
if (smth instanceof Utils.Json) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

all this code has no coverage, please add tests for it

@sushantdhiman sushantdhiman left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need bit of refactoring as SQLite and MySQL are now having almost same methods. Refactor to make sure code is least duplicated between both dialect. SQLite inherits MySQL you can use this when refactoring

Comment thread test/integration/json.test.js Outdated
});

// JSONB Supports this, but not JSON in postgres/mysql
if (current.dialect.name !== 'postgres' && current.dialect.name !== 'mysql') {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only SQLite supports it then? Compare with dialect === 'sqlite' in that case

return `ALTER TABLE ${this.quoteTable(tableName)} CHANGE ${attrString.join(', ')};`;
},

handleSequelizeMethod(smth, tableName, factory, options, prepend) {

@sushantdhiman sushantdhiman Oct 1, 2017 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks same as SQLite's, is there any difference? SQLite inherits MySQL dialect, I would like to minimize duplicated code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They're different, and they both call AbstractQuery.handleSequelizeMethod() at the end, so there's no duplicated code here. I did however remove the _traverseJSON method which was duplicated.

@@ -3,6 +3,7 @@
const _ = require('lodash');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some methods are copied from SQLite, SQLite inherits MySQL. Please find a way to reduce this duplicated code

@sushantdhiman sushantdhiman left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, implementation wise. Please address some minor comments related to code.

Once those comments are addressed this PR will enter final review mode and we will try our best to release it as soon as possible :)

},

_castKey(key, value, cast) {
toJSONValue(value) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

make private _toJSONValue? I understand you are following toBooleanValue but I would like to keep these new methods private

* @param {String} stmt The statement to validate
* @returns {Boolean} true if the given statement is json function
* @throws {Error} throw if the statement looks like json function but has invalid token
*/

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make this one private as well with underscore prefix

Add @private marker

Comment thread test/unit/sql/json.test.js Outdated
expectsql(sql.handleSequelizeMethod(Sequelize.json('json(\'{"profile":{"name":"david"}}\')')), {
default: 'json(\'{"profile":{"name":"david"}}\')'
default: 'json(\'{"profile":{"name":"david"}}\')',
//mysql: '`json(\'{"profile":{"name":"david"}}\')`->>\'$.\''

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can remove this line if its same as default. Please do the same for other tests below with commented mysql assertion

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, thanks @jedwards1211 !

@sushantdhiman
sushantdhiman requested a review from a team October 21, 2017 18:59
Comment thread test/unit/sql/json.test.js Outdated
test('json function', () => {
expectsql(sql.handleSequelizeMethod(Sequelize.json('json(\'{"profile":{"name":"david"}}\')')), {
default: 'json(\'{"profile":{"name":"david"}}\')'
default: 'json(\'{"profile":{"name":"david"}}\')',

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this trailing comma is not needed
(as the next two as well)

// Convert .number. to [number].
path = path.replace(/\.(\d+)\./g, '[$1].');
// Convert .number$ to [number]
path = path.replace(/\.(\d+)$/, '[$1]');

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just to make sure, you meant with .number$ the end of the string, right?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, exactly

@sushantdhiman
sushantdhiman merged commit e40f6f4 into sequelize:master Oct 26, 2017
@sushantdhiman

Copy link
Copy Markdown
Contributor

Looks like all comments from @eseliger addressed.

Thanks @rundef 👍 , this will be released as v4.18.0

@eseliger

Copy link
Copy Markdown
Member

yes, all good

@akhoury

akhoury commented Dec 29, 2017 •

Copy link
Copy Markdown

did this land in v4.18? I'm on [email protected] with mysql and still got a SQL syntax error

Executing (default): CREATE TABLE IF NOT EXISTS `categories` (`id` INTEGER NOT NULL auto_increment , `name` VARCHAR(255), `services` JSON, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `parentId` INTEGER, PRIMARY KEY (`id`), FOREIGN KEY (`parentId`) REFERENCES `categories` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;
2017-12-29T17:55:37.478Z - error:  SequelizeDatabaseError: 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 'JSON, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `parentId` I' at line 1

@rundef

rundef commented Dec 29, 2017

Copy link
Copy Markdown
Contributor Author

@akhoury Are you using mysql >= 5.7 ?

@akhoury

akhoury commented Dec 29, 2017 •

Copy link
Copy Markdown

I am not, using 5.5, my bad. Thanks for pointing that out @rundef

For some reason, I thought Sequelize 4.18+ is adding JSON support by using TEXT, but JSON.stringifying on set and JSON.parseing on get, all under its hood 😄 independently from the database engine, so I ended doing this for a minute, but I will upgrade to mysql 5.7+

        services: {
            type: Sequelize.STRING,
            get() {
                const valstr = this.getDataValue('services');
                let val = null;
                try {
                    val = JSON.parse(valstr || '[]');
                } catch (e) {}
                return val;
            },
            set(val) {
                if (typeof val !== 'string') {
                    try {
                        val = JSON.stringify(val);
                    } catch (e) {
                        val = null;
                    }
                }
                this.setDataValue('services', val);
            }
        }

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

Labels

dialect: mysql For issues and PRs. Things that involve MySQL (and do not involve all dialects). type: feature DEPRECATED: replace with the "feature" issue type

Projects

None yet

Development

Successfully merging this pull request may close these issues.