Skip to content

SQLite JSON datatype support (with JSON1 extension) - #7094

Merged
sushantdhiman merged 30 commits into
sequelize:masterfrom
rokoroku:sqlite-json
Feb 19, 2017
Merged

sushantdhiman merged 30 commits into
sequelize:masterfrom
rokoroku:sqlite-json

Conversation

@rokoroku

@rokoroku rokoroku commented Jan 10, 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 (part of JSON type should stringify/parse in mysql/mssql/sqlite #4873) or a description of the issue you are solving?
  • Have you added new tests to prevent regressions?
  • Have you added an entry under Future in the changelog?
  • Is a documentation update included (if this change modifies existing APIs, or introduces new ones)?

Description of change

Continued from #6500

  • Add supports for SQLite's built-in JSON datatype with JSON1 extension.

    (JSON1 extension is enabled with sqlite3 package 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:

    1. $contains on JSON field only supported via JSONB type, but described in JSON spec
    2. create index on JSON field only support via JSONB type, but described in JSON spec
  • Move each dialect's JSON path extraction query into whereItemQuery(...) in AbstractQueryGenerator and add new private API.

    from this PR, dialects that supports JSON path extraction query should override below method

  /**
   * Generates an SQL query that extract JSON property of given path.
   *
   * @param   {String}               column    The JSON column 
   * @param   {String|Array<String>} [path]    The path to extract (optional)
   * @returns {String}                         The generated sql query
   * @private
   */
  jsonPathExtractionQuery(column, path): String
  • Move common JSON dao test suites to abstract/dao.test.js

  • Add some injection preventions of JSON functions to each dialect's dao.js & dao.test.js.

  • Change postgres' CAST syntax for JSON column (before ::, after CAST(... AS ...) )

  • Update related files to use ES6 syntax.

Please let me know if there is something wrong or something to fix.

arcanis and others added 3 commits January 10, 2017 18:48
* add integration test for sqlite json

* add unit test for sqlite json

* fix inaccurate test for json from postgres
@codecov-io

codecov-io commented Jan 11, 2017 •

Copy link
Copy Markdown

Codecov Report

Merging #7094 into master will decrease coverage by -0.01%.
The diff coverage is 95.07%.


Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 8cbd375...f5885ce. Read the comment docs.

BaseTypes.GEOMETRY.types.sqlite = false;
BaseTypes.JSON.types.sqlite = ['JSON', 'JSONB'];

function JSONTYPE() {

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.

Just call it 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.

@rokoroku Also we will end up polluting internal JSON, leave it as JSONTYPE

@rokoroku rokoroku Jan 15, 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.

@sushantdhiman Oh, I understood you want me to erase JSONB from line 26.

So, would I just leave above code as it is?

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.

We need JSON.parse so we can't rename function itself, but its okay I think. So no changes

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

whereItemQuery(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.

Extra line

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'll fix it.

Comment thread lib/dialects/sqlite/query-generator.js Outdated
const result = items.join(' AND ');
return items.length > 1 ? '('+result+')' : result;
} else {
return MySqlQueryGenerator.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.

AbstractQueryGen

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 thought sqlite query-generator's __proto__ is set as MySqlQueryGenerator, so I use it in inheritance manner.
I'll change it anyway.

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.

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

Comment thread lib/dialects/sqlite/query-generator.js Outdated
return str;
}
} else {
return MySqlQueryGenerator.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.

AbsctractQueryGen

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.

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('.')}')`

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.

I dont want you to move it, just use replace MySqlQueryGenerator => AbstractQueryGenerator

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.

It should be possible to use Abstract Generator as MySQL doesn't define this method either ( it also depends upon Abstract)

Comment thread lib/dialects/sqlite/query-generator.js Outdated

// A recursive parser for nested where conditions
// (copied from ../postgres/query-generator.js)
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.

If this same method being used in both dialects, we should move it to AbstractQueryGen

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.

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');

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.

You dont need to include it, access it as this.sequelize

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.

OK

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']] });

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.

this.sequelize

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.

OK

@rokoroku rokoroku left a comment

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 commented with some question.
Anyway, I'll try to change things as you mentioned.

Comment thread lib/dialects/sqlite/query-generator.js Outdated

// A recursive parser for nested where conditions
// (copied from ../postgres/query-generator.js)
parseConditionObject(_conditions, path) {

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.

Sure, I'll try to move it to AbstractQueryGen.

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

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.

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('.')}')`

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

whereItemQuery(key, value, options) {

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'll fix it.

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

addColumnQuery(table, key, dataType) {

@rokoroku rokoroku Jan 14, 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.

@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']] });

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.

OK

Comment thread lib/dialects/sqlite/query-generator.js Outdated
const result = items.join(' AND ');
return items.length > 1 ? '('+result+')' : result;
} else {
return MySqlQueryGenerator.whereItemQuery.call(this, key, value, options);

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 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');

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.

OK

- 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

@rokoroku rokoroku Jan 14, 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.

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

@sushantdhiman

Copy link
Copy Markdown
Contributor

@rokoroku Please document that JSON supported fo SQLite as well

* A JSON string column. Only available in postgres.

@sushantdhiman

Copy link
Copy Markdown
Contributor

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

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 name the params result, key, value? More common though is previous, current, index
(even though I realize this is copy+pasted)

@rokoroku rokoroku Jan 16, 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.

Yes, I just copy-and-pasted existing things without many modification.
I'll change similar things anyway :)

Comment thread lib/dialects/sqlite/query-generator.js Outdated
if (smth instanceof Utils.Json) {
// Parse nested object
if (smth.conditions) {
const conditions = _.map(this.parseConditionObject(smth.conditions), condition =>

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 parseConditionObject returns an array, you can use array.map() 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.

That's right. (It's also copied code from postgres)

Comment thread lib/dialects/sqlite/query-generator.js Outdated

// Allow specifying conditions using the sqlite json1 functions
// https://sqlite.org/json1.html
if (/(json(?:_.*)*)\(.*\)/i.test(smth.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.

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?

@rokoroku rokoroku Jan 16, 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 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.

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.

@rokoroku Could you please add a case for SQL Injection attack (please check these tests for inspiration)

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.

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

Comment thread lib/dialects/sqlite/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/sqlite/query-generator.js Outdated
const result = items.join(' AND ');
return items.length > 1 ? '('+result+')' : result;
} else {
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.whereItemQuery()

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.

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.

@rokoroku rokoroku Jan 16, 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.

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.

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.

@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) {

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.

use arrow functions.

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.

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]}\'';

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.

use const.

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 agree

});

it('should update json using a custom field name', function() {
var self = this;

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.

use arrow functions.

@rokoroku rokoroku Jan 16, 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.

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) => {

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 omit parenthesis if there is only one parameter

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.

OK, it's not a problem

@rokoroku

rokoroku commented Jan 17, 2017 •

Copy link
Copy Markdown
Contributor Author

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

Copy link
Copy Markdown
Contributor Author

Add some prevention codes for possible injection I can think of.
Newly added method might looks bulky, but it effectively checks json_method brackets with quoted strings.

expect(users[0].field).to.be.deep.eql(point);
}
});
}).then(function () {

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 test has been removed?

@rokoroku

rokoroku commented Jan 27, 2017 •

Copy link
Copy Markdown
Contributor Author

While composing common methods to the abstract/query-generator, I found an inconsistency about the casting syntax of postgres.

Previously it uses :: casting syntax while generating json operation queries, but I changed it using Sequelize.Cast (See the changes from here: abstract/query-generator.js#dccadc-L1973) and added a new handleSequelizeMethod override for Sequelize.Cast in postgres/query-generator.js#dccadc-R234 to support multi-dialect JSON support without modifying whereItemsQuery.

Since it's difficult to make :: casting only for json method without overriding whereItemsQuery, I changed all existing test for postgres as using :: casting syntax for now.

Now we have three options:

  1. Use :: syntax for all postgres casting (current change)
  2. Use CAST() syntax as well as json operations. (needs all json test to be updated)
  3. Override whereItemsQuery in postgres/query-generator again to use the :: syntax only for json operations.

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.

@sushantdhiman

Copy link
Copy Markdown
Contributor

(1) This means we will have different casting syntax for different dialect, right ? Thats not an option

We can use (2) Use CAST() syntax as well as json operations. (needs all json test to be updated), this means JSON operation will use CAST as well, if its not very difficult to do, its a good option.

Finally, if its necessary than you can override whereItemsQuery in postgres

@rokoroku

rokoroku commented Feb 1, 2017

Copy link
Copy Markdown
Contributor Author

@sunshinewyin Agreed, and I think :: casting only for JSON methods is not necessary. The existing code was written in this way, but I prefer the way to use consistent syntax (2).

Then I will proceed with (2) :)

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

Small change with indentation

if (!schema) {
schema = 'public';
}
return 'SELECT pk.constraint_type as "Constraint", c.column_name as "Field", ' +

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.

There is only indentation change here, please revert it to original

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.

Sure, maybe my IDE formatted these lines.

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.

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

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.

No I dont want extra trailing spaces either. No change

@sushantdhiman

Copy link
Copy Markdown
Contributor

Would like reviews from @sequelize/core

@sushantdhiman

sushantdhiman commented Feb 3, 2017 •

Copy link
Copy Markdown
Contributor

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

@felixfbecker felixfbecker 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!

update jsdoc of jsonPathExtractionQuery to match the exact function arguments
@rokoroku

rokoroku commented Feb 3, 2017

Copy link
Copy Markdown
Contributor Author

Reviewed again, cleaned up some codes and updated description of changes :)

@sushantdhiman sushantdhiman mentioned this pull request Feb 4, 2017
4 of 5 tasks

@janmeier janmeier left a comment

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 a cursory review and some minor style things. Good work @rokoroku !! 🌮

jsonPathExtractionQuery(column, path) {
const paths = _.toPath(path);
const pathStr = `{${paths.join(',')}}`;
const quotedColumn = this.isIdentifierQuoted(column) ? column : this.quoteIdentifier(column);

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.

In what cases is the identifier already quoted?

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.

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;

@janmeier janmeier Feb 8, 2017 •

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.

These regexes can be placed outside the function, so they don't need to be compiled for each invocation

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 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 = /.../)

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.

Either that, or set them as (static) properties in the class, so we can keep them close to the function that uses them

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.

@janmeier you sure V8 will not optimize this?
@rokoroku I would uppercase it if it's a constant (not if it's a property)

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.

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.

yES!

@@ -0,0 +1,240 @@
'use strict';

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.

Please move this to test/integration/json.test.js or similar

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.

you mean this file?

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.

Yep

, current = Support.sequelize
, DataTypes = require(__dirname + '/../../../../lib/data-types');

describe('DAO', function () {

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.

DAO = model

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.

Sure :)

});
});

describe('JSON', function () {

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.

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

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.

Ummm... I'll try to get closer to the awesome human being.

@sushantdhiman
sushantdhiman merged commit 75841f3 into sequelize:master Feb 19, 2017
@janmeier

Copy link
Copy Markdown
Member

<3

@janmeier janmeier mentioned this pull request Feb 20, 2017
5 tasks done
@kevingilbert100

kevingilbert100 commented Mar 11, 2017 •

Copy link
Copy Markdown

When will this be in a NPM build? @sushantdhiman

mkaufmaner pushed a commit to mkaufmaner/sequelize that referenced this pull request Apr 25, 2017
* 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
@yonjah yonjah mentioned this pull request Aug 7, 2017
4 of 5 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants