typeorm-extensions 2.2.0-rc.7 → 2.2.0-rc.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +70 -39
  2. package/dist/decorators/generated-column.decorator.d.ts +17 -0
  3. package/dist/decorators/generated-column.decorator.js +15 -0
  4. package/dist/decorators/index.d.ts +1 -0
  5. package/dist/decorators/index.js +1 -0
  6. package/dist/extensions/calculated-column.extension.d.ts +3 -3
  7. package/dist/extensions/calculated-column.extension.js +3 -16
  8. package/dist/extensions/cursor-pagination.extension.js +7 -13
  9. package/dist/extensions/get-many-with-totals.extension.js +9 -32
  10. package/dist/extensions/join-lateral.extension.js +4 -6
  11. package/dist/extensions/period-filter.extension.js +1 -11
  12. package/dist/extensions/typed/index.d.ts +1 -0
  13. package/dist/extensions/typed/index.js +1 -0
  14. package/dist/extensions/typed/typed-calculated/typed-calculated-column.extension.d.ts +25 -0
  15. package/dist/extensions/typed/typed-calculated/typed-calculated-column.extension.js +24 -0
  16. package/dist/extensions/typed/typed-having/typed-having.extension.js +1 -1
  17. package/dist/extensions/typed/typed-joins/typed-join-and-map.extension.js +11 -10
  18. package/dist/extensions/typed/typed-joins/typed-joins.extension.js +11 -22
  19. package/dist/extensions/typed/typed-order-by/typed-order-by.extension.js +11 -17
  20. package/dist/extensions/typed/typed-returning/typed-returning.extension.js +1 -9
  21. package/dist/extensions/typed/typed-select/typed-select.extension.js +2 -8
  22. package/dist/extensions/typed/typed-where/typed-period-filter.extension.js +1 -11
  23. package/dist/extensions/typed/typed-where/typed-where-array.extension.js +4 -18
  24. package/dist/extensions/typed/typed-where/typed-where-ilike.extension.js +1 -11
  25. package/dist/extensions/typed/typed-where/typed-where-is-any.extension.js +3 -22
  26. package/dist/extensions/typed/typed-where/typed-where-is-distinct-from.extension.js +3 -22
  27. package/dist/extensions/typed/typed-where/typed-where-is-in.extension.js +3 -23
  28. package/dist/extensions/typed/typed-where/typed-where-json.extension.js +4 -23
  29. package/dist/extensions/typed/typed-where/typed-where-lower.extension.js +1 -11
  30. package/dist/extensions/typed/typed-where/typed-where-similar.extension.js +1 -10
  31. package/dist/extensions/typed/typed-where/typed-where.extension.js +2 -12
  32. package/dist/extensions/union.extension.js +1 -1
  33. package/dist/extensions/where-array.extension.js +1 -11
  34. package/dist/extensions/where-exists.extension.js +4 -15
  35. package/dist/extensions/where-is-any.extension.d.ts +38 -160
  36. package/dist/extensions/where-is-any.extension.js +1 -11
  37. package/dist/extensions/where-is-distinct-from.extension.js +1 -11
  38. package/dist/extensions/where-is-in.extension.d.ts +35 -145
  39. package/dist/extensions/where-is-in.extension.js +11 -29
  40. package/dist/extensions/where-json.extension.js +1 -11
  41. package/dist/extensions/where-relation-exists.extension.js +5 -25
  42. package/dist/helpers.d.ts +1 -0
  43. package/dist/helpers.js +2 -1
  44. package/dist/index.d.ts +1 -6
  45. package/dist/index.js +1 -12
  46. package/dist/types/extensions/cursor-pagination.types.d.ts +5 -0
  47. package/dist/types/extensions/get-many-with-totals.types.d.ts +4 -0
  48. package/dist/utils/calculated-column.utils.d.ts +8 -0
  49. package/dist/utils/calculated-column.utils.js +20 -3
  50. package/dist/utils/common.utils.d.ts +2 -0
  51. package/dist/utils/common.utils.js +4 -1
  52. package/dist/utils/cursor.utils.js +4 -6
  53. package/dist/utils/json-path.utils.js +2 -2
  54. package/dist/utils/pagination.utils.d.ts +7 -0
  55. package/dist/utils/pagination.utils.js +20 -10
  56. package/dist/utils/parameter.utils.d.ts +10 -0
  57. package/dist/utils/parameter.utils.js +22 -1
  58. package/dist/utils/period.utils.js +2 -1
  59. package/dist/utils/prototype.utils.d.ts +9 -0
  60. package/dist/utils/prototype.utils.js +12 -2
  61. package/dist/utils/query-builder.utils.d.ts +30 -2
  62. package/dist/utils/query-builder.utils.js +82 -44
  63. package/dist/utils/table.utils.js +9 -11
  64. package/dist/utils/time-zone.utils.d.ts +8 -0
  65. package/dist/utils/time-zone.utils.js +15 -5
  66. package/dist/utils/typed-where.utils.d.ts +9 -0
  67. package/dist/utils/typed-where.utils.js +17 -0
  68. package/dist/utils/where.utils.d.ts +2 -0
  69. package/dist/utils/where.utils.js +12 -14
  70. package/package.json +1 -1
package/README.md CHANGED
@@ -5,62 +5,93 @@
5
5
  [![Issues](https://img.shields.io/github/issues-raw/koenigstag/typeorm-extensions.svg?maxAge=25000)](https://github.com/koenigstag/typeorm-extensions/issues)
6
6
  [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://github.com/koenigstag/typeorm-extensions/pulls)
7
7
 
8
- ## Description
8
+ **Type-safe extensions for the TypeORM QueryBuilder.** Write selects, joins, conditions and ordering as property callbacks the compiler checks against your entities, page through results with totals or cursors, and build the raw SQL you still need with helpers that quote it for the database.
9
9
 
10
- TypeORM Extensions is a library that provides additional functionality and extensions for the TypeORM QueryBuilder. It aims to simplify common tasks and enhance the capabilities of TypeORM.
10
+ ```typescript
11
+ import 'typeorm-extensions';
11
12
 
12
- ## Features
13
+ const { list, total, hasMore } = await dataSource
14
+ .getRepository(UserEntity)
15
+ .createQueryBuilder('user')
16
+ .leftJoinTyped(user => user.images, 'images')
17
+ .whereTyped(user => user.createdAt, '>', since)
18
+ // a key inside a JSON column: "user"."metadata" ->> 'role' = :param
19
+ .andWhereTyped(user => user.metadata.role, '=', 'admin')
20
+ .orderByTyped(user => user.images.url, 'ASC', 'NULLS LAST')
21
+ .getManyWithTotals({ page: 1, pageSize: 20 });
22
+ ```
13
23
 
14
- - Simplicity: applying pagination and ordering to queries is as simple as calling a method.
15
- - Type Safety: the library is written in TypeScript and provides type-safe QueryBuilder methods based on Entity metadata.
16
- - Flexibility: the library is designed to be flexible and can be used with any TypeORM entity.
24
+ Try it in the [playground](https://koenigstag.github.io/typeorm-extensions/playground/): an editor and a database in the browser.
17
25
 
18
- ## Installation
26
+ ## Why
19
27
 
20
- To install `typeorm-extensions`:
28
+ The QueryBuilder takes columns as strings. A renamed property, a typo or a half-quoted alias compiles and then fails at runtime:
21
29
 
22
- Install using npm, yarn or pnpm:
23
- ```bash
24
- npm install typeorm-extensions
30
+ ```typescript
31
+ .where('user.createdAt > :since', { since }) // still compiles after createdAt is renamed
32
+ .andWhere('order."userId" = :userId', { userId }) // PostgreSQL: syntax error at or near "order"
25
33
  ```
26
34
 
27
- ## Usage
35
+ With the extensions a column is a property of the entity type, so the compiler catches the rename, and the SQL is built and quoted for you:
28
36
 
29
37
  ```typescript
30
- import 'typeorm-extensions'; // Importing the library root extends the QueryBuilder with all extensions
38
+ .whereTyped(user => user.createdAt, '>', since)
31
39
 
32
- // Or init specific extension: import 'typeorm-extensions/dist/extensions/pagination.extension';
40
+ const orders = tableHelper(OrderEntity, 'order');
41
+ .andWhere(`${orders.userId} = :userId`, { userId }) // "order"."userId" = :userId
42
+ ```
33
43
 
34
- const query = myDataSource
35
- .getRepository(UserEntity)
36
- .createQueryBuilder('users')
37
- // Join relation defined in entity model
38
- .leftJoinTyped(user => user.images, 'images')
39
- // Select type-safe properties
40
- .selectTyped(user => [
41
- user.id,
42
- user.name,
43
- user.email,
44
- user.images.url,
45
- ])
46
- .whereTyped(user => user.name, 'ILIKE', 'John')
47
- // Paths into JSON columns: "users"."metadata" ->> 'role' = :param
48
- .andWhereTyped(user => user.metadata.role, '=', 'admin')
49
- // Order by type-safe own and relation properties
50
- .orderByTyped(user => user.images.url, 'ASC', 'NULLS LAST')
51
- // Use pagination as simple as that
52
- .applyPaginationFilter({ page: 1, pageSize: 10 }, { useTakeAndSkip: true });
44
+ ## Installation
45
+
46
+ ```bash
47
+ npm install typeorm-extensions
53
48
  ```
54
49
 
55
- ## Documentation
50
+ `typeorm` 0.3.12 or later, or 1.x, is a peer dependency. Release candidates of the next version are published under the `next` tag: `npm install typeorm-extensions@next`.
51
+
52
+ ## Features
53
+
54
+ **Typed queries** ([docs](https://koenigstag.github.io/typeorm-extensions/docs/api/typed/))
55
+ - `selectTyped`, `whereTyped` (keys inside JSON columns too; `strictParams` checks the parameter against the column type), `orderByTyped`, `groupByTyped` / `havingTyped`, `distinctOnTyped`, `returningTyped`
56
+ - typed joins and map joins (`leftJoinTyped`, `innerJoinAndMapOneTyped`, …), `typed<Root>()` for the aliases a query joins, `whereRelationExists` built from the relation metadata
57
+
58
+ **Pagination** ([docs](https://koenigstag.github.io/typeorm-extensions/docs/api/pagination/))
59
+ - `getManyWithTotals` and `getRawManyWithTotals`: the rows of a page, the total, `page` / `pageSize`, `hasMore` and the order it was read in
60
+ - `getManyWithCursor`: keyset pagination with an opaque cursor
61
+ - `applyPaginationFilter` for a page of any query
56
62
 
57
- For more information, please refer to the [documentation](https://koenigstag.github.io/typeorm-extensions).
63
+ **Filters and ordering** ([docs](https://koenigstag.github.io/typeorm-extensions/docs/api/where/))
64
+ - `whereIsIn` / `whereIsNotIn` that handle empty arrays, `whereIsAny`, null-safe `whereIsDistinctFrom`
65
+ - case-insensitive search with escaped wildcards, `applyPeriodFilter` in a time zone
66
+ - `applyOrder` from a client's order filter, `orderByArrayPosition`
58
67
 
59
- ## ToDo list
68
+ **Subqueries and joins**
69
+ - `whereExists` / `whereNotExists`, with the subquery's parameters renamed so they never clash with the outer query's
70
+ - `leftJoinLateral` / `innerJoinLateral`, `innerJoinUnnest`, `fromUnion` and CTE unions
71
+
72
+ **SQL helpers** ([docs](https://koenigstag.github.io/typeorm-extensions/docs/api/utils/tableHelper/))
73
+ - `tableHelper`: quoted column references, conditions, counts, sums, JSON objects and paths, time zones. Given the entity class it writes the database name of a renamed column
74
+ - the reserved qualifier guard: catches SQL like `order."userId"` before PostgreSQL rejects it
75
+
76
+ **Columns** ([docs](https://koenigstag.github.io/typeorm-extensions/docs/api/columns/generatedColumn/))
77
+ - `@CalculatedColumn` with `addSelectCalculated` / `orderByCalculated`: a value each query computes
78
+ - `@GeneratedColumn`: a column the database generates, which TypeORM reads and never writes
79
+
80
+ ## Entry points
81
+
82
+ | Import | Gives |
83
+ |---|---|
84
+ | `import 'typeorm-extensions'` | every QueryBuilder extension, and all exports |
85
+ | `import 'typeorm-extensions/dist/extensions/pagination.extension'` | one extension |
86
+ | `import { tableHelper, GeneratedColumn } from 'typeorm-extensions/helpers'` | the helpers, with no side effects |
87
+
88
+ ## Compatibility
89
+
90
+ TypeORM 0.3.12 and later, and 1.x. CI runs the test suite on SQLite with TypeORM 0.3.12, the latest 0.3 and 1.x, and on MySQL 8.4. Features that only work on some databases (array and JSON operators, `DISTINCT ON`, `orderByArrayPosition`, …) say so in their docs.
91
+
92
+ ## Documentation
60
93
 
61
- - [x] Add tests for pagination and order extensions
62
- - [x] Calculated columns: the `@CalculatedColumn` decorator and `addSelectCalculated`. `getMany`, `getOne` and `getManyWithTotals` fill them as they are, so they need no variants of their own
63
- - [x] Order by a calculated column: `orderByCalculated`, and `applyOrder` orders a `@CalculatedColumn` field by its value
94
+ The [documentation](https://koenigstag.github.io/typeorm-extensions/) has a page for every method, with its signature, options and examples, and the [playground](https://koenigstag.github.io/typeorm-extensions/playground/) runs them.
64
95
 
65
96
  ## License
66
97
 
@@ -0,0 +1,17 @@
1
+ import { ColumnOptions, ColumnType } from 'typeorm';
2
+ /** The options of `@Column`, without those that would let TypeORM write the column. */
3
+ export type GeneratedColumnOptions = Omit<ColumnOptions, 'insert' | 'update' | 'readonly'>;
4
+ /**
5
+ * A column of the table that the database computes: `GENERATED ALWAYS AS (…) STORED`. TypeORM reads it like any
6
+ * column and never writes it. `asExpression` alone doesn't stop TypeORM (0.3 and 1.x) from sending the column in
7
+ * `save`, `insert` and `update`, which the database rejects for a generated column.
8
+ *
9
+ * Pass `asExpression` and `generatedType: 'STORED'` when TypeORM creates the schema (synchronize, generated
10
+ * migrations); a column created by a hand-written migration needs neither.
11
+ *
12
+ * @example
13
+ * \@GeneratedColumn({ type: 'integer', asExpression: 'price * quantity', generatedType: 'STORED' })
14
+ * total: number;
15
+ */
16
+ export declare function GeneratedColumn(options?: GeneratedColumnOptions): PropertyDecorator;
17
+ export declare function GeneratedColumn(type: ColumnType, options?: GeneratedColumnOptions): PropertyDecorator;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GeneratedColumn = void 0;
4
+ const typeorm_1 = require("typeorm");
5
+ function GeneratedColumn(typeOrOptions, options = {}) {
6
+ const columnOptions = typeof typeOrOptions === 'object'
7
+ ? { ...typeOrOptions }
8
+ : typeOrOptions === undefined
9
+ ? { ...options }
10
+ : { ...options, type: typeOrOptions };
11
+ // TypeORM 0.3 applies `readonly` after `update`: `readonly: false` from an untyped caller would turn writes back on
12
+ delete columnOptions.readonly;
13
+ return (0, typeorm_1.Column)({ ...columnOptions, insert: false, update: false });
14
+ }
15
+ exports.GeneratedColumn = GeneratedColumn;
@@ -1 +1,2 @@
1
1
  export * from './calculated-column.decorator';
2
+ export * from './generated-column.decorator';
@@ -15,3 +15,4 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./calculated-column.decorator"), exports);
18
+ __exportStar(require("./generated-column.decorator"), exports);
@@ -1,6 +1,6 @@
1
- import { ObjectLiteral, SelectQueryBuilder } from 'typeorm';
2
- /** `addSelect`'s selection: an SQL expression, or a factory that builds a subquery on the builder it is given. */
3
- export type CalculatedSelection<SubEntity extends ObjectLiteral = ObjectLiteral> = string | ((qb: SelectQueryBuilder<ObjectLiteral>) => SelectQueryBuilder<SubEntity>);
1
+ import { ObjectLiteral } from 'typeorm';
2
+ import { CalculatedSelection } from '../utils/calculated-column.utils';
3
+ export type { CalculatedSelection };
4
4
  declare module 'typeorm/query-builder/SelectQueryBuilder' {
5
5
  interface SelectQueryBuilder<Entity extends ObjectLiteral> {
6
6
  /**
@@ -7,27 +7,14 @@ const calculated_column_utils_1 = require("../utils/calculated-column.utils");
7
7
  const extension = {
8
8
  prototype: {
9
9
  addSelectCalculated(selection, property, alias) {
10
- return addSelectCalculated(this, selection, property, alias);
10
+ return (0, calculated_column_utils_1.addSelectCalculatedColumn)(this, selection, property, alias, 'addSelectCalculated');
11
11
  },
12
12
  orderByCalculated(property, order, nulls, alias) {
13
- return attachOrderByCalculated(this, 'orderBy', property, order, nulls, alias);
13
+ return (0, calculated_column_utils_1.orderByCalculatedColumn)(this, 'orderBy', property, order, nulls, alias, 'orderByCalculated');
14
14
  },
15
15
  addOrderByCalculated(property, order, nulls, alias) {
16
- return attachOrderByCalculated(this, 'addOrderBy', property, order, nulls, alias);
16
+ return (0, calculated_column_utils_1.orderByCalculatedColumn)(this, 'addOrderBy', property, order, nulls, alias, 'addOrderByCalculated');
17
17
  },
18
18
  },
19
19
  };
20
20
  (0, prototype_utils_1.patchPrototype)(typeorm_1.SelectQueryBuilder, extension);
21
- // implementation
22
- function addSelectCalculated(builder, selection, property, aliasName) {
23
- const { key } = (0, calculated_column_utils_1.resolveCalculatedColumn)(builder, property, aliasName, 'addSelectCalculated');
24
- // two calls: addSelect's overloads take a string or a factory, not their union
25
- if (typeof selection === 'function') {
26
- return builder.addSelect(selection, key);
27
- }
28
- return builder.addSelect(selection, key);
29
- }
30
- function attachOrderByCalculated(builder, method, property, order, nulls, aliasName) {
31
- const orderAlias = (0, calculated_column_utils_1.selectCalculatedForOrder)(builder, property, aliasName, `${method}Calculated`);
32
- return builder[method](orderAlias, order, nulls);
33
- }
@@ -2,11 +2,12 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.InvalidCursorError = void 0;
4
4
  const SelectQueryBuilder_1 = require("typeorm/query-builder/SelectQueryBuilder");
5
- const constants_1 = require("../constants");
5
+ const pagination_utils_1 = require("../utils/pagination.utils");
6
6
  const prototype_utils_1 = require("../utils/prototype.utils");
7
7
  const order_utils_1 = require("../utils/order.utils");
8
8
  const where_utils_1 = require("../utils/where.utils");
9
9
  const sql_utils_1 = require("../utils/sql.utils");
10
+ const query_builder_utils_1 = require("../utils/query-builder.utils");
10
11
  const cursor_utils_1 = require("../utils/cursor.utils");
11
12
  var cursor_utils_2 = require("../utils/cursor.utils");
12
13
  Object.defineProperty(exports, "InvalidCursorError", { enumerable: true, get: function () { return cursor_utils_2.InvalidCursorError; } });
@@ -44,14 +45,11 @@ function getCursorKeys(builder, orderBy) {
44
45
  }
45
46
  return keys;
46
47
  }
47
- const getPageSize = (pageSize) => typeof pageSize === 'number' && Number.isFinite(pageSize) && pageSize >= 1
48
- ? Math.floor(pageSize)
49
- : constants_1.defaultPageSize;
50
48
  async function getManyWithCursor(builder, cursorFilter, options) {
51
49
  const { orderBy, useTakeAndSkip = false } = options !== null && options !== void 0 ? options : {};
52
50
  const keys = getCursorKeys(builder, orderBy);
53
51
  const fields = keys.map((key) => key.column.propertyPath);
54
- const pageSize = getPageSize(cursorFilter === null || cursorFilter === void 0 ? void 0 : cursorFilter.pageSize);
52
+ const pageSize = (0, pagination_utils_1.normalizePageSize)(cursorFilter === null || cursorFilter === void 0 ? void 0 : cursorFilter.pageSize);
55
53
  const query = builder.clone();
56
54
  const alias = query.alias;
57
55
  const driver = query.connection.driver.options.type;
@@ -68,6 +66,7 @@ async function getManyWithCursor(builder, cursorFilter, options) {
68
66
  }
69
67
  query.orderBy();
70
68
  keys.forEach((key) => query.addOrderBy(`${alias}.${key.column.propertyPath}`, key.direction));
69
+ const appliedOrderBy = (0, query_builder_utils_1.getAppliedOrderBy)(query);
71
70
  // the key values of the last row are read from the raw result: dates and times as text, so the
72
71
  // cursor keeps the database's precision (PostgreSQL timestamps have microseconds, a JS Date has not)
73
72
  const keyAliases = keys.map((key, i) => {
@@ -81,16 +80,11 @@ async function getManyWithCursor(builder, cursorFilter, options) {
81
80
  .map((key, i) => ({ key, i }))
82
81
  .filter(({ key }) => key.column.isPrimary)
83
82
  .map(({ key, i }) => ({ column: key.column, keyAlias: keyAliases[i] }));
84
- if (useTakeAndSkip) {
85
- query.take(pageSize + 1);
86
- }
87
- else {
88
- query.limit(pageSize + 1);
89
- }
83
+ (0, pagination_utils_1.setPageLimit)(query, pageSize + 1, useTakeAndSkip);
90
84
  const { entities, raw } = await query.getRawAndEntities();
91
85
  const list = entities.slice(0, pageSize);
92
86
  if (entities.length <= pageSize) {
93
- return { list, nextCursor: null, hasMore: false };
87
+ return { list, nextCursor: null, hasMore: false, pageSize, orderBy: appliedOrderBy };
94
88
  }
95
89
  // with joined collections there are several raw rows per entity: find one of the last entity's
96
90
  const last = list[list.length - 1];
@@ -105,5 +99,5 @@ async function getManyWithCursor(builder, cursorFilter, options) {
105
99
  }
106
100
  return value;
107
101
  });
108
- return { list, nextCursor: (0, cursor_utils_1.encodeCursor)(fields, values), hasMore: true };
102
+ return { list, nextCursor: (0, cursor_utils_1.encodeCursor)(fields, values), hasMore: true, pageSize, orderBy: appliedOrderBy };
109
103
  }
@@ -31,8 +31,7 @@ const extension = {
31
31
  * runner, so the one that starts second finds a transaction active and does not open its own.
32
32
  */
33
33
  function canCountConcurrently(builder) {
34
- const queryBuilder = builder;
35
- return !queryBuilder.queryRunner;
34
+ return !(0, query_builder_utils_1.getQueryRunner)(builder);
36
35
  }
37
36
  function getManyWithTotals(builder, paginationFilter, options) {
38
37
  return readWithTotals(builder, paginationFilter, options, {
@@ -58,10 +57,9 @@ function getRawManyWithTotals(builder, paginationFilter, options) {
58
57
  });
59
58
  }
60
59
  async function readWithTotals(builder, paginationFilter, options, read) {
61
- var _a;
62
60
  const { disableTotalsCalculation = false, loadAll = false, ...paginationOptions } = options || {};
63
- const { limit, offset } = loadAll
64
- ? { limit: null, offset: null }
61
+ const { limit, offset, page, pageSize } = loadAll
62
+ ? { limit: null, offset: null, page: null, pageSize: null }
65
63
  : (0, pagination_utils_1.getLimitAndOffset)(paginationFilter);
66
64
  // without a total, one row past the page is what tells whether more rows follow
67
65
  const probeForMore = disableTotalsCalculation && !loadAll && limit !== null;
@@ -71,15 +69,9 @@ async function readWithTotals(builder, paginationFilter, options, read) {
71
69
  }
72
70
  const paged = builder.applyPaginationFilter(paginationFilter, paginationOptions);
73
71
  if (probeForMore) {
74
- const probeLimit = limit + 1;
75
72
  const { useTakeAndSkip = constants_1.defaultUseTakeAndSkip } = paginationOptions;
76
73
  // replaces the limit applyPaginationFilter just set, keeping its offset
77
- if (useTakeAndSkip) {
78
- paged.take(probeLimit);
79
- }
80
- else {
81
- paged.limit(probeLimit);
82
- }
74
+ (0, pagination_utils_1.setPageLimit)(paged, limit + 1, useTakeAndSkip);
83
75
  }
84
76
  return read.rows(paged);
85
77
  };
@@ -110,21 +102,15 @@ async function readWithTotals(builder, paginationFilter, options, read) {
110
102
  hasMore =
111
103
  total !== null && offset !== null ? offset + rows.length < total : null;
112
104
  }
113
- // allOrderBys, not orderBys: it is what the SQL is built from, so without an explicit order it
114
- // falls back to the `orderBy` of @Entity, and respects the `disable-global-order` option
115
- const orderBy = Object.entries((_a = builder.expressionMap.allOrderBys) !== null && _a !== void 0 ? _a : {}).map(([key, value]) => {
116
- const selector = (0, query_builder_utils_1.resolveDeferredKeys)(builder, key);
117
- return typeof value === 'string'
118
- ? { selector, order: value }
119
- : { selector, order: value.order, nulls: value.nulls };
120
- });
121
105
  return {
122
106
  list,
123
107
  total,
108
+ page,
109
+ pageSize,
124
110
  limit,
125
111
  offset,
126
112
  hasMore,
127
- orderBy,
113
+ orderBy: (0, query_builder_utils_1.getAppliedOrderBy)(builder),
128
114
  };
129
115
  }
130
116
  /**
@@ -147,9 +133,6 @@ async function bothOrFirstError(first, second) {
147
133
  function settle(promise) {
148
134
  return promise.then((value) => ({ fulfilled: true, value }), (reason) => ({ fulfilled: false, reason }));
149
135
  }
150
- function getQueryRunner(builder) {
151
- return builder.queryRunner;
152
- }
153
136
  /**
154
137
  * Counts the rows of a raw query without its pagination and ORDER BY. The query goes into a
155
138
  * subquery, so the count is that of its result rows whatever it groups or filters. A
@@ -158,13 +141,7 @@ function getQueryRunner(builder) {
158
141
  */
159
142
  async function countRawRows(builder, countExpression) {
160
143
  var _a;
161
- const unpaged = cloneForCount(builder)
162
- .orderBy()
163
- .offset(undefined)
164
- .limit(undefined)
165
- .skip(undefined)
166
- .take(undefined)
167
- .setOption('disable-global-order');
144
+ const unpaged = (0, query_builder_utils_1.withoutPaging)(cloneForCount(builder));
168
145
  let counting;
169
146
  if (countExpression) {
170
147
  // the expression counts on its own: DISTINCT ON next to an aggregate is an error
@@ -175,7 +152,7 @@ async function countRawRows(builder, countExpression) {
175
152
  else {
176
153
  // on the builder's query runner, if it has one: inside its transaction
177
154
  const counter = builder.connection
178
- .createQueryBuilder(getQueryRunner(builder))
155
+ .createQueryBuilder((0, query_builder_utils_1.getQueryRunner)(builder))
179
156
  .select('COUNT(*)', 'count')
180
157
  .from(`(${unpaged.getQuery()})`, 'counted')
181
158
  .setParameters(unpaged.getParameters());
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const typeorm_1 = require("typeorm");
4
4
  const parameter_utils_1 = require("../utils/parameter.utils");
5
+ const query_builder_utils_1 = require("../utils/query-builder.utils");
5
6
  const prototype_utils_1 = require("../utils/prototype.utils");
6
7
  /* eslint-enable @typescript-eslint/no-empty-interface, @typescript-eslint/no-unused-vars */
7
8
  // patching
@@ -32,18 +33,15 @@ function toLateralSql(builder, subQuery) {
32
33
  return { sql: `(${subQuery})`, parameters: {} };
33
34
  }
34
35
  const subBuilder = typeof subQuery === 'function' ? subQuery(detachedSubQuery(builder)) : subQuery;
35
- const query = subBuilder.getQuery();
36
- // a builder from subQuery() wraps itself in parentheses, any other doesn't
37
- const wrapped = subBuilder.expressionMap.subQuery ? query : `(${query})`;
38
- const [sql, parameters] = (0, parameter_utils_1.withUniqueParameterNames)(wrapped, subBuilder.getParameters());
39
- return { sql, parameters };
36
+ const [sql, parameters] = (0, parameter_utils_1.toSubQuerySql)(subBuilder);
37
+ return { sql: `(${sql})`, parameters };
40
38
  }
41
39
  /**
42
40
  * A subquery builder for a factory, as TypeORM's `subQuery()` but without a parent: TypeORM's would
43
41
  * set the factory's parameters on the outer query under their own names, before they can be renamed.
44
42
  */
45
43
  function detachedSubQuery(builder) {
46
- const queryRunner = builder.queryRunner;
44
+ const queryRunner = (0, query_builder_utils_1.getQueryRunner)(builder);
47
45
  const subQuery = builder.connection.createQueryBuilder(queryRunner);
48
46
  subQuery.expressionMap.subQuery = true;
49
47
  return subQuery;
@@ -1,7 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const typeorm_1 = require("typeorm");
4
- const SoftDeleteQueryBuilder_1 = require("typeorm/query-builder/SoftDeleteQueryBuilder");
5
3
  const prototype_utils_1 = require("../utils/prototype.utils");
6
4
  const query_builder_utils_1 = require("../utils/query-builder.utils");
7
5
  const period_utils_1 = require("../utils/period.utils");
@@ -14,12 +12,4 @@ const extension = {
14
12
  },
15
13
  },
16
14
  };
17
- const queryBuilders = [
18
- typeorm_1.SelectQueryBuilder,
19
- typeorm_1.UpdateQueryBuilder,
20
- typeorm_1.DeleteQueryBuilder,
21
- SoftDeleteQueryBuilder_1.SoftDeleteQueryBuilder,
22
- ];
23
- queryBuilders.forEach((builder) => {
24
- (0, prototype_utils_1.patchPrototype)(builder, extension);
25
- });
15
+ (0, prototype_utils_1.patchPrototypes)(prototype_utils_1.WHERE_QUERY_BUILDERS, extension);
@@ -17,4 +17,5 @@ export * from './typed-where/typed-where-lower.extension';
17
17
  export * from './typed-where/typed-where-similar.extension';
18
18
  export * from './typed-returning/typed-returning.extension';
19
19
  export * from './typed-order-by/typed-order-by-array-position.extension';
20
+ export * from './typed-calculated/typed-calculated-column.extension';
20
21
  export * from './typed-root.extension';
@@ -34,4 +34,5 @@ __exportStar(require("./typed-where/typed-where-lower.extension"), exports);
34
34
  __exportStar(require("./typed-where/typed-where-similar.extension"), exports);
35
35
  __exportStar(require("./typed-returning/typed-returning.extension"), exports);
36
36
  __exportStar(require("./typed-order-by/typed-order-by-array-position.extension"), exports);
37
+ __exportStar(require("./typed-calculated/typed-calculated-column.extension"), exports);
37
38
  __exportStar(require("./typed-root.extension"), exports);
@@ -0,0 +1,25 @@
1
+ import { ObjectLiteral } from 'typeorm';
2
+ import { DeepUnwrapArray, ProxyColumnValueType } from '../../../types/modules/proxy-callback.types';
3
+ import type { TypedRoot } from '../../../types/modules/typed-root.types';
4
+ import { CalculatedSelection } from '../../../utils/calculated-column.utils';
5
+ type CalculatedPropertyCallback<Type extends ObjectLiteral> = (proxy: DeepUnwrapArray<Type>) => ProxyColumnValueType;
6
+ export interface TypedCalculatedColumnMethods<Entity extends ObjectLiteral> {
7
+ /**
8
+ * `addSelectCalculated` with the `@CalculatedColumn` picked by a typed callback: `(user) => user.imagesCount`, or
9
+ * `(q) => q.owner.imagesCount` for the entity of the joined alias `owner`. The callback starts at the root set with
10
+ * `typed<Root>()`, else at the entity. Throws a `TypeError` if the property isn't a `@CalculatedColumn`.
11
+ */
12
+ addSelectCalculatedTyped<Type extends ObjectLiteral = TypedRoot<Entity, this>, SubEntity extends ObjectLiteral = ObjectLiteral>(selection: CalculatedSelection<SubEntity>, property: CalculatedPropertyCallback<Type>): this;
13
+ /**
14
+ * `orderByCalculated` with the `@CalculatedColumn` picked by a typed callback: ORDER BY its value, selected with
15
+ * `addSelectCalculated` / `addSelectCalculatedTyped` first. Replaces the previous ORDER BY, like `orderBy`.
16
+ */
17
+ orderByCalculatedTyped<Type extends ObjectLiteral = TypedRoot<Entity, this>>(property: CalculatedPropertyCallback<Type>, order?: 'ASC' | 'DESC', nulls?: 'NULLS FIRST' | 'NULLS LAST'): this;
18
+ /** `addOrderByCalculated` with the `@CalculatedColumn` picked by a typed callback, like `addOrderBy`. */
19
+ addOrderByCalculatedTyped<Type extends ObjectLiteral = TypedRoot<Entity, this>>(property: CalculatedPropertyCallback<Type>, order?: 'ASC' | 'DESC', nulls?: 'NULLS FIRST' | 'NULLS LAST'): this;
20
+ }
21
+ declare module 'typeorm/query-builder/SelectQueryBuilder' {
22
+ interface SelectQueryBuilder<Entity extends ObjectLiteral> extends TypedCalculatedColumnMethods<Entity> {
23
+ }
24
+ }
25
+ export {};
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const SelectQueryBuilder_1 = require("typeorm/query-builder/SelectQueryBuilder");
4
+ const calculated_column_utils_1 = require("../../../utils/calculated-column.utils");
5
+ const query_builder_utils_1 = require("../../../utils/query-builder.utils");
6
+ const prototype_utils_1 = require("../../../utils/prototype.utils");
7
+ /* eslint-enable @typescript-eslint/no-empty-interface */
8
+ // patching
9
+ const createOrderByCalculatedTypedMethod = (method) => function (property, order, nulls) {
10
+ const methodName = `${method}CalculatedTyped`;
11
+ const { aliasName, propertyPath } = (0, query_builder_utils_1.resolveTypedProperty)(this, property, methodName);
12
+ return (0, calculated_column_utils_1.orderByCalculatedColumn)(this, method, propertyPath, order, nulls, aliasName, methodName);
13
+ };
14
+ const extension = {
15
+ prototype: {
16
+ addSelectCalculatedTyped(selection, property) {
17
+ const { aliasName, propertyPath } = (0, query_builder_utils_1.resolveTypedProperty)(this, property, 'addSelectCalculatedTyped');
18
+ return (0, calculated_column_utils_1.addSelectCalculatedColumn)(this, selection, propertyPath, aliasName, 'addSelectCalculatedTyped');
19
+ },
20
+ orderByCalculatedTyped: createOrderByCalculatedTypedMethod('orderBy'),
21
+ addOrderByCalculatedTyped: createOrderByCalculatedTypedMethod('addOrderBy'),
22
+ },
23
+ };
24
+ (0, prototype_utils_1.patchPrototype)(SelectQueryBuilder_1.SelectQueryBuilder, extension);
@@ -33,7 +33,7 @@ function attachTypedHaving(builder, method, aggregate, selection, conditions, pa
33
33
  else {
34
34
  // a path into a JSON column is cast: to a number to add it up, and for MIN / MAX to the type of the
35
35
  // value it is compared with, as in whereTyped; a count needs no cast
36
- const compared = (0, where_utils_1.isParamsObject)(parameters) ? Object.values(parameters)[0] : parameters;
36
+ const compared = (0, where_utils_1.getComparedValue)(parameters);
37
37
  const value = aggregate === 'SUM' || aggregate === 'AVG' ? 0 : aggregate === 'MIN' || aggregate === 'MAX' ? compared : undefined;
38
38
  argument = (0, query_builder_utils_1.getTypedSingleColumnKey)(builder, selection, methodName, { value });
39
39
  }
@@ -2,19 +2,20 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const typeorm_1 = require("typeorm");
4
4
  const proxy_key_utils_1 = require("../../../utils/proxy-key.utils");
5
+ const prototype_utils_1 = require("../../../utils/prototype.utils");
5
6
  // patching
6
- typeorm_1.SelectQueryBuilder.prototype.leftJoinAndMapOneTyped = function (mapToProperty, entity, alias, condition, parameters) {
7
- return addJoinAndMap(this, 'leftJoinAndMapOne', mapToProperty, entity, alias, condition, parameters);
7
+ const createJoinAndMapTypedMethod = (method) => function (mapToProperty, entity, alias, condition, parameters) {
8
+ return addJoinAndMap(this, method, mapToProperty, entity, alias, condition, parameters);
8
9
  };
9
- typeorm_1.SelectQueryBuilder.prototype.innerJoinAndMapOneTyped = function (mapToProperty, entity, alias, condition, parameters) {
10
- return addJoinAndMap(this, 'innerJoinAndMapOne', mapToProperty, entity, alias, condition, parameters);
11
- };
12
- typeorm_1.SelectQueryBuilder.prototype.leftJoinAndMapManyTyped = function (mapToProperty, entity, alias, condition, parameters) {
13
- return addJoinAndMap(this, 'leftJoinAndMapMany', mapToProperty, entity, alias, condition, parameters);
14
- };
15
- typeorm_1.SelectQueryBuilder.prototype.innerJoinAndMapManyTyped = function (mapToProperty, entity, alias, condition, parameters) {
16
- return addJoinAndMap(this, 'innerJoinAndMapMany', mapToProperty, entity, alias, condition, parameters);
10
+ const extension = {
11
+ prototype: {
12
+ leftJoinAndMapOneTyped: createJoinAndMapTypedMethod('leftJoinAndMapOne'),
13
+ innerJoinAndMapOneTyped: createJoinAndMapTypedMethod('innerJoinAndMapOne'),
14
+ leftJoinAndMapManyTyped: createJoinAndMapTypedMethod('leftJoinAndMapMany'),
15
+ innerJoinAndMapManyTyped: createJoinAndMapTypedMethod('innerJoinAndMapMany'),
16
+ },
17
17
  };
18
+ (0, prototype_utils_1.patchPrototype)(typeorm_1.SelectQueryBuilder, extension);
18
19
  function addJoinAndMap(query, method, mapToProperty, entity, alias, condition, parameters) {
19
20
  // `() => query.alias`: `(q) => q.photo.owner` needs no main alias, only `(u) => u.profile` does
20
21
  const key = (0, proxy_key_utils_1.getSqlKeyFromProxyCallback)(mapToProperty, () => query.alias, false);
@@ -2,31 +2,20 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const typeorm_1 = require("typeorm");
4
4
  const proxy_key_utils_1 = require("../../../utils/proxy-key.utils");
5
+ const prototype_utils_1 = require("../../../utils/prototype.utils");
5
6
  // patching
6
- typeorm_1.SelectQueryBuilder.prototype.leftJoinTyped = function (selection, alias, condition, parameters) {
7
- if (typeof selection === 'function') {
8
- return addJoin(this, 'leftJoin', selection, alias, condition, parameters);
9
- }
10
- return this;
7
+ const createJoinTypedMethod = (method) => function (selection, alias, condition, parameters) {
8
+ return addJoin(this, method, selection, alias, condition, parameters);
11
9
  };
12
- typeorm_1.SelectQueryBuilder.prototype.innerJoinTyped = function (selection, alias, condition, parameters) {
13
- if (typeof selection === 'function') {
14
- return addJoin(this, 'innerJoin', selection, alias, condition, parameters);
15
- }
16
- return this;
17
- };
18
- typeorm_1.SelectQueryBuilder.prototype.leftJoinAndSelectTyped = function (selection, alias, condition, parameters) {
19
- if (typeof selection === 'function') {
20
- return addJoin(this, 'leftJoinAndSelect', selection, alias, condition, parameters);
21
- }
22
- return this;
23
- };
24
- typeorm_1.SelectQueryBuilder.prototype.innerJoinAndSelectTyped = function (selection, alias, condition, parameters) {
25
- if (typeof selection === 'function') {
26
- return addJoin(this, 'innerJoinAndSelect', selection, alias, condition, parameters);
27
- }
28
- return this;
10
+ const extension = {
11
+ prototype: {
12
+ leftJoinTyped: createJoinTypedMethod('leftJoin'),
13
+ innerJoinTyped: createJoinTypedMethod('innerJoin'),
14
+ leftJoinAndSelectTyped: createJoinTypedMethod('leftJoinAndSelect'),
15
+ innerJoinAndSelectTyped: createJoinTypedMethod('innerJoinAndSelect'),
16
+ },
29
17
  };
18
+ (0, prototype_utils_1.patchPrototype)(typeorm_1.SelectQueryBuilder, extension);
30
19
  function addJoin(query, method, selection, alias, condition, parameters) {
31
20
  // `() => query.alias`: `(q) => q.base.images` needs no main alias, only `(u) => u.images` does
32
21
  const key = (0, proxy_key_utils_1.getSqlKeyFromProxyCallback)(selection, () => query.alias, false);
@@ -3,25 +3,19 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const typeorm_1 = require("typeorm");
4
4
  const proxy_key_utils_1 = require("../../../utils/proxy-key.utils");
5
5
  const query_builder_utils_1 = require("../../../utils/query-builder.utils");
6
- const sql_utils_1 = require("../../../utils/sql.utils");
6
+ const prototype_utils_1 = require("../../../utils/prototype.utils");
7
7
  // patching and implementation
8
- typeorm_1.SelectQueryBuilder.prototype.orderByTyped = function (selection, order, nulls, options) {
9
- if (selection instanceof proxy_key_utils_1.KeyHolder) {
10
- return this.orderBy(selection.toSql(undefined, options === null || options === void 0 ? void 0 : options.useQuotes, (0, sql_utils_1.getDriverType)(this)), order, nulls);
11
- }
12
- if (typeof selection === 'function') {
13
- const key = (0, query_builder_utils_1.getTypedSelectionKey)(this, selection, options === null || options === void 0 ? void 0 : options.useQuotes, 'orderByTyped');
14
- return this.orderBy(key, order, nulls);
8
+ const createOrderByTypedMethod = (method) => function (selection, order, nulls, options) {
9
+ if (selection instanceof proxy_key_utils_1.KeyHolder || typeof selection === 'function') {
10
+ const key = (0, query_builder_utils_1.getTypedSelectionKey)(this, selection, options === null || options === void 0 ? void 0 : options.useQuotes, `${method}Typed`);
11
+ return this[method](key, order, nulls);
15
12
  }
16
13
  return this;
17
14
  };
18
- typeorm_1.SelectQueryBuilder.prototype.addOrderByTyped = function (selection, order, nulls, options) {
19
- if (selection instanceof proxy_key_utils_1.KeyHolder) {
20
- return this.addOrderBy(selection.toSql(undefined, options === null || options === void 0 ? void 0 : options.useQuotes, (0, sql_utils_1.getDriverType)(this)), order, nulls);
21
- }
22
- if (typeof selection === 'function') {
23
- const key = (0, query_builder_utils_1.getTypedSelectionKey)(this, selection, options === null || options === void 0 ? void 0 : options.useQuotes, 'addOrderByTyped');
24
- return this.addOrderBy(key, order, nulls);
25
- }
26
- return this;
15
+ const extension = {
16
+ prototype: {
17
+ orderByTyped: createOrderByTypedMethod('orderBy'),
18
+ addOrderByTyped: createOrderByTypedMethod('addOrderBy'),
19
+ },
27
20
  };
21
+ (0, prototype_utils_1.patchPrototype)(typeorm_1.SelectQueryBuilder, extension);