From cf27c662c59d22ec05e468d16a7634e373d133e4 Mon Sep 17 00:00:00 2001 From: George Zhao Date: Wed, 12 Jan 2022 21:07:05 +1100 Subject: [PATCH] fix(model.d): fix type for `count` and `findAndCountAll` (#13786) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(model): add stop mysql-8 script * fix(model): fix type for `count` and `findAndCountAll` Co-authored-by: ZoƩ --- .../core-concepts/model-querying-finders.md | 171 +++++++++--------- package.json | 1 + types/lib/model.d.ts | 32 ++-- types/test/{count.ts => model-count.ts} | 3 +- types/test/model.ts | 15 +- 5 files changed, 122 insertions(+), 100 deletions(-) rename types/test/{count.ts => model-count.ts} (76%) diff --git a/docs/manual/core-concepts/model-querying-finders.md b/docs/manual/core-concepts/model-querying-finders.md index c5644a9dca57..ebe6c5820324 100644 --- a/docs/manual/core-concepts/model-querying-finders.md +++ b/docs/manual/core-concepts/model-querying-finders.md @@ -1,83 +1,88 @@ -# Model Querying - Finders - -Finder methods are the ones that generate `SELECT` queries. - -By default, the results of all finder methods are instances of the model class (as opposed to being just plain JavaScript objects). This means that after the database returns the results, Sequelize automatically wraps everything in proper instance objects. In a few cases, when there are too many results, this wrapping can be inefficient. To disable this wrapping and receive a plain response instead, pass `{ raw: true }` as an option to the finder method. - -## `findAll` - -The `findAll` method is already known from the previous tutorial. It generates a standard `SELECT` query which will retrieve all entries from the table (unless restricted by something like a `where` clause, for example). - -## `findByPk` - -The `findByPk` method obtains only a single entry from the table, using the provided primary key. - -```js -const project = await Project.findByPk(123); -if (project === null) { - console.log('Not found!'); -} else { - console.log(project instanceof Project); // true - // Its primary key is 123 -} -``` - -## `findOne` - -The `findOne` method obtains the first entry it finds (that fulfills the optional query options, if provided). - -```js -const project = await Project.findOne({ where: { title: 'My Title' } }); -if (project === null) { - console.log('Not found!'); -} else { - console.log(project instanceof Project); // true - console.log(project.title); // 'My Title' -} -``` - -## `findOrCreate` - -The method `findOrCreate` will create an entry in the table unless it can find one fulfilling the query options. In both cases, it will return an instance (either the found instance or the created instance) and a boolean indicating whether that instance was created or already existed. - -The `where` option is considered for finding the entry, and the `defaults` option is used to define what must be created in case nothing was found. If the `defaults` do not contain values for every column, Sequelize will take the values given to `where` (if present). - -Let's assume we have an empty database with a `User` model which has a `username` and a `job`. - -```js -const [user, created] = await User.findOrCreate({ - where: { username: 'sdepold' }, - defaults: { - job: 'Technical Lead JavaScript' - } -}); -console.log(user.username); // 'sdepold' -console.log(user.job); // This may or may not be 'Technical Lead JavaScript' -console.log(created); // The boolean indicating whether this instance was just created -if (created) { - console.log(user.job); // This will certainly be 'Technical Lead JavaScript' -} -``` - -## `findAndCountAll` - -The `findAndCountAll` method is a convenience method that combines `findAll` and `count`. This is useful when dealing with queries related to pagination where you want to retrieve data with a `limit` and `offset` but also need to know the total number of records that match the query. - -The `findAndCountAll` method returns an object with two properties: - -* `count` - an integer - the total number records matching the query -* `rows` - an array of objects - the obtained records - -```js -const { count, rows } = await Project.findAndCountAll({ - where: { - title: { - [Op.like]: 'foo%' - } - }, - offset: 10, - limit: 2 -}); -console.log(count); -console.log(rows); -``` \ No newline at end of file +# Model Querying - Finders + +Finder methods are the ones that generate `SELECT` queries. + +By default, the results of all finder methods are instances of the model class (as opposed to being just plain JavaScript objects). This means that after the database returns the results, Sequelize automatically wraps everything in proper instance objects. In a few cases, when there are too many results, this wrapping can be inefficient. To disable this wrapping and receive a plain response instead, pass `{ raw: true }` as an option to the finder method. + +## `findAll` + +The `findAll` method is already known from the previous tutorial. It generates a standard `SELECT` query which will retrieve all entries from the table (unless restricted by something like a `where` clause, for example). + +## `findByPk` + +The `findByPk` method obtains only a single entry from the table, using the provided primary key. + +```js +const project = await Project.findByPk(123); +if (project === null) { + console.log('Not found!'); +} else { + console.log(project instanceof Project); // true + // Its primary key is 123 +} +``` + +## `findOne` + +The `findOne` method obtains the first entry it finds (that fulfills the optional query options, if provided). + +```js +const project = await Project.findOne({ where: { title: 'My Title' } }); +if (project === null) { + console.log('Not found!'); +} else { + console.log(project instanceof Project); // true + console.log(project.title); // 'My Title' +} +``` + +## `findOrCreate` + +The method `findOrCreate` will create an entry in the table unless it can find one fulfilling the query options. In both cases, it will return an instance (either the found instance or the created instance) and a boolean indicating whether that instance was created or already existed. + +The `where` option is considered for finding the entry, and the `defaults` option is used to define what must be created in case nothing was found. If the `defaults` do not contain values for every column, Sequelize will take the values given to `where` (if present). + +Let's assume we have an empty database with a `User` model which has a `username` and a `job`. + +```js +const [user, created] = await User.findOrCreate({ + where: { username: 'sdepold' }, + defaults: { + job: 'Technical Lead JavaScript' + } +}); +console.log(user.username); // 'sdepold' +console.log(user.job); // This may or may not be 'Technical Lead JavaScript' +console.log(created); // The boolean indicating whether this instance was just created +if (created) { + console.log(user.job); // This will certainly be 'Technical Lead JavaScript' +} +``` + +## `findAndCountAll` + +The `findAndCountAll` method is a convenience method that combines `findAll` and `count`. This is useful when dealing with queries related to pagination where you want to retrieve data with a `limit` and `offset` but also need to know the total number of records that match the query. + +When `group` is not provided, the `findAndCountAll` method returns an object with two properties: + +* `count` - an integer - the total number records matching the query +* `rows` - an array of objects - the obtained records + +When `group` is provided, the `findAndCountAll` method returns an object with two properties: + +* `count` - an array of objects - contains the count in each group and the projected attributes +* `rows` - an array of objects - the obtained records + +```js +const { count, rows } = await Project.findAndCountAll({ + where: { + title: { + [Op.like]: 'foo%' + } + }, + offset: 10, + limit: 2 +}); +console.log(count); +console.log(rows); +``` diff --git a/package.json b/package.json index 27ef9469c271..46c347add7a5 100644 --- a/package.json +++ b/package.json @@ -233,6 +233,7 @@ "start-db2": "bash dev/db2/11.5/start.sh", "stop-mariadb": "bash dev/mariadb/10.3/stop.sh", "stop-mysql": "bash dev/mysql/5.7/stop.sh", + "stop-mysql-8": "bash dev/mysql/8.0/stop.sh", "stop-postgres": "bash dev/postgres/10/stop.sh", "stop-mssql": "bash dev/mssql/2019/stop.sh", "stop-db2": "bash dev/db2/11.5/stop.sh", diff --git a/types/lib/model.d.ts b/types/lib/model.d.ts index 7467bc0d1379..bb0502032b89 100644 --- a/types/lib/model.d.ts +++ b/types/lib/model.d.ts @@ -633,17 +633,15 @@ export interface CountOptions /** * Options for Model.count when GROUP BY is used */ -export interface CountWithOptions extends CountOptions { - /** - * GROUP BY in sql - * Used in conjunction with `attributes`. - * @see Projectable - */ - group: GroupOption; -} +export type CountWithOptions = SetRequired, 'group'> export interface FindAndCountOptions extends CountOptions, FindOptions { } +interface GroupedCountResultItem { + [key: string]: unknown // projected attributes + count: number // the count for each group +} + /** * Options for Model.build method */ @@ -1902,25 +1900,27 @@ export abstract class Model( this: ModelStatic, options: CountWithOptions - ): Promise>; + ): Promise; /** * Count the number of records matching the provided where clause. * * If you provide an `include` option, the number of matching associations will be counted instead. + * @return Returns count for each group and the projected attributes. */ public static count( this: ModelStatic, - options?: CountOptions + options?: Omit, 'group'> ): Promise; /** * Find all the rows matching your query, within a specified offset / limit, and get the total number of - * rows matching your query. This is very usefull for paging + * rows matching your query. This is very useful for paging * * ```js * Model.findAndCountAll({ @@ -1952,6 +1952,14 @@ export abstract class Model( this: ModelStatic, @@ -1960,7 +1968,7 @@ export abstract class Model( this: ModelStatic, options: SetRequired, 'group'> - ): Promise<{ rows: M[]; count: number[] }>; + ): Promise<{ rows: M[]; count: GroupedCountResultItem[] }>; /** * Find the maximum value of field diff --git a/types/test/count.ts b/types/test/model-count.ts similarity index 76% rename from types/test/count.ts rename to types/test/model-count.ts index eff1682e89a6..7c9ea96a5de5 100644 --- a/types/test/count.ts +++ b/types/test/model-count.ts @@ -4,8 +4,7 @@ import { Model, Op } from 'sequelize'; class MyModel extends Model {} expectTypeOf(MyModel.count()).toEqualTypeOf>(); -expectTypeOf(MyModel.count({ group: 'tag' })) - .toEqualTypeOf>>(); +expectTypeOf(MyModel.count({ group: 'tag' })).toEqualTypeOf>(); expectTypeOf(MyModel.count({ col: 'tag', distinct: true })).toEqualTypeOf>(); expectTypeOf(MyModel.count({ where: { diff --git a/types/test/model.ts b/types/test/model.ts index f3b3d0624e05..870d8be2dc76 100644 --- a/types/test/model.ts +++ b/types/test/model.ts @@ -52,13 +52,22 @@ MyModel.findAndCountAll({ include: OtherModel }).then(({ count, rows }) => { }); MyModel.findAndCountAll({ include: OtherModel, group: ['MyModel.num'] }).then(({ count, rows }) => { - expectTypeOf(count).toEqualTypeOf(); + expectTypeOf(count).toEqualTypeOf<({ [key: string]: unknown, count: number })[]>(); expectTypeOf(rows).toEqualTypeOf(); }); -MyModel.count({ include: OtherModel }); +MyModel.count({ include: OtherModel }).then((count) => { + expectTypeOf(count).toEqualTypeOf(); +}); + +MyModel.count({ include: [MyModel], where: { '$num$': [10, 120] } }).then((count) => { + expectTypeOf(count).toEqualTypeOf(); +}); -MyModel.count({ include: [MyModel], where: { '$num$': [10, 120] } }); +MyModel.count({ group: 'type' }).then((result) => { + expectTypeOf(result).toEqualTypeOf<({ [key: string]: unknown, count: number })[]>(); + expectTypeOf(result[0]).toMatchTypeOf<{ count: number }>(); +}); MyModel.build({ int: 10 }, { include: OtherModel });