-
-
Notifications
You must be signed in to change notification settings - Fork 171
docs: query builder #804
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
yagodorea
wants to merge
1
commit into
sequelize:main
Choose a base branch
from
yagodorea:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
docs: query builder #804
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| --- | ||
| title: Query Builder (experimental) | ||
| --- | ||
|
|
||
| The Query Builder provides a convenient and flexible interface to build arbitrary/complex queries programatically. | ||
|
|
||
| ## Usage | ||
|
|
||
| It can be instantiated from the desired model: | ||
|
|
||
| ```typescript | ||
| const query = User.select(); // Returns a QueryBuilder instance | ||
| ``` | ||
|
|
||
| This query builder uses a Builder pattern, each function returns a new immutable copy of the Query Builder with the new properties defined by the chain function. | ||
|
|
||
| ### Chaining options | ||
|
|
||
| - `.select()` - Called from the static model, will instantiate the QueryBuilder | ||
| - `.attributes()` - Sets desired attributes to be selected, will default to `*` if none are provided | ||
| - `.where()` - WHERE conditions for the query, normal sequelize `WhereOptions` are used here | ||
| - `.includes()` - Custom JOIN conditions with other models\*. The parameters for this are: | ||
| - `model: ModelStatic<M>` - Model to be joined with | ||
| - `as` - Alias for this model | ||
| - `on` - Mandatory join condition (`Record<keyof M, Col>`) | ||
| - `attributes` - Attributes to be selected | ||
| - `where` - Where conditions for this model | ||
| - `required` - If true, will be an inner join | ||
| - `joinType` - "LEFT" | "INNER" | "RIGHT" | ||
| - `.groupBy()` - GROUP BY clause (`GroupOption`) | ||
| - `.having()` - HAVING clause (`Literal`) | ||
| - `.andHaving()` - Chain an additional HAVING clause | ||
| - `.orderBy()` - ORDER BY clause (`Order`) | ||
| - `.limit()` - LIMIT number | ||
| - `.offset()` - OFFSET number | ||
|
|
||
| _\* = currently only supporting joining with base model, include inside include. But you can join multiple times with the base model_ | ||
|
|
||
| To return the built query, you need to invoke the `getQuery()` method. You can optionally send `{ multiline: true }` so the builder breakes the SQL into multiple lines for convenience. | ||
|
|
||
| Additionally, `.execute()` can be ran to run the query instead of returning it, it will return a result like a raw `.query()` call. Joins will explode the resulting rows, the query builder doesn't handle dependency aggregation. | ||
|
|
||
| ## Usage example | ||
|
|
||
| ```typescript | ||
| User.select() | ||
| .attributes(['name', ['age', 'userAge']]) | ||
| .includes({ | ||
| model: Post, | ||
| as: 'p', | ||
| on: sequelize.where(sequelize.col('User.id'), '=', sequelize.col('p.userId')), | ||
| attributes: ['title'], | ||
| where: { title: { [Op.iLike]: '%cr%' } }, | ||
| required: true, | ||
| }) | ||
| .includes({ | ||
| model: Comments, | ||
| as: 'c', | ||
| on: sequelize.where(sequelize.col('User.id'), '=', sequelize.col('c.userId')), | ||
| attributes: [[sequelize.literal('SUM("c"."likes")'), 'likeCount']], | ||
| joinType: 'LEFT', | ||
| }) | ||
| .where({ | ||
| [Op.or]: [ | ||
| { active: true }, | ||
| { | ||
| [Op.and]: [{ age: { [Op.gte]: 18 } }, { name: { [Op.iLike]: '%admin%' } }], | ||
| }, | ||
| ], | ||
| }) | ||
| .groupBy([sequelize.col('User.id'), sequelize.col('p.id')]) | ||
| .having(sequelize.literal('SUM("c"."likes") > 10')) | ||
| .andHaving(sequelize.literal('SUM("c"."likes") < 300')) | ||
| .orderBy([ | ||
| ['name', 'DESC'], | ||
| [sequelize.col('p.title'), 'ASC'], | ||
| ]) | ||
| .getQuery({ multiline: true }); | ||
| /** | ||
| * Returns: | ||
| SELECT "User"."name", "User"."age" AS "userAge", "p"."title" AS "p.title", SUM("c"."likes") AS "c.likeCount" | ||
| FROM "Users" AS "User" | ||
| INNER JOIN "Posts" AS "p" ON "User"."id" = "p"."userId" AND "p"."title" ILIKE '%cr%' | ||
| LEFT OUTER JOIN "Comments" AS "c" ON "User"."id" = "c"."userId" | ||
| WHERE ("User"."active" = true OR ("User"."age" >= 18 AND "User"."name" ILIKE '%admin%')) | ||
| GROUP BY "User"."id", "p"."id" | ||
| HAVING (SUM("c"."likes") > 10 AND SUM("c"."likes") < 300) | ||
| ORDER BY "User"."name" DESC, "p"."title" ASC; | ||
| */ | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
90 changes: 90 additions & 0 deletions
90
versioned_docs/version-6.x.x/other-topics/query-builder.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| --- | ||
| title: Query Builder (experimental) | ||
| --- | ||
|
|
||
| The Query Builder provides a convenient and flexible interface to build arbitrary/complex queries programatically. | ||
|
|
||
| ## Usage | ||
|
|
||
| It can be instantiated from the desired model: | ||
|
|
||
| ```typescript | ||
| const query = User.select(); // Returns a QueryBuilder instance | ||
| ``` | ||
|
|
||
| This query builder uses a Builder pattern, each function returns a new immutable copy of the Query Builder with the new properties defined by the chain function. | ||
|
|
||
| ### Chaining options | ||
|
|
||
| - `.select()` - Called from the static model, will instantiate the QueryBuilder | ||
| - `.attributes()` - Sets desired attributes to be selected, will default to `*` if none are provided | ||
| - `.where()` - WHERE conditions for the query, normal sequelize `WhereOptions` are used here | ||
| - `.includes()` - Custom JOIN conditions with other models\*. The parameters for this are: | ||
| - `model: ModelStatic<M>` - Model to be joined with | ||
| - `as` - Alias for this model | ||
| - `on` - Mandatory join condition (`Record<keyof M, Col>`) | ||
| - `attributes` - Attributes to be selected | ||
| - `where` - Where conditions for this model | ||
| - `required` - If true, will be an inner join | ||
| - `joinType` - "LEFT" | "INNER" | "RIGHT" | ||
| - `.groupBy()` - GROUP BY clause (`GroupOption`) | ||
| - `.having()` - HAVING clause (`Literal`) | ||
| - `.andHaving()` - Chain an additional HAVING clause | ||
| - `.orderBy()` - ORDER BY clause (`Order`) | ||
| - `.limit()` - LIMIT number | ||
| - `.offset()` - OFFSET number | ||
|
|
||
| _\* = currently only supporting joining with base model, include inside include. But you can join multiple times with the base model_ | ||
|
|
||
| To return the built query, you need to invoke the `getQuery()` method. You can optionally send `{ multiline: true }` so the builder breakes the SQL into multiple lines for convenience. | ||
|
|
||
| Additionally, `.execute()` can be ran to run the query instead of returning it, it will return a result like a raw `.query()` call. Joins will explode the resulting rows, the query builder doesn't handle dependency aggregation. | ||
|
|
||
| ## Usage example | ||
|
|
||
| ```typescript | ||
| User.select() | ||
| .attributes(['name', ['age', 'userAge']]) | ||
| .includes({ | ||
| model: Post, | ||
| as: 'p', | ||
| on: sequelize.where(sequelize.col('User.id'), '=', sequelize.col('p.userId')), | ||
| attributes: ['title'], | ||
| where: { title: { [Op.iLike]: '%cr%' } }, | ||
| required: true, | ||
| }) | ||
| .includes({ | ||
| model: Comments, | ||
| as: 'c', | ||
| on: sequelize.where(sequelize.col('User.id'), '=', sequelize.col('c.userId')), | ||
| attributes: [[sequelize.literal('SUM("c"."likes")'), 'likeCount']], | ||
| joinType: 'LEFT', | ||
| }) | ||
| .where({ | ||
| [Op.or]: [ | ||
| { active: true }, | ||
| { | ||
| [Op.and]: [{ age: { [Op.gte]: 18 } }, { name: { [Op.iLike]: '%admin%' } }], | ||
| }, | ||
| ], | ||
| }) | ||
| .groupBy([sequelize.col('User.id'), sequelize.col('p.id')]) | ||
| .having(sequelize.literal('SUM("c"."likes") > 10')) | ||
| .andHaving(sequelize.literal('SUM("c"."likes") < 300')) | ||
| .orderBy([ | ||
| ['name', 'DESC'], | ||
| [sequelize.col('p.title'), 'ASC'], | ||
| ]) | ||
| .getQuery({ multiline: true }); | ||
| /** | ||
| * Returns: | ||
| SELECT "User"."name", "User"."age" AS "userAge", "p"."title" AS "p.title", SUM("c"."likes") AS "c.likeCount" | ||
| FROM "Users" AS "User" | ||
| INNER JOIN "Posts" AS "p" ON "User"."id" = "p"."userId" AND "p"."title" ILIKE '%cr%' | ||
| LEFT OUTER JOIN "Comments" AS "c" ON "User"."id" = "c"."userId" | ||
| WHERE ("User"."active" = true OR ("User"."age" >= 18 AND "User"."name" ILIKE '%admin%')) | ||
| GROUP BY "User"."id", "p"."id" | ||
| HAVING (SUM("c"."likes") > 10 AND SUM("c"."likes") < 300) | ||
| ORDER BY "User"."name" DESC, "p"."title" ASC; | ||
| */ | ||
| ``` |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we don't accept new features in Sequelize 6