Repository navigation
Add support for MySQL JSON data type - #7106
Conversation
| // A recursive parser for nested where conditions | ||
| parseConditionObject(_conditions, path) { | ||
| path = path || []; | ||
| return Utils._.reduce(_conditions, (r, v, k) => { // result, key, value |
There was a problem hiding this comment.
the comment is wrong.
| }, | ||
|
|
||
| // A recursive parser for nested where conditions | ||
| parseConditionObject(_conditions, path) { |
There was a problem hiding this comment.
Is this method copied? If yes, you might wanna add it to AbstractQueryGenerator
| return str; | ||
| } | ||
| } else { | ||
| return AbstractQueryGenerator.handleSequelizeMethod.call(this, smth, tableName, factory, options, prepend); |
There was a problem hiding this comment.
super.handleSequelizeMethod()
| } | ||
| } | ||
|
|
||
| if (_.isPlainObject(value) && fieldType instanceof DataTypes.JSON) { |
There was a problem hiding this comment.
Why not allow class instances?
There was a problem hiding this comment.
No reason in particular, I inspired myself from the AbstractQueryGenerator. I'll remove it.
| } | ||
| } | ||
|
|
||
| return AbstractQueryGenerator.whereItemQuery.call(this, key, value, options); |
|
Thanks for the feedback @felixfbecker , I updated the code accordingly. |
|
Delighted that this is coming in! I'm testing some behavior in my own application and I'm seeing an error using However, placing this object into the 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: |
|
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 NULLCan you confirm that this is indeed the expected behaviour ? Thank you |
|
Probably needs to be rebased / repurposed on top of the changes from #7094, so we don't have too much duplicated code |
|
@janmeier , I updated the PR accordingly |
| where: { | ||
| data: { | ||
| employment: null | ||
| employment: current.dialect.name === 'mysql' ? 'null' : null |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
Yeah, it seems wrong to me too, but unfortunately, MySQL returns null as a string, rather than the null value.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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 tableMySQL 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) { |
There was a problem hiding this comment.
Seems at least partly duplicated from abstract query-generator. What's changed here?
There was a problem hiding this comment.
I added code to handle MySQL JSON queries. It's pretty similar to the sqlite query-generator.
| Sequelize.ARRAY(Sequelize.TEXT) // Defines an array. PostgreSQL only. | ||
|
|
||
| Sequelize.JSON // JSON column. PostgreSQL only. | ||
| Sequelize.JSON // JSON column. PostgreSQL and MySQL only. |
There was a problem hiding this comment.
Please add SQLite as well
| @@ -984,7 +984,7 @@ An OR query | |||
| ## `json(conditions, [value])` -> `Sequelize.json` | |||
There was a problem hiding this comment.
Remove all changes from this file, its auto generated, change actual comments in same file sequelize.js
| @@ -179,7 +179,7 @@ A key / value column. Only available in postgres. | |||
| ## `JSON()` | |||
There was a problem hiding this comment.
Change the actual file, its datatypes.js
| where: { | ||
| data: { | ||
| employment: null | ||
| employment: current.dialect.name === 'mysql' ? 'null' : null |
There was a problem hiding this comment.
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
| // 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 ? |
There was a problem hiding this comment.
Why this need special treatment for MySQL, it seems to work with Postgres and SQLite ?
| test('json function', function () { | ||
| expectsql(sql.handleSequelizeMethod(Sequelize.json(`json('{"profile":{"name":"david"}}')`)), { | ||
| default: `json('{"profile":{"name":"david"}}')` | ||
| if (current.dialect.name !== 'mysql') { |
There was a problem hiding this comment.
Why these tests ignored for MySQL ?
|
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 :) |
|
@rundef Please rebase |
|
@rundef any updates? |
|
@sushantdhiman @nytr0gen It's ready to be merged. |
|
Can you guys merge, please? |
^ Conflicts |
| }, | ||
|
|
||
| handleSequelizeMethod(smth, tableName, factory, options, prepend) { | ||
| if (smth instanceof Utils.Json) { |
There was a problem hiding this comment.
all this code has no coverage, please add tests for it
sushantdhiman
left a comment
There was a problem hiding this comment.
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
| }); | ||
|
|
||
| // JSONB Supports this, but not JSON in postgres/mysql | ||
| if (current.dialect.name !== 'postgres' && current.dialect.name !== 'mysql') { |
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
Looks same as SQLite's, is there any difference? SQLite inherits MySQL dialect, I would like to minimize duplicated code
There was a problem hiding this comment.
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'); | |||
There was a problem hiding this comment.
Some methods are copied from SQLite, SQLite inherits MySQL. Please find a way to reduce this duplicated code
sushantdhiman
left a comment
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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 | ||
| */ |
There was a problem hiding this comment.
Make this one private as well with underscore prefix
Add @private marker
| expectsql(sql.handleSequelizeMethod(Sequelize.json('json(\'{"profile":{"name":"david"}}\')')), { | ||
| default: 'json(\'{"profile":{"name":"david"}}\')' | ||
| default: 'json(\'{"profile":{"name":"david"}}\')', | ||
| //mysql: '`json(\'{"profile":{"name":"david"}}\')`->>\'$.\'' |
There was a problem hiding this comment.
can remove this line if its same as default. Please do the same for other tests below with commented mysql assertion
make requested changes
| test('json function', () => { | ||
| expectsql(sql.handleSequelizeMethod(Sequelize.json('json(\'{"profile":{"name":"david"}}\')')), { | ||
| default: 'json(\'{"profile":{"name":"david"}}\')' | ||
| default: 'json(\'{"profile":{"name":"david"}}\')', |
There was a problem hiding this comment.
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]'); |
There was a problem hiding this comment.
just to make sure, you meant with .number$ the end of the string, right?
|
yes, all good |
|
did this land in |
|
@akhoury Are you using mysql >= 5.7 ? |
|
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 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);
}
} |
Pull Request check-list
npm run testornpm run test-DIALECTpass with this change (including linting)?Futurein the changelog?Description of change
Add support for MySQL JSON data type