Skip to content

feat: rewrite the part of QueryGenerator responsible for WHERE - #15598

Merged
ephys merged 50 commits into
mainfrom
ephys/new-query-generator-revisited
Mar 12, 2023
Merged

ephys merged 50 commits into
mainfrom
ephys/new-query-generator-revisited

Conversation

@ephys

@ephys ephys commented Jan 25, 2023 •

Copy link
Copy Markdown
Member

Pull Request Checklist

  • Have you added new tests to prevent regressions?
  • If a documentation update is necessary, have you opened a PR to the documentation repository?
  • Did you update the typescript typings accordingly (if applicable)?
  • Does the description below contain a link to an existing issue (Closes #[issue]) or a description of the issue you are solving?
  • Does the name of your PR follow our conventions?

Description Of Change

This PR is a reimplementation of #14020 against the modernized codebase. Hopefully now I'll be able to fix my very first bug report!

Closes #13602
Closes #13753
Closes #13773
Closes #15238
Closes #4494
Closes #13011
Closes #14099
Closes #5409
Closes #10599
Closes #13828
Closes #14066
Closes #10832
Closes #15237 (comment)

  • Remove all differences between the implementations of Sequelize.where() and pojo where objects (i.e. where: { firstName: 'zoé' }).
  • Fix the many bugs we had with the { attribute: value } syntax. See the where.test.ts to view the list of fixed bugs
  • Make Op.startsWith, Op.endsWith, Op.substring and their inverse support dynamic values & bind parameters.
  • Implements Add Sequelize.attr #13773. That feature is used in the new implementation
    • I named it sql.attribute instead of attr, but we can change it if you want. If we do, we'll want to consider naming sql.identifier -> sql.ident (but it's a bit too close to indent to my liking).
  • Partially implement Allow fn(), cast(), col(), etc… to be used in literal() #14299. Everything has been added except for unsafeReplacement(). We'll see if it is even needed.
    • The new "expression builders" are available on the sql tag (e.g. sql.attribute)
  • Be more strict: An invalid where object should throw with a message describing what is invalid, instead of crashing with an obscure message.
  • where() supports any value for both operands: Sequelize.where([], Op.eq, []) is valid
  • Replace how JSON extraction is done. See https://gist.github.com/ephys/f054c6fd343d09403f92e2e133929e04

Commit message body

Empty first line is important!


- The `Op.not` operator *always* means `NOT (x)`. If you need `IS NOT`, use `Op.isNot`, if you need `!=`, use `Op.ne`.
  This should not impact you much however, because writing `{ [Op.not]: 1 }` will be interpreted as `{ [Op.not]: { [Op.eq]: 1 } }` and will result in `NOT (x = 1)` instead of `x != 1`
- Removed the ability to use string operators in `where` (use the `sql` tag for that)
- Removed operator aliases (they were deprecated since Sequelize 5)
- Removed the ability to use an attribute object (one of the values of `Model.rawAttributes`) as one of the operands of `where`, it made little sense, was undocumented, and complicated the code.
- `or([])` produces `''` instead of `'0=1'`
- `not({})` produces `''` instead of `'0=1'`
- JSON operations now produce JSON strings (`->` operator) instead of unquoting them (`->>` operator) to fix https://github.com/sequelize/sequelize/issues/15238
- The `Json` class, that is produced by `json()` has been removed. `json()` now returns either `Where` or `Attribute` depending on its parameters.
- `json()` only accepts the sequelize JSON notation, it will not accept the dialect-specific syntaxes, or `json()` functions anymore. Use the `sql` tag, `literal` or `fn` for that
- Array values in replacements are not escaped as SQL Lists anymore, but as SQL arrays. If the user wishes to use a list, they need to wrap their array with the new `list()` method
- The signature of the `escape` method has changed. `escape` is now able to handle any SQL value (dynamic like `fn` or literal like `'a string'`) and accepts a `bindParam` option which can be used to make it add bind parameters instead of escaping
- Removed the ability to pass the value of the primary key directly to `where`. `User.findOne({ where: 1 })` will throw. Use `User.findByPk(1)` instead.
- `SequelizeMethod` has been renamed to `BaseSqlExpression`

Deprecations

  • Op.col is deprecated. Use sql.col(), sql.identifier() or sql.attribute()
  • json() is deprecated. Use sql.where(), sql.attribute() or sql.jsonPath()

Future PRs

@ephys

ephys commented Jan 26, 2023 •

Copy link
Copy Markdown
Member Author

With the partial implementation of #14299, we now have a lot of new top-level functions:

old:

  • where
  • fn
  • col (discouraged)
  • cast
  • literal
  • json (deprecated)

new:

  • list
  • identifier
  • attribute
  • sql
  • jsonPath

Some of them, like attribute use very common names and will likely clash with local variables when imported.

They can be accessed through Sequelize.x but Sequelize.literal is verbose.

Maybe we should make all of them properties of the sql tag? sql.identifier, sql.jsonPath, etc:

sql`SELECT * FROM ${sql.identifier('users')} WHERE ${sql.where({ id: 5 })}`

@ephys ephys changed the title feat: rewrite the part of QueryGenerator responsible for WHERE feat: rewrite the part of QueryGenerator responsible for WHERE Jan 26, 2023
@WikiRik

WikiRik commented Jan 27, 2023

Copy link
Copy Markdown
Member

Yes, I think properties of the sql tag would be good

@ephys

ephys commented Jan 27, 2023 •

Copy link
Copy Markdown
Member Author

This should fix #5409 too thanks to the new (not actually new, just extended to every attributes) casting syntax:

Project.destroy({
  where: {
    'myJsonColumn::text': '{}',
  },
});

Also #13828:

await Foo.count({ 
  where: {
    'myUuidColumn::text': { [Op.iLike]: '573b77ae%' },
  },
});

Something else I'm really happy about in the new implementation: Validation is cast aware ✨✨:

User.findAll({
  where: {
    // This makes Sequelize throw an error "12345678% is not a valid UUID"
    myUuid: '12345678%',
  },
});

// VS

User.findAll({
  where: {
    // With the cast, the DataType validator changes to DataTypes.TEXT and the query goes through just fine
    'myUuid::text': '12345678%',
  },
});

@ephys

ephys commented Feb 25, 2023

Copy link
Copy Markdown
Member Author

Breaking change documentation PR: sequelize/website#417

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

Initial review of tests, including notes to myself on some tests. I still need to go through the integration test files json.test.js, json.test.ts and model/json.test.js since there's also a lot changed there

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

Now I've gone through the updated code, looks very good. Don't understand all of it though, parts of the new whereSqlBuilder and the BNF parser are very like magic.

Now only those JSON integration tests to go and then slowly resolving my comments before we can start unleashing this to the rest of the alpha users

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