Repository navigation
SQLite JSON datatype support (with JSON1 extension) - #7094
Conversation
* add integration test for sqlite json * add unit test for sqlite json * fix inaccurate test for json from postgres
Codecov Report
Continue to review full report at Codecov.
|
| BaseTypes.GEOMETRY.types.sqlite = false; | ||
| BaseTypes.JSON.types.sqlite = ['JSON', 'JSONB']; | ||
|
|
||
| function JSONTYPE() { |
There was a problem hiding this comment.
@rokoroku Also we will end up polluting internal JSON, leave it as JSONTYPE
There was a problem hiding this comment.
@sushantdhiman Oh, I understood you want me to erase JSONB from line 26.
So, would I just leave above code as it is?
There was a problem hiding this comment.
We need JSON.parse so we can't rename function itself, but its okay I think. So no changes
| }, | ||
|
|
||
| whereItemQuery(key, value, options) { | ||
|
|
| const result = items.join(' AND '); | ||
| return items.length > 1 ? '('+result+')' : result; | ||
| } else { | ||
| return MySqlQueryGenerator.whereItemQuery.call(this, key, value, options); |
There was a problem hiding this comment.
I thought sqlite query-generator's __proto__ is set as MySqlQueryGenerator, so I use it in inheritance manner.
I'll change it anyway.
There was a problem hiding this comment.
Correct but this should be fixed in future. Either method is shared using Abstract or defined in current instance. Cross dialect references couples dialect code, thus less freedom to change queries because of these references
| return str; | ||
| } | ||
| } else { | ||
| return MySqlQueryGenerator.handleSequelizeMethod.call(this, smth, tableName, factory, options, prepend); |
There was a problem hiding this comment.
Well, this method is bit different from postgres one.
in postgres, #>> syntax is used
`${this.quoteIdentifier(_.first(path))}#>>'{${_.tail(path).join(',')}}'`however, in sqlite, json_extract syntax is used
`json_extract(${this.quoteIdentifier(_.first(path))}, '$.${_.tail(path).join('.')}')`There was a problem hiding this comment.
I dont want you to move it, just use replace MySqlQueryGenerator => AbstractQueryGenerator
There was a problem hiding this comment.
It should be possible to use Abstract Generator as MySQL doesn't define this method either ( it also depends upon Abstract)
|
|
||
| // A recursive parser for nested where conditions | ||
| // (copied from ../postgres/query-generator.js) | ||
| parseConditionObject(_conditions, path) { |
There was a problem hiding this comment.
If this same method being used in both dialects, we should move it to AbstractQueryGen
There was a problem hiding this comment.
Sure, I'll try to move it to AbstractQueryGen.
| , dialect = Support.getTestDialect() | ||
| , DataTypes = require(__dirname + '/../../../../lib/data-types') | ||
| , dialect = Support.getTestDialect(); | ||
| , sequelize = require(__dirname + '/../../../../lib/sequelize'); |
There was a problem hiding this comment.
You dont need to include it, access it as this.sequelize
| return this.User.create({ username: 'swen', emergency_contact: emergencyContact }) | ||
| .then(function(user) { | ||
| expect(user.emergency_contact).to.eql(emergencyContact); | ||
| return self.User.find({ where: { username: 'swen' }, attributes: [[sequelize.json('emergency_contact.phones[1]'), 'firstEmergencyNumber']] }); |
rokoroku
left a comment
There was a problem hiding this comment.
I commented with some question.
Anyway, I'll try to change things as you mentioned.
|
|
||
| // A recursive parser for nested where conditions | ||
| // (copied from ../postgres/query-generator.js) | ||
| parseConditionObject(_conditions, path) { |
There was a problem hiding this comment.
Sure, I'll try to move it to AbstractQueryGen.
| return str; | ||
| } | ||
| } else { | ||
| return MySqlQueryGenerator.handleSequelizeMethod.call(this, smth, tableName, factory, options, prepend); |
There was a problem hiding this comment.
Well, this method is bit different from postgres one.
in postgres, #>> syntax is used
`${this.quoteIdentifier(_.first(path))}#>>'{${_.tail(path).join(',')}}'`however, in sqlite, json_extract syntax is used
`json_extract(${this.quoteIdentifier(_.first(path))}, '$.${_.tail(path).join('.')}')`| }, | ||
|
|
||
| whereItemQuery(key, value, options) { | ||
|
|
| }, | ||
|
|
||
| addColumnQuery(table, key, dataType) { | ||
|
|
There was a problem hiding this comment.
@sushantdhiman May I fix extra line (line 232), too?
| return this.User.create({ username: 'swen', emergency_contact: emergencyContact }) | ||
| .then(function(user) { | ||
| expect(user.emergency_contact).to.eql(emergencyContact); | ||
| return self.User.find({ where: { username: 'swen' }, attributes: [[sequelize.json('emergency_contact.phones[1]'), 'firstEmergencyNumber']] }); |
| const result = items.join(' AND '); | ||
| return items.length > 1 ? '('+result+')' : result; | ||
| } else { | ||
| return MySqlQueryGenerator.whereItemQuery.call(this, key, value, options); |
There was a problem hiding this comment.
I thought sqlite query-generator's __proto__ is set as MySqlQueryGenerator, so I use it in inheritance manner.
I'll change it anyway.
| , dialect = Support.getTestDialect() | ||
| , DataTypes = require(__dirname + '/../../../../lib/data-types') | ||
| , dialect = Support.getTestDialect(); | ||
| , sequelize = require(__dirname + '/../../../../lib/sequelize'); |
- Change MySqlQueryGenerator to AbstractQueryGenerator (sqlite) - Move parseConditionObject method to the AbstractQueryGenerator (sqlite, postgres) - Remove unnecessary module require - Remove extra lines
| var chai = require('chai') | ||
| , expect = chai.expect | ||
| , Support = require(__dirname + '/../../support') | ||
| , Sequelize = Support.Sequelize |
There was a problem hiding this comment.
json(...) is a static method within Sequelize class, but this.sequelize was an instance of Sequelize. (it causes test failure.)
So, I added Sequelize from Support.Sequelize here
|
LGTM, Its a big change, would also like reviews from other members of @sequelize/core |
| // A recursive parser for nested where conditions | ||
| parseConditionObject(conditions, path) { | ||
| path = path || []; | ||
| return _.reduce(conditions, (r, v, k) => { // result, key, value |
There was a problem hiding this comment.
why not name the params result, key, value? More common though is previous, current, index
(even though I realize this is copy+pasted)
There was a problem hiding this comment.
Yes, I just copy-and-pasted existing things without many modification.
I'll change similar things anyway :)
| if (smth instanceof Utils.Json) { | ||
| // Parse nested object | ||
| if (smth.conditions) { | ||
| const conditions = _.map(this.parseConditionObject(smth.conditions), condition => |
There was a problem hiding this comment.
If parseConditionObject returns an array, you can use array.map() here
There was a problem hiding this comment.
That's right. (It's also copied code from postgres)
|
|
||
| // Allow specifying conditions using the sqlite json1 functions | ||
| // https://sqlite.org/json1.html | ||
| if (/(json(?:_.*)*)\(.*\)/i.test(smth.path)) { |
There was a problem hiding this comment.
can you have nested parenthesis in the input, e.g using the result of a function as a parameter to the JSON function?
In that case a regexp will not suffice.
Shouldn't you pass a function call as sequelize.fn()?
Can this cause SQL injection if where comes from user input?
There was a problem hiding this comment.
It is derived code from lib/dialects/postgres/query-generator.js#L150
And it's tested by this spec:
it('should be able to retrieve a row based on the values of the json document', function() {
var self = this;
return this.sequelize.Promise.all([
this.User.create({ username: 'swen', emergency_contact: { name: 'kate' } }),
this.User.create({ username: 'anna', emergency_contact: { name: 'joe' } })])
.then(function() {
return self.User.find({ where: Sequelize.json(`json_extract(emergency_contact, '$.name')`, 'kate'), attributes: ['username', 'emergency_contact'] });
})
.then(function(user) {
expect(user.emergency_contact.name).to.equal('kate');
});
});which derived from test/integration/dialects/postgres/dao.test.js#L221
I do not understand sequelize as deeply as you, but the original code also seems to check just the query contains raw syntax or not. (means it allows user to use raw-string query, or query from Literal('...') maybe?)
If this is the case, and If user want to use raw queries, SQL injection should be protected above this raw-query layer (before create and call the query) I think.
If you have any suggestions, please let me know.
There was a problem hiding this comment.
@rokoroku Could you please add a case for SQL Injection attack (please check these tests for inspiration)
There was a problem hiding this comment.
@sushantdhiman That seems to be a test limited to the GEOMETRY type.
Unfortunately, I really do not have any knowledge of what kind of injection is possible for JSON methods. Please let me know if there is any easy reference.
| return str; | ||
| } | ||
| } else { | ||
| return AbstractQueryGenerator.handleSequelizeMethod.call(this, smth, tableName, factory, options, prepend); |
There was a problem hiding this comment.
super.handleSequelizeMethod()
| const result = items.join(' AND '); | ||
| return items.length > 1 ? '('+result+')' : result; | ||
| } else { | ||
| return AbstractQueryGenerator.whereItemQuery.call(this, key, value, options); |
There was a problem hiding this comment.
super.whereItemQuery()
There was a problem hiding this comment.
Calling super here will trigger MySQLQueryGen (as SQLITE inherits it), but super.whereItemQuery is not present in MySQLQueryGen (Although SQLite -> MySQL -> Abstract is true) but we should refer to AbstractQueryGen as we want to switch from MySQLQueryGen in future.
There was a problem hiding this comment.
According to MySQL JSON functions, they allows ->, ->> syntax to query JSON datatypes while SQLite does not.
And the following PR #7106 also implements whereItemQuery which returns ->> syntax
It works with super.whereItemQuery() for now, but there should be more differences in the future, so I agree that it should be switched from MySQLQueryGen someday.
There was a problem hiding this comment.
@rokoroku Please keep it AbstractQueryGen, I'll try to move SQLite away from MySQL dependency next weekend
| describe('json', function() { | ||
| it('should tell me that a column is json', function() { | ||
| return this.sequelize.queryInterface.describeTable('Users') | ||
| .then(function(table) { |
There was a problem hiding this comment.
OK, since I cannot change all the es5-styled files, I will convert at least this file to es6.
| }, { | ||
| fields: ['id', 'username', 'document', 'emergency_contact'], | ||
| logging: function(sql) { | ||
| var expected = '\'{"name":"joe","phones":[1337,42]}\''; |
| }); | ||
|
|
||
| it('should update json using a custom field name', function() { | ||
| var self = this; |
There was a problem hiding this comment.
For this, this reference is required so it cannot be replaced by arrow function..
- Convert es5 syntax to es6 for sqlite query-generator
| return self.User.findAll({ | ||
| where: { createdAt: { $gt: new Date(2012, 1, 1) }} | ||
| }).then(function(users) { | ||
| }).then((users) => { |
There was a problem hiding this comment.
please omit parenthesis if there is only one parameter
There was a problem hiding this comment.
OK, it's not a problem
|
While improving other tests to cover this PR, I found an issue that deleteQuery doesn't expand JSON methods in sqlite. So I'm now working on this. Update: done with baf75df |
- Add checkValidJsonStatement method to sqlite query-generator - Add injection tests for sqlite
|
Add some prevention codes for possible injection I can think of. |
| expect(users[0].field).to.be.deep.eql(point); | ||
| } | ||
| }); | ||
| }).then(function () { |
There was a problem hiding this comment.
Why this test has been removed?
|
While composing common methods to the Previously it uses Since it's difficult to make Now we have three options:
Please leave some comment about this, I will follow the decision. NOTE: the test is still failed for postgres. Since it related with casting syntax, I'm gonna fix them after this decision. |
|
We can use Finally, if its necessary than you can override |
|
@sunshinewyin Agreed, and I think Then I will proceed with |
sushantdhiman
left a comment
There was a problem hiding this comment.
Small change with indentation
| if (!schema) { | ||
| schema = 'public'; | ||
| } | ||
| return 'SELECT pk.constraint_type as "Constraint", c.column_name as "Field", ' + |
There was a problem hiding this comment.
There is only indentation change here, please revert it to original
There was a problem hiding this comment.
Sure, maybe my IDE formatted these lines.
There was a problem hiding this comment.
@sushantdhiman I reverted the indentation, but trailing whitespace has been removed since .editorconfig overrides trim_trailing_whitespace = true.
If you want revert the whitespaces as well, I'll try different editor.
There was a problem hiding this comment.
No I dont want extra trailing spaces either. No change
|
Would like reviews from @sequelize/core |
|
Now we are ready for final reviews from @sequelize/core team @rokoroku please change description for PR to match recent changes, so its easy for others to review. 👍 great work |
update jsdoc of jsonPathExtractionQuery to match the exact function arguments
|
Reviewed again, cleaned up some codes and updated description of changes :) |
| jsonPathExtractionQuery(column, path) { | ||
| const paths = _.toPath(path); | ||
| const pathStr = `{${paths.join(',')}}`; | ||
| const quotedColumn = this.isIdentifierQuoted(column) ? column : this.quoteIdentifier(column); |
There was a problem hiding this comment.
In what cases is the identifier already quoted?
There was a problem hiding this comment.
If it called via whereItemQuery. abstract/query-generator.js#1945
But not quoted when it called via Sequelize.json(). seepostgres/query-generator.js#211
| } | ||
|
|
||
| // https://www.postgresql.org/docs/current/static/functions-json.html | ||
| const jsonFunctionRegex = /^\s*((?:[a-z]+_){0,2}jsonb?(?:_[a-z]+){0,2})\([^)]*\)/i; |
There was a problem hiding this comment.
These regexes can be placed outside the function, so they don't need to be compiled for each invocation
There was a problem hiding this comment.
I didn't want to polute the query-generator class, but I agree with your suggestion.
May I place these regexps as class properties?
if so, should I use uppercased name? (e.g. const JSON_FUNCTION_REGEX = /.../)
There was a problem hiding this comment.
Either that, or set them as (static) properties in the class, so we can keep them close to the function that uses them
There was a problem hiding this comment.
| @@ -0,0 +1,240 @@ | |||
| 'use strict'; | |||
There was a problem hiding this comment.
Please move this to test/integration/json.test.js or similar
There was a problem hiding this comment.
you mean this file?
| , current = Support.sequelize | ||
| , DataTypes = require(__dirname + '/../../../../lib/data-types'); | ||
|
|
||
| describe('DAO', function () { |
| }); | ||
| }); | ||
|
|
||
| describe('JSON', function () { |
There was a problem hiding this comment.
OPTIONAL:
If you are a completely awesome human being, please rewrite these as unit tests ,along the lines of https://github.com/sequelize/sequelize/blob/master/test/unit/sql/json.test.js
There was a problem hiding this comment.
Ummm... I'll try to get closer to the awesome human being.
* Capitalize AND operator while generating json query via condition object
6deecc0 to
f5885ce
Compare
|
<3 |
|
When will this be in a NPM build? @sushantdhiman |
* Adds JSON support for sqlite * Add JSON support to sqlite query-generator * add integration test for sqlite json * add unit test for sqlite json * fix inaccurate test for json from postgres * Fix failing test spec in postgres * Change accroding to review - Change MySqlQueryGenerator to AbstractQueryGenerator (sqlite) - Move parseConditionObject method to the AbstractQueryGenerator (sqlite, postgres) - Remove unnecessary module require - Remove extra lines * Fix failing test with sequelize static reference * Add JSONB type alias to sqlite data types * Update changelog.md * Update jsdoc for JSON datatype * Updates from PR feedback - Convert es5 syntax to es6 for sqlite query-generator * Fix parenthesis with single parameter * Fix deleteQuery condition with JSON field * Update integration/data-types.test.js * Add JSON injection preventation code for sqlite - Add checkValidJsonStatement method to sqlite query-generator - Add injection tests for sqlite * Update sqlite JSON query-generator * Move common json DAO tests to abstract/dao.test.js - Add support for json property accessors (sqlite, postgres) * Fix wrong indentation in abstract/query-generator.js * Update query-generator.js to use common json method * Fix inconsistent postgres cast syntax * Update JSON test specs - Add injection test for postgres/query-generators.js - Replace default sql test expectation with specific dialect (postgres) - Update expectsql from test/support.js to throw error when no default expectation * Fix failing postgres test with cast * Fix postgres casting syntax * Fix failing test for postgres * Revert indentation of postgres query-generator * Cleanup unnecessarily added code update jsdoc of jsonPathExtractionQuery to match the exact function arguments * Move integration/dialects/abstract/dao.test.js to integration/json.test.js * Rewrite unit tests for json query-generator in unit/sql/json.test.js * Capitalize AND operator while generating json query via condition object * Fix failed tests
Pull Request check-list
npm run testornpm run test-DIALECTpass with this change (including linting)?Futurein the changelog?Description of change
Continued from #6500
Add supports for SQLite's built-in JSON datatype with JSON1 extension.
(JSON1 extension is enabled with
sqlite3package by default. (see node-sqlite3#538))Separate postgres' JSON tests into JSON and JSONB test
Since most of the existing JSON implementations (and test codes) were based on PostgreSQL, so I tried to seperate them. I think it will be better for future updates for JSON with other dialects. (for example, operators like
->>,#>>is only supported by postgres. It cannot be shared operator for JSON data type, IMHO)There seems like also inaccurate tests. What I fixed for postgres are:
Move each dialect's JSON path extraction query into
whereItemQuery(...)inAbstractQueryGeneratorand add new private API.from this PR, dialects that supports JSON path extraction query should override below method
Move common JSON dao test suites to
abstract/dao.test.jsAdd some injection preventions of JSON functions to each dialect's
dao.js&dao.test.js.Change postgres' CAST syntax for JSON column (before
::, afterCAST(... AS ...))Update related files to use ES6 syntax.
Please let me know if there is something wrong or something to fix.