@abedmurrar/objection 0.0.0-stage → 4.0.0-alpha.0

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 (190) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +69 -2
  3. package/lib/.eslintrc.json +8 -0
  4. package/lib/initialize.js +14 -0
  5. package/lib/model/AjvValidator.js +325 -0
  6. package/lib/model/Model.js +942 -0
  7. package/lib/model/ModifierNotFoundError.js +12 -0
  8. package/lib/model/NotFoundError.js +23 -0
  9. package/lib/model/RelationDoesNotExistError.js +14 -0
  10. package/lib/model/ValidationError.js +54 -0
  11. package/lib/model/Validator.js +26 -0
  12. package/lib/model/getModel.js +9 -0
  13. package/lib/model/graph/ModelGraph.js +80 -0
  14. package/lib/model/graph/ModelGraphBuilder.js +241 -0
  15. package/lib/model/graph/ModelGraphEdge.js +52 -0
  16. package/lib/model/graph/ModelGraphNode.js +240 -0
  17. package/lib/model/inheritModel.js +28 -0
  18. package/lib/model/modelBindKnex.js +83 -0
  19. package/lib/model/modelClone.js +121 -0
  20. package/lib/model/modelColPropMap.js +34 -0
  21. package/lib/model/modelId.js +62 -0
  22. package/lib/model/modelJsonAttributes.js +92 -0
  23. package/lib/model/modelParseRelations.js +82 -0
  24. package/lib/model/modelQueryProps.js +147 -0
  25. package/lib/model/modelSet.js +136 -0
  26. package/lib/model/modelTableMetadata.js +83 -0
  27. package/lib/model/modelToJson.js +187 -0
  28. package/lib/model/modelUtils.js +47 -0
  29. package/lib/model/modelValidate.js +48 -0
  30. package/lib/model/modelValues.js +126 -0
  31. package/lib/model/modelVisitor.js +41 -0
  32. package/lib/objection.js +114 -0
  33. package/lib/queryBuilder/FunctionBuilder.js +339 -0
  34. package/lib/queryBuilder/InternalOptions.js +29 -0
  35. package/lib/queryBuilder/JoinBuilder.js +157 -0
  36. package/lib/queryBuilder/QueryBuilder.js +1398 -0
  37. package/lib/queryBuilder/QueryBuilderBase.js +884 -0
  38. package/lib/queryBuilder/QueryBuilderContext.js +27 -0
  39. package/lib/queryBuilder/QueryBuilderContextBase.js +35 -0
  40. package/lib/queryBuilder/QueryBuilderOperationSupport.js +558 -0
  41. package/lib/queryBuilder/QueryBuilderUserContext.js +31 -0
  42. package/lib/queryBuilder/RawBuilder.js +93 -0
  43. package/lib/queryBuilder/ReferenceBuilder.js +284 -0
  44. package/lib/queryBuilder/RelationExpression.js +431 -0
  45. package/lib/queryBuilder/StaticHookArguments.js +134 -0
  46. package/lib/queryBuilder/ValueBuilder.js +127 -0
  47. package/lib/queryBuilder/expressions.js +151 -0
  48. package/lib/queryBuilder/functions/mysql.js +817 -0
  49. package/lib/queryBuilder/graph/GraphAction.js +69 -0
  50. package/lib/queryBuilder/graph/GraphData.js +14 -0
  51. package/lib/queryBuilder/graph/GraphFetcher.js +191 -0
  52. package/lib/queryBuilder/graph/GraphNodeDbExistence.js +184 -0
  53. package/lib/queryBuilder/graph/GraphOperation.js +27 -0
  54. package/lib/queryBuilder/graph/GraphOptions.js +207 -0
  55. package/lib/queryBuilder/graph/GraphUpsert.js +305 -0
  56. package/lib/queryBuilder/graph/delete/GraphDelete.js +20 -0
  57. package/lib/queryBuilder/graph/delete/GraphDeleteAction.js +74 -0
  58. package/lib/queryBuilder/graph/insert/GraphInsert.js +145 -0
  59. package/lib/queryBuilder/graph/insert/GraphInsertAction.js +225 -0
  60. package/lib/queryBuilder/graph/insert/JoinRowGraphInsertAction.js +92 -0
  61. package/lib/queryBuilder/graph/patch/GraphPatch.js +20 -0
  62. package/lib/queryBuilder/graph/patch/GraphPatchAction.js +258 -0
  63. package/lib/queryBuilder/graph/recursiveUpsert/GraphRecursiveUpsert.js +31 -0
  64. package/lib/queryBuilder/graph/recursiveUpsert/GraphRecursiveUpsertAction.js +126 -0
  65. package/lib/queryBuilder/join/JoinResultColumn.js +23 -0
  66. package/lib/queryBuilder/join/JoinResultParser.js +119 -0
  67. package/lib/queryBuilder/join/RelationJoiner.js +341 -0
  68. package/lib/queryBuilder/join/TableNode.js +163 -0
  69. package/lib/queryBuilder/join/TableTree.js +85 -0
  70. package/lib/queryBuilder/join/utils.js +25 -0
  71. package/lib/queryBuilder/operations/DelegateOperation.js +141 -0
  72. package/lib/queryBuilder/operations/DeleteOperation.js +51 -0
  73. package/lib/queryBuilder/operations/FindByIdOperation.js +37 -0
  74. package/lib/queryBuilder/operations/FindByIdsOperation.js +29 -0
  75. package/lib/queryBuilder/operations/FindOperation.js +164 -0
  76. package/lib/queryBuilder/operations/FirstOperation.js +27 -0
  77. package/lib/queryBuilder/operations/FromOperation.js +110 -0
  78. package/lib/queryBuilder/operations/InsertAndFetchOperation.js +49 -0
  79. package/lib/queryBuilder/operations/InsertGraphAndFetchOperation.js +45 -0
  80. package/lib/queryBuilder/operations/InsertGraphOperation.js +108 -0
  81. package/lib/queryBuilder/operations/InsertOperation.js +206 -0
  82. package/lib/queryBuilder/operations/InstanceDeleteOperation.js +46 -0
  83. package/lib/queryBuilder/operations/InstanceFindOperation.js +21 -0
  84. package/lib/queryBuilder/operations/InstanceInsertOperation.js +24 -0
  85. package/lib/queryBuilder/operations/InstanceUpdateOperation.js +59 -0
  86. package/lib/queryBuilder/operations/JoinRelatedOperation.js +103 -0
  87. package/lib/queryBuilder/operations/KnexOperation.js +14 -0
  88. package/lib/queryBuilder/operations/MergeOperation.js +56 -0
  89. package/lib/queryBuilder/operations/ObjectionToKnexConvertingOperation.js +192 -0
  90. package/lib/queryBuilder/operations/OnBuildKnexOperation.js +29 -0
  91. package/lib/queryBuilder/operations/OnBuildOperation.js +29 -0
  92. package/lib/queryBuilder/operations/OnErrorOperation.js +29 -0
  93. package/lib/queryBuilder/operations/QueryBuilderOperation.js +297 -0
  94. package/lib/queryBuilder/operations/RangeOperation.js +47 -0
  95. package/lib/queryBuilder/operations/RelateOperation.js +27 -0
  96. package/lib/queryBuilder/operations/ReturningOperation.js +30 -0
  97. package/lib/queryBuilder/operations/RunAfterOperation.js +29 -0
  98. package/lib/queryBuilder/operations/RunBeforeOperation.js +29 -0
  99. package/lib/queryBuilder/operations/UnrelateOperation.js +23 -0
  100. package/lib/queryBuilder/operations/UpdateAndFetchOperation.js +80 -0
  101. package/lib/queryBuilder/operations/UpdateOperation.js +155 -0
  102. package/lib/queryBuilder/operations/UpsertGraphAndFetchOperation.js +45 -0
  103. package/lib/queryBuilder/operations/UpsertGraphOperation.js +66 -0
  104. package/lib/queryBuilder/operations/WhereCompositeOperation.js +57 -0
  105. package/lib/queryBuilder/operations/WhereInOperation.js +48 -0
  106. package/lib/queryBuilder/operations/eager/EagerOperation.js +61 -0
  107. package/lib/queryBuilder/operations/eager/JoinEagerOperation.js +51 -0
  108. package/lib/queryBuilder/operations/eager/NaiveEagerOperation.js +13 -0
  109. package/lib/queryBuilder/operations/eager/WhereInEagerOperation.js +285 -0
  110. package/lib/queryBuilder/operations/jsonApi/WhereJsonHasOperation.js +36 -0
  111. package/lib/queryBuilder/operations/jsonApi/WhereJsonNotObjectOperation.js +53 -0
  112. package/lib/queryBuilder/operations/jsonApi/WhereJsonOperation.js +31 -0
  113. package/lib/queryBuilder/operations/jsonApi/WhereJsonOverlapsOperation.js +31 -0
  114. package/lib/queryBuilder/operations/jsonApi/mysqlJsonApi.js +167 -0
  115. package/lib/queryBuilder/operations/jsonApi/postgresJsonApi.js +164 -0
  116. package/lib/queryBuilder/operations/select/SelectOperation.js +66 -0
  117. package/lib/queryBuilder/operations/select/Selection.js +123 -0
  118. package/lib/queryBuilder/operations/whereInComposite/WhereInCompositeMsSqlOperation.js +117 -0
  119. package/lib/queryBuilder/operations/whereInComposite/WhereInCompositeOperation.js +100 -0
  120. package/lib/queryBuilder/operations/whereInComposite/WhereInCompositeSqliteOperation.js +104 -0
  121. package/lib/queryBuilder/parsers/jsonFieldExpressionParser.js +886 -0
  122. package/lib/queryBuilder/parsers/jsonFieldExpressionParser.pegjs +97 -0
  123. package/lib/queryBuilder/parsers/relationExpressionParser.js +1042 -0
  124. package/lib/queryBuilder/parsers/relationExpressionParser.pegjs +141 -0
  125. package/lib/queryBuilder/transformations/CompositeQueryTransformation.js +22 -0
  126. package/lib/queryBuilder/transformations/QueryTransformation.js +11 -0
  127. package/lib/queryBuilder/transformations/WrapMysqlModifySubqueryTransformation.js +71 -0
  128. package/lib/queryBuilder/transformations/index.js +15 -0
  129. package/lib/queryBuilder/whereScopes.js +227 -0
  130. package/lib/relations/Relation.js +401 -0
  131. package/lib/relations/RelationDeleteOperation.js +29 -0
  132. package/lib/relations/RelationFindOperation.js +149 -0
  133. package/lib/relations/RelationInsertOperation.js +33 -0
  134. package/lib/relations/RelationOwner.js +236 -0
  135. package/lib/relations/RelationProperty.js +247 -0
  136. package/lib/relations/RelationUpdateOperation.js +30 -0
  137. package/lib/relations/belongsToOne/BelongsToOneDeleteOperation.js +23 -0
  138. package/lib/relations/belongsToOne/BelongsToOneInsertOperation.js +44 -0
  139. package/lib/relations/belongsToOne/BelongsToOneRelateOperation.js +50 -0
  140. package/lib/relations/belongsToOne/BelongsToOneRelation.js +53 -0
  141. package/lib/relations/belongsToOne/BelongsToOneUnrelateOperation.js +61 -0
  142. package/lib/relations/hasMany/HasManyInsertOperation.js +61 -0
  143. package/lib/relations/hasMany/HasManyRelateOperation.js +64 -0
  144. package/lib/relations/hasMany/HasManyRelation.js +49 -0
  145. package/lib/relations/hasMany/HasManyUnrelateOperation.js +33 -0
  146. package/lib/relations/hasOne/HasOneRelation.js +13 -0
  147. package/lib/relations/hasOneThrough/HasOneThroughRelation.js +13 -0
  148. package/lib/relations/manyToMany/ManyToManyModifyMixin.js +105 -0
  149. package/lib/relations/manyToMany/ManyToManyRelation.js +507 -0
  150. package/lib/relations/manyToMany/ManyToManySqliteModifyMixin.js +36 -0
  151. package/lib/relations/manyToMany/delete/ManyToManyDeleteOperation.js +10 -0
  152. package/lib/relations/manyToMany/delete/ManyToManyDeleteOperationBase.js +26 -0
  153. package/lib/relations/manyToMany/delete/ManyToManyDeleteSqliteOperation.js +12 -0
  154. package/lib/relations/manyToMany/find/ManyToManyFindOperation.js +105 -0
  155. package/lib/relations/manyToMany/insert/ManyToManyInsertOperation.js +52 -0
  156. package/lib/relations/manyToMany/relate/ManyToManyRelateOperation.js +81 -0
  157. package/lib/relations/manyToMany/unrelate/ManyToManyUnrelateOperation.js +14 -0
  158. package/lib/relations/manyToMany/unrelate/ManyToManyUnrelateOperationBase.js +34 -0
  159. package/lib/relations/manyToMany/unrelate/ManyToManyUnrelateSqliteOperation.js +16 -0
  160. package/lib/relations/manyToMany/update/ManyToManyUpdateOperation.js +10 -0
  161. package/lib/relations/manyToMany/update/ManyToManyUpdateOperationBase.js +82 -0
  162. package/lib/relations/manyToMany/update/ManyToManyUpdateSqliteOperation.js +12 -0
  163. package/lib/transaction.js +96 -0
  164. package/lib/utils/assert.js +25 -0
  165. package/lib/utils/buildUtils.js +21 -0
  166. package/lib/utils/classUtils.js +13 -0
  167. package/lib/utils/clone.js +2329 -0
  168. package/lib/utils/createModifier.js +42 -0
  169. package/lib/utils/deprecate.js +15 -0
  170. package/lib/utils/identifierMapping.js +227 -0
  171. package/lib/utils/internalPropUtils.js +11 -0
  172. package/lib/utils/knexUtils.js +76 -0
  173. package/lib/utils/mixin.js +25 -0
  174. package/lib/utils/mysqlJsonPath.js +55 -0
  175. package/lib/utils/normalizeIds.js +144 -0
  176. package/lib/utils/objectUtils.js +416 -0
  177. package/lib/utils/parseFieldExpression.js +51 -0
  178. package/lib/utils/postgresJsonPath.js +110 -0
  179. package/lib/utils/promiseUtils/after.js +17 -0
  180. package/lib/utils/promiseUtils/afterReturn.js +17 -0
  181. package/lib/utils/promiseUtils/index.js +17 -0
  182. package/lib/utils/promiseUtils/isPromise.js +11 -0
  183. package/lib/utils/promiseUtils/map.js +110 -0
  184. package/lib/utils/promiseUtils/mapAfterAllReturn.js +29 -0
  185. package/lib/utils/promiseUtils/try.js +22 -0
  186. package/lib/utils/resolveModel.js +107 -0
  187. package/lib/utils/tmpColumnUtils.js +16 -0
  188. package/package.json +86 -4
  189. package/typings/objection/index.d.ts +4104 -0
  190. package/typings/objection/relation-expression.d.ts +237 -0
@@ -0,0 +1,4104 @@
1
+ /// <reference types="node" />
2
+
3
+ // Type definitions for Objection.js
4
+ // Project: <http://vincit.github.io/objection.js/>
5
+ //
6
+ // Contributions by:
7
+ // * Matthew McEachen <https://github.com/mceachen>
8
+ // * Sami Koskimäki <https://github.com/koskimas>
9
+ // * Mikael Lepistö <https://github.com/elhigu>
10
+ // * Joseph T Lapp <https://github.com/jtlapp>
11
+ // * Drew R. <https://github.com/drew-r>
12
+ // * Karl Blomster <https://github.com/kblomster>
13
+ // * And many others: See <https://github.com/Vincit/objection.js/blob/main/typings/objection/index.d.ts>
14
+
15
+ import Ajv, { Options as AjvOptions } from 'ajv';
16
+ import * as dbErrors from 'db-errors';
17
+ import { Knex } from 'knex';
18
+ import {
19
+ GraphNode,
20
+ ParseError,
21
+ ParseRelationExpression,
22
+ UnknownGraph,
23
+ } from './relation-expression';
24
+
25
+ // Export the entire Objection namespace.
26
+ export = Objection;
27
+
28
+ declare namespace Objection {
29
+ const raw: RawFunction;
30
+ const val: ValueFunction;
31
+ const ref: ReferenceFunction;
32
+ const fn: FunctionFunction;
33
+
34
+ const compose: ComposeFunction;
35
+ const mixin: MixinFunction;
36
+ const defineRelations: DefineRelationsFunction;
37
+
38
+ const BelongsToOneRelation: RelationType<'one'>;
39
+ const HasOneRelation: RelationType<'one'>;
40
+ const HasManyRelation: RelationType<'many'>;
41
+ const ManyToManyRelation: RelationType<'many'>;
42
+ const HasOneThroughRelation: RelationType<'one'>;
43
+
44
+ const snakeCaseMappers: SnakeCaseMappersFactory;
45
+ const knexSnakeCaseMappers: KnexSnakeCaseMappersFactory;
46
+
47
+ const transaction: transaction;
48
+ const initialize: initialize;
49
+
50
+ const DBError: typeof dbErrors.DBError;
51
+ const DataError: typeof dbErrors.DataError;
52
+ const CheckViolationError: typeof dbErrors.CheckViolationError;
53
+ const UniqueViolationError: typeof dbErrors.UniqueViolationError;
54
+ const ConstraintViolationError: typeof dbErrors.ConstraintViolationError;
55
+ const ForeignKeyViolationError: typeof dbErrors.ForeignKeyViolationError;
56
+ const NotNullViolationError: typeof dbErrors.NotNullViolationError;
57
+
58
+ export interface RawBuilder extends Aliasable {}
59
+ /**
60
+ * What `raw()` returns: a `RawBuilder` with the expression methods.
61
+ */
62
+ export interface RawExpressionBuilder extends RawBuilder, ExpressionMethods {}
63
+
64
+ export interface RawFunction extends RawInterface<RawExpressionBuilder> {}
65
+ export interface RawInterface<R> {
66
+ (sql: string, ...bindings: any[]): R;
67
+ }
68
+
69
+ export interface ValueBuilder extends Castable, ExpressionMethods {}
70
+ export interface ValueFunction {
71
+ (
72
+ value: PrimitiveValue | PrimitiveValue[] | PrimitiveValueObject | PrimitiveValueObject[],
73
+ ): ValueBuilder;
74
+ }
75
+
76
+ /**
77
+ * A reference to a column or a field of a JSON column. `T` is the type of the value.
78
+ */
79
+ export interface ReferenceBuilder<T = unknown> extends Aliasable, ExpressionMethods {
80
+ /**
81
+ * The type of the referenced value. Only used by the typings.
82
+ */
83
+ '~type'?: T;
84
+ from(tableReference: string): this;
85
+ table(tableReference: string): this;
86
+ castText(): ReferenceBuilder<string | null>;
87
+ castInt(): ReferenceBuilder<number | null>;
88
+ castBigInt(): ReferenceBuilder<FnNumeric | null>;
89
+ castFloat(): ReferenceBuilder<number | null>;
90
+ castDecimal(): ReferenceBuilder<FnNumeric | null>;
91
+ castReal(): ReferenceBuilder<number | null>;
92
+ castBool(): ReferenceBuilder<boolean | 0 | 1 | null>;
93
+ castJson(): ReferenceBuilder<unknown>;
94
+ castTo<U = unknown>(sqlType: string): ReferenceBuilder<U>;
95
+ }
96
+ export interface ReferenceFunction {
97
+ (expression: string): ReferenceBuilder;
98
+ }
99
+
100
+ /**
101
+ * The columns of model `M`: its data properties, without relations and methods.
102
+ */
103
+ type RefColumnName<M> = Extract<ModelProps<Extract<M, Model>>, string>;
104
+
105
+ type IsJsonType<T> = 0 extends 1 & T
106
+ ? true
107
+ : unknown extends T
108
+ ? true
109
+ : [Exclude<T, null | undefined>] extends [Date | Buffer]
110
+ ? false
111
+ : [Exclude<T, null | undefined>] extends [object]
112
+ ? true
113
+ : false;
114
+
115
+ /**
116
+ * The columns of model `M` that hold JSON objects or arrays.
117
+ */
118
+ type JsonColumnName<M> = {
119
+ [K in RefColumnName<M>]: IsJsonType<M[K & keyof M]> extends true ? K : never;
120
+ }[RefColumnName<M>];
121
+
122
+ /**
123
+ * The json field part of a field expression (`a.b`, `[0]`, `[key]`) for a column of
124
+ * type `T`. The first key is checked when `T` has known keys.
125
+ */
126
+ type JsonFieldPath<T> = 0 extends 1 & T
127
+ ? string
128
+ : unknown extends T
129
+ ? string
130
+ : T extends readonly unknown[]
131
+ ? `[${string}` | `${number}${string}`
132
+ : string extends keyof T
133
+ ? string
134
+ : `${Extract<keyof T, string>}${'' | `.${string}` | `[${string}`}` | `[${string}`;
135
+
136
+ /**
137
+ * The expressions `Model.ref()` accepts for model `M`: a column, optionally with a
138
+ * table or alias (`alias.column`), and field expressions of JSON columns
139
+ * (`column:a.b`). Models that declare no columns accept any string.
140
+ */
141
+ type RefExpression<M> = [RefColumnName<M>] extends [never]
142
+ ? string
143
+ :
144
+ | RefColumnName<M>
145
+ | `${string}.${RefColumnName<M>}`
146
+ | '*'
147
+ | {
148
+ [K in JsonColumnName<M>]: `${K | `${string}.${K}`}:${JsonFieldPath<
149
+ Exclude<M[K & keyof M], null | undefined>
150
+ >}`;
151
+ }[JsonColumnName<M>];
152
+
153
+ type RefValue<M, E> = E extends `${string}:${string}`
154
+ ? unknown
155
+ : E extends `${string}.${infer C}`
156
+ ? M[C & keyof M]
157
+ : M[E & keyof M];
158
+
159
+ export interface FunctionBuilder<T = unknown> extends Castable, ExpressionMethods {
160
+ /**
161
+ * The type of the result of the function. Only used by the typings.
162
+ */
163
+ '~type'?: T;
164
+ }
165
+ export interface SqlFunctionShortcut<T = unknown> {
166
+ (...args: any[]): FunctionBuilder<T>;
167
+ }
168
+ export interface AggregateFunctionShortcut<T = unknown> {
169
+ (...args: any[]): AggregateFunctionBuilder<T>;
170
+ }
171
+
172
+ /**
173
+ * An aggregate function like `fn.count()` or `fn.sum()`.
174
+ */
175
+ export interface AggregateFunctionBuilder<T = unknown> extends FunctionBuilder<T> {
176
+ /**
177
+ * Only aggregates the rows that match `condition`.
178
+ * `fn.count().filter(Pet.ref('species').eq('dog'))` is
179
+ * `COUNT(CASE WHEN species = 'dog' THEN 1 END)`. Calling it again adds a
180
+ * condition with `AND`.
181
+ */
182
+ filter(condition: FnArg): this;
183
+ /**
184
+ * Uses the function as a window function: `fn.sum(ref('amount')).over({ partitionBy: 'ownerId' })`.
185
+ */
186
+ over(window?: FnWindow): this;
187
+ }
188
+
189
+ /**
190
+ * A window function like `fn.rowNumber()`. It can only be used after `over()`.
191
+ */
192
+ export interface WindowFunctionBuilder<T = unknown> {
193
+ over(window?: FnWindow): FunctionBuilder<T>;
194
+ }
195
+
196
+ /**
197
+ * The window of `over()`. Strings are column names.
198
+ */
199
+ interface FnWindow {
200
+ partitionBy?: FnArg | readonly FnArg[];
201
+ orderBy?: FnOrderBy | readonly FnOrderBy[];
202
+ }
203
+
204
+ /**
205
+ * `fn.case()` and `fn.case(value)`.
206
+ */
207
+ export interface CaseBuilder<T = never> extends FunctionBuilder<T | null> {
208
+ /**
209
+ * `WHEN condition THEN result`, or `WHEN value THEN result` for `fn.case(value)`.
210
+ */
211
+ when<const R>(condition: FnArg, result: R): CaseBuilder<T | FnResult<R>>;
212
+ else<const R>(result: R): FunctionBuilder<T | FnResult<R>>;
213
+ }
214
+
215
+ /**
216
+ * The type of the value of an expression.
217
+ */
218
+ type FnResult<R> =
219
+ R extends FunctionBuilder<infer U>
220
+ ? U
221
+ : R extends ReferenceBuilder<infer U>
222
+ ? U
223
+ : R extends Raw | ValueBuilder | AnyQueryBuilder
224
+ ? unknown
225
+ : R;
226
+
227
+ /**
228
+ * The value of a condition: a boolean on postgres, 0 or 1 on MySQL and SQLite, and
229
+ * NULL when a compared value is NULL.
230
+ */
231
+ type SqlBoolean = boolean | 0 | 1 | null;
232
+
233
+ /**
234
+ * An expression with a known value type.
235
+ */
236
+ interface Typed {
237
+ '~type'?: unknown;
238
+ }
239
+
240
+ /**
241
+ * A value to compare with a value of type `T`. Dates can also be compared with
242
+ * strings.
243
+ */
244
+ type CompareValue<T> = unknown extends T
245
+ ? FnArg
246
+ : Exclude<T, undefined> | (Date extends T ? string : never) | null | FnExpression;
247
+
248
+ /**
249
+ * Comparison, logic and arithmetic methods of `ref()`, `val()`, `fn()` and `raw()`:
250
+ * `Person.ref('age').gte(18)`, `Pet.ref('order').plus(1)`. The sql of each one is
251
+ * wrapped in parentheses. Values are checked against the type of the expression.
252
+ */
253
+ interface ExpressionMethods {
254
+ /**
255
+ * The type of the value. Only used by the typings.
256
+ */
257
+ '~type'?: unknown;
258
+ /**
259
+ * `= value`. `eq(null)` is `IS NULL`.
260
+ */
261
+ eq<S extends Typed>(this: S, value: CompareValue<S['~type']>): FunctionBuilder<SqlBoolean>;
262
+ /**
263
+ * `<> value`. `ne(null)` is `IS NOT NULL`.
264
+ */
265
+ ne<S extends Typed>(this: S, value: CompareValue<S['~type']>): FunctionBuilder<SqlBoolean>;
266
+ gt<S extends Typed>(this: S, value: CompareValue<S['~type']>): FunctionBuilder<SqlBoolean>;
267
+ gte<S extends Typed>(this: S, value: CompareValue<S['~type']>): FunctionBuilder<SqlBoolean>;
268
+ lt<S extends Typed>(this: S, value: CompareValue<S['~type']>): FunctionBuilder<SqlBoolean>;
269
+ lte<S extends Typed>(this: S, value: CompareValue<S['~type']>): FunctionBuilder<SqlBoolean>;
270
+ in<S extends Typed>(
271
+ this: S,
272
+ values: readonly CompareValue<S['~type']>[] | AnyQueryBuilder,
273
+ ): FunctionBuilder<SqlBoolean>;
274
+ notIn<S extends Typed>(
275
+ this: S,
276
+ values: readonly CompareValue<S['~type']>[] | AnyQueryBuilder,
277
+ ): FunctionBuilder<SqlBoolean>;
278
+ like(pattern: string | FnExpression): FunctionBuilder<SqlBoolean>;
279
+ between<S extends Typed>(
280
+ this: S,
281
+ min: CompareValue<S['~type']>,
282
+ max: CompareValue<S['~type']>,
283
+ ): FunctionBuilder<SqlBoolean>;
284
+ isNull(): FunctionBuilder<SqlBoolean>;
285
+ isNotNull(): FunctionBuilder<SqlBoolean>;
286
+ /**
287
+ * NULL, an empty string or a string of only spaces.
288
+ */
289
+ isBlank(): FunctionBuilder<SqlBoolean>;
290
+ isNotBlank(): FunctionBuilder<SqlBoolean>;
291
+ and(...conditions: FnArg[]): FunctionBuilder<SqlBoolean>;
292
+ or(...conditions: FnArg[]): FunctionBuilder<SqlBoolean>;
293
+ not(): FunctionBuilder<SqlBoolean>;
294
+ plus(value: FnArg): FunctionBuilder<FnNumeric | null>;
295
+ minus(value: FnArg): FunctionBuilder<FnNumeric | null>;
296
+ times(value: FnArg): FunctionBuilder<FnNumeric | null>;
297
+ div(value: FnArg): FunctionBuilder<FnNumeric | null>;
298
+ }
299
+
300
+ /**
301
+ * A number that the database driver may return as a string, like `DECIMAL` and
302
+ * `BIGINT` values with mysql2's and pg's default settings.
303
+ */
304
+ type FnNumeric = number | string;
305
+ /**
306
+ * An argument of an `fn` helper. Strings are values; use `ref()` for columns.
307
+ */
308
+ type FnArg =
309
+ | ReferenceBuilder
310
+ | Raw
311
+ | FunctionBuilder<any>
312
+ | ValueBuilder
313
+ | AnyQueryBuilder
314
+ | PrimitiveValue;
315
+ /**
316
+ * A JSON document argument. Objects and arrays are cast to JSON.
317
+ */
318
+ type FnJsonArg = FnArg | object;
319
+ /**
320
+ * An `fn` argument that isn't a plain value.
321
+ */
322
+ type FnExpression = Exclude<FnArg, PrimitiveValue>;
323
+ type FnOrderBy = FnArg | [FnArg, 'asc' | 'desc' | 'ASC' | 'DESC'];
324
+
325
+ // <generated:mysql-function-types>
326
+ type FnIntervalUnit =
327
+ | 'MICROSECOND'
328
+ | 'microsecond'
329
+ | 'SECOND'
330
+ | 'second'
331
+ | 'MINUTE'
332
+ | 'minute'
333
+ | 'HOUR'
334
+ | 'hour'
335
+ | 'DAY'
336
+ | 'day'
337
+ | 'WEEK'
338
+ | 'week'
339
+ | 'MONTH'
340
+ | 'month'
341
+ | 'QUARTER'
342
+ | 'quarter'
343
+ | 'YEAR'
344
+ | 'year'
345
+ | 'SECOND_MICROSECOND'
346
+ | 'second_microsecond'
347
+ | 'MINUTE_MICROSECOND'
348
+ | 'minute_microsecond'
349
+ | 'MINUTE_SECOND'
350
+ | 'minute_second'
351
+ | 'HOUR_MICROSECOND'
352
+ | 'hour_microsecond'
353
+ | 'HOUR_SECOND'
354
+ | 'hour_second'
355
+ | 'HOUR_MINUTE'
356
+ | 'hour_minute'
357
+ | 'DAY_MICROSECOND'
358
+ | 'day_microsecond'
359
+ | 'DAY_SECOND'
360
+ | 'day_second'
361
+ | 'DAY_MINUTE'
362
+ | 'day_minute'
363
+ | 'DAY_HOUR'
364
+ | 'day_hour'
365
+ | 'YEAR_MONTH'
366
+ | 'year_month';
367
+ type FnTimestampUnit =
368
+ | 'MICROSECOND'
369
+ | 'microsecond'
370
+ | 'SECOND'
371
+ | 'second'
372
+ | 'MINUTE'
373
+ | 'minute'
374
+ | 'HOUR'
375
+ | 'hour'
376
+ | 'DAY'
377
+ | 'day'
378
+ | 'WEEK'
379
+ | 'week'
380
+ | 'MONTH'
381
+ | 'month'
382
+ | 'QUARTER'
383
+ | 'quarter'
384
+ | 'YEAR'
385
+ | 'year';
386
+ // </generated:mysql-function-types>
387
+
388
+ export interface FunctionFunction {
389
+ (functionName: string, ...arguments: any[]): FunctionBuilder;
390
+
391
+ now(precision: number): FunctionBuilder<Date | string>;
392
+ now(): FunctionBuilder<Date | string>;
393
+
394
+ coalesce: SqlFunctionShortcut;
395
+ concat: SqlFunctionShortcut<string | null>;
396
+ sum: AggregateFunctionShortcut<FnNumeric | null>;
397
+ avg: AggregateFunctionShortcut<FnNumeric | null>;
398
+ min: AggregateFunctionShortcut;
399
+ max: AggregateFunctionShortcut;
400
+ /**
401
+ * `fn.count()` and `fn.count('*')` are `COUNT(*)`.
402
+ */
403
+ count: AggregateFunctionShortcut<FnNumeric>;
404
+ upper: SqlFunctionShortcut<string | null>;
405
+ lower: SqlFunctionShortcut<string | null>;
406
+
407
+ /**
408
+ * `fn.case().when(condition, result).else(result)` is `CASE WHEN ... END`.
409
+ */
410
+ case(): CaseBuilder;
411
+ /**
412
+ * `fn.case(value).when(other, result).else(result)` is `CASE value WHEN ... END`.
413
+ */
414
+ case(value: FnArg): CaseBuilder;
415
+ /**
416
+ * `EXISTS (subquery)`.
417
+ */
418
+ exists(subquery: AnyQueryBuilder): FunctionBuilder<SqlBoolean>;
419
+ /**
420
+ * The value an upsert tried to insert, for `onConflict().merge({ ... })`:
421
+ * `VALUES(column)` on MySQL, `excluded.column` on postgres and SQLite.
422
+ */
423
+ excluded(column: string | ReferenceBuilder): FunctionBuilder;
424
+
425
+ // The MySQL built-in functions. Generated from lib/queryBuilder/functions/mysql.js
426
+ // by scripts/generate-fn-typings.js.
427
+ // <generated:mysql-functions>
428
+ /** `ASCII()` (portable) */
429
+ ascii(str: FnArg): FunctionBuilder<number | null>;
430
+ /** `BIN()` (MySQL) */
431
+ bin(n: FnArg): FunctionBuilder<string | null>;
432
+ /** `BIT_LENGTH()` (portable) */
433
+ bitLength(str: FnArg): FunctionBuilder<number | null>;
434
+ /** `CHAR()` (MySQL) */
435
+ char(codes: FnArg | FnArg[], options?: { using?: string }): FunctionBuilder<Buffer | null>;
436
+ /** `CHAR_LENGTH()` (portable) */
437
+ charLength(str: FnArg): FunctionBuilder<number | null>;
438
+ /** `CHARACTER_LENGTH()` (portable) */
439
+ characterLength(str: FnArg): FunctionBuilder<number | null>;
440
+ /** `CONCAT_WS()` (portable) */
441
+ concatWs(separator: FnArg, ...strs: FnArg[]): FunctionBuilder<string | null>;
442
+ /** `ELT()` (MySQL) */
443
+ elt(n: FnArg, ...strs: FnArg[]): FunctionBuilder<string | null>;
444
+ /** `EXPORT_SET()` (MySQL) */
445
+ exportSet(
446
+ bits: FnArg,
447
+ on: FnArg,
448
+ off: FnArg,
449
+ separator?: FnArg,
450
+ numberOfBits?: FnArg,
451
+ ): FunctionBuilder<string | null>;
452
+ /** `FIELD()` (MySQL) */
453
+ field(str: FnArg, ...strs: FnArg[]): FunctionBuilder<number | null>;
454
+ /** `FIND_IN_SET()` (MySQL) */
455
+ findInSet(str: FnArg, strList: FnArg): FunctionBuilder<number | null>;
456
+ /** `FORMAT()` (MySQL) */
457
+ format(x: FnArg, decimals: FnArg, locale?: FnArg): FunctionBuilder<string | null>;
458
+ /** `FROM_BASE64()` (MySQL) */
459
+ fromBase64(str: FnArg): FunctionBuilder<Buffer | null>;
460
+ /** `HEX()` (MySQL) */
461
+ hex(x: FnArg): FunctionBuilder<string | null>;
462
+ /** `INSERT()` (MySQL) */
463
+ insert(str: FnArg, pos: FnArg, len: FnArg, newStr: FnArg): FunctionBuilder<string | null>;
464
+ /** `INSTR()` (MySQL) */
465
+ instr(str: FnArg, substr: FnArg): FunctionBuilder<number | null>;
466
+ /** `LCASE()` (MySQL) */
467
+ lcase(str: FnArg): FunctionBuilder<string | null>;
468
+ /** `LEFT()` (portable) */
469
+ left(str: FnArg, len: FnArg): FunctionBuilder<string | null>;
470
+ /** `LENGTH()` (portable) */
471
+ length(str: FnArg): FunctionBuilder<number | null>;
472
+ /** `LOCATE()` (MySQL) */
473
+ locate(substr: FnArg, str: FnArg, pos?: FnArg): FunctionBuilder<number | null>;
474
+ /** `LPAD()` (portable) */
475
+ lpad(str: FnArg, len: FnArg, padStr: FnArg): FunctionBuilder<string | null>;
476
+ /** `LTRIM()` (portable) */
477
+ ltrim(str: FnArg): FunctionBuilder<string | null>;
478
+ /** `MAKE_SET()` (MySQL) */
479
+ makeSet(bits: FnArg, ...strs: FnArg[]): FunctionBuilder<string | null>;
480
+ /** `MID()` (MySQL) */
481
+ mid(str: FnArg, pos: FnArg, len?: FnArg): FunctionBuilder<string | null>;
482
+ /** `OCT()` (MySQL) */
483
+ oct(n: FnArg): FunctionBuilder<string | null>;
484
+ /** `OCTET_LENGTH()` (portable) */
485
+ octetLength(str: FnArg): FunctionBuilder<number | null>;
486
+ /** `ORD()` (MySQL) */
487
+ ord(str: FnArg): FunctionBuilder<number | null>;
488
+ /** `POSITION()` (portable) */
489
+ position(substr: FnArg, str: FnArg): FunctionBuilder<number | null>;
490
+ /** `QUOTE()` (MySQL) */
491
+ quote(str: FnArg): FunctionBuilder<string | null>;
492
+ /** `REGEXP_INSTR()` (MySQL) */
493
+ regexpInstr(
494
+ expr: FnArg,
495
+ pattern: FnArg,
496
+ pos?: FnArg,
497
+ occurrence?: FnArg,
498
+ returnOption?: FnArg,
499
+ matchType?: FnArg,
500
+ ): FunctionBuilder<number | null>;
501
+ /** `REGEXP_LIKE()` (MySQL) */
502
+ regexpLike(expr: FnArg, pattern: FnArg, matchType?: FnArg): FunctionBuilder<0 | 1 | null>;
503
+ /** `REGEXP_REPLACE()` (MySQL) */
504
+ regexpReplace(
505
+ expr: FnArg,
506
+ pattern: FnArg,
507
+ replacement: FnArg,
508
+ pos?: FnArg,
509
+ occurrence?: FnArg,
510
+ matchType?: FnArg,
511
+ ): FunctionBuilder<string | null>;
512
+ /** `REGEXP_SUBSTR()` (MySQL) */
513
+ regexpSubstr(
514
+ expr: FnArg,
515
+ pattern: FnArg,
516
+ pos?: FnArg,
517
+ occurrence?: FnArg,
518
+ matchType?: FnArg,
519
+ ): FunctionBuilder<string | null>;
520
+ /** `REPEAT()` (portable) */
521
+ repeat(str: FnArg, count: FnArg): FunctionBuilder<string | null>;
522
+ /** `REPLACE()` (portable) */
523
+ replace(str: FnArg, from: FnArg, to: FnArg): FunctionBuilder<string | null>;
524
+ /** `REVERSE()` (portable) */
525
+ reverse(str: FnArg): FunctionBuilder<string | null>;
526
+ /** `RIGHT()` (portable) */
527
+ right(str: FnArg, len: FnArg): FunctionBuilder<string | null>;
528
+ /** `RPAD()` (portable) */
529
+ rpad(str: FnArg, len: FnArg, padStr: FnArg): FunctionBuilder<string | null>;
530
+ /** `RTRIM()` (portable) */
531
+ rtrim(str: FnArg): FunctionBuilder<string | null>;
532
+ /** `SOUNDEX()` (MySQL) */
533
+ soundex(str: FnArg): FunctionBuilder<string | null>;
534
+ /** `SPACE()` (MySQL) */
535
+ space(n: FnArg): FunctionBuilder<string | null>;
536
+ /** `STRCMP()` (MySQL) */
537
+ strcmp(a: FnArg, b: FnArg): FunctionBuilder<-1 | 0 | 1 | null>;
538
+ /** `SUBSTR()` (portable) */
539
+ substr(str: FnArg, pos: FnArg, len?: FnArg): FunctionBuilder<string | null>;
540
+ /** `SUBSTRING()` (portable) */
541
+ substring(str: FnArg, pos: FnArg, len?: FnArg): FunctionBuilder<string | null>;
542
+ /** `SUBSTRING_INDEX()` (MySQL) */
543
+ substringIndex(str: FnArg, delimiter: FnArg, count: FnArg): FunctionBuilder<string | null>;
544
+ /** `TO_BASE64()` (MySQL) */
545
+ toBase64(str: FnArg): FunctionBuilder<string | null>;
546
+ /** `TRIM()` (portable) */
547
+ trim(
548
+ str: FnArg,
549
+ options?: { side?: 'both' | 'leading' | 'trailing'; remove?: FnArg },
550
+ ): FunctionBuilder<string | null>;
551
+ /** `UCASE()` (MySQL) */
552
+ ucase(str: FnArg): FunctionBuilder<string | null>;
553
+ /** `UNHEX()` (MySQL) */
554
+ unhex(str: FnArg): FunctionBuilder<Buffer | null>;
555
+ /** `WEIGHT_STRING()` (MySQL) */
556
+ weightString(str: FnArg): FunctionBuilder<Buffer | null>;
557
+ /** `MATCH()` (MySQL) */
558
+ match(
559
+ columns: FnArg | FnArg[],
560
+ search: FnArg,
561
+ options?: {
562
+ mode?: 'natural' | 'natural with query expansion' | 'boolean' | 'with query expansion';
563
+ },
564
+ ): FunctionBuilder<number | null>;
565
+ /** `ABS()` (portable) */
566
+ abs(x: FnArg): FunctionBuilder<FnNumeric | null>;
567
+ /** `ACOS()` (portable) */
568
+ acos(x: FnArg): FunctionBuilder<number | null>;
569
+ /** `ASIN()` (portable) */
570
+ asin(x: FnArg): FunctionBuilder<number | null>;
571
+ /** `ATAN()` (MySQL) */
572
+ atan(x: FnArg, y?: FnArg): FunctionBuilder<number | null>;
573
+ /** `ATAN2()` (portable) */
574
+ atan2(y: FnArg, x: FnArg): FunctionBuilder<number | null>;
575
+ /** `CEIL()` (portable) */
576
+ ceil(x: FnArg): FunctionBuilder<FnNumeric | null>;
577
+ /** `CEILING()` (portable) */
578
+ ceiling(x: FnArg): FunctionBuilder<FnNumeric | null>;
579
+ /** `CONV()` (MySQL) */
580
+ conv(n: FnArg, fromBase: FnArg, toBase: FnArg): FunctionBuilder<string | null>;
581
+ /** `COS()` (portable) */
582
+ cos(x: FnArg): FunctionBuilder<number | null>;
583
+ /** `COT()` (portable) */
584
+ cot(x: FnArg): FunctionBuilder<number | null>;
585
+ /** `CRC32()` (MySQL) */
586
+ crc32(x: FnArg): FunctionBuilder<number | null>;
587
+ /** `DEGREES()` (portable) */
588
+ degrees(x: FnArg): FunctionBuilder<number | null>;
589
+ /** `EXP()` (portable) */
590
+ exp(x: FnArg): FunctionBuilder<number | null>;
591
+ /** `FLOOR()` (portable) */
592
+ floor(x: FnArg): FunctionBuilder<FnNumeric | null>;
593
+ /** `LN()` (portable) */
594
+ ln(x: FnArg): FunctionBuilder<number | null>;
595
+ /** `LOG()` (MySQL) */
596
+ log(baseOrX: FnArg, x?: FnArg): FunctionBuilder<number | null>;
597
+ /** `LOG10()` (MySQL) */
598
+ log10(x: FnArg): FunctionBuilder<number | null>;
599
+ /** `LOG2()` (MySQL) */
600
+ log2(x: FnArg): FunctionBuilder<number | null>;
601
+ /** `MOD()` (portable) */
602
+ mod(n: FnArg, m: FnArg): FunctionBuilder<FnNumeric | null>;
603
+ /** `PI()` (portable) */
604
+ pi(): FunctionBuilder<number | null>;
605
+ /** `POW()` (MySQL) */
606
+ pow(x: FnArg, y: FnArg): FunctionBuilder<number | null>;
607
+ /** `POWER()` (portable) */
608
+ power(x: FnArg, y: FnArg): FunctionBuilder<number | null>;
609
+ /** `RADIANS()` (portable) */
610
+ radians(x: FnArg): FunctionBuilder<number | null>;
611
+ /** `RAND()` (MySQL) */
612
+ rand(seed?: FnArg): FunctionBuilder<number | null>;
613
+ /** `ROUND()` (portable) */
614
+ round(x: FnArg, decimals?: FnArg): FunctionBuilder<FnNumeric | null>;
615
+ /** `SIGN()` (portable) */
616
+ sign(x: FnArg): FunctionBuilder<number | null>;
617
+ /** `SIN()` (portable) */
618
+ sin(x: FnArg): FunctionBuilder<number | null>;
619
+ /** `SQRT()` (portable) */
620
+ sqrt(x: FnArg): FunctionBuilder<number | null>;
621
+ /** `TAN()` (portable) */
622
+ tan(x: FnArg): FunctionBuilder<number | null>;
623
+ /** `TRUNCATE()` (MySQL) */
624
+ truncate(x: FnArg, decimals: FnArg): FunctionBuilder<FnNumeric | null>;
625
+ /** `ADDDATE()` (MySQL) */
626
+ addDate(
627
+ date: FnArg,
628
+ amount: FnArg,
629
+ unit?: FnIntervalUnit,
630
+ ): FunctionBuilder<Date | string | null>;
631
+ /** `ADDTIME()` (MySQL) */
632
+ addTime(datetime: FnArg, time: FnArg): FunctionBuilder<Date | string | null>;
633
+ /** `CONVERT_TZ()` (MySQL) */
634
+ convertTz(datetime: FnArg, fromTz: FnArg, toTz: FnArg): FunctionBuilder<Date | string | null>;
635
+ /** `CURDATE()` (MySQL) */
636
+ curDate(): FunctionBuilder<Date | string | null>;
637
+ /** `CURRENT_DATE()` (MySQL) */
638
+ currentDate(): FunctionBuilder<Date | string | null>;
639
+ /** `CURRENT_TIME()` (MySQL) */
640
+ currentTime(fsp?: number): FunctionBuilder<string | null>;
641
+ /** `CURRENT_TIMESTAMP()` (MySQL) */
642
+ currentTimestamp(fsp?: number): FunctionBuilder<Date | string | null>;
643
+ /** `CURTIME()` (MySQL) */
644
+ curTime(fsp?: number): FunctionBuilder<string | null>;
645
+ /** `DATE()` (MySQL) */
646
+ date(x: FnArg): FunctionBuilder<Date | string | null>;
647
+ /** `DATE_ADD()` (MySQL) */
648
+ dateAdd(
649
+ date: FnArg,
650
+ amount: FnArg,
651
+ unit: FnIntervalUnit,
652
+ ): FunctionBuilder<Date | string | null>;
653
+ /** `DATEDIFF()` (MySQL) */
654
+ dateDiff(a: FnArg, b: FnArg): FunctionBuilder<number | null>;
655
+ /** `DATE_FORMAT()` (MySQL) */
656
+ dateFormat(date: FnArg, format: FnArg): FunctionBuilder<string | null>;
657
+ /** `DATE_SUB()` (MySQL) */
658
+ dateSub(
659
+ date: FnArg,
660
+ amount: FnArg,
661
+ unit: FnIntervalUnit,
662
+ ): FunctionBuilder<Date | string | null>;
663
+ /** `DAY()` (MySQL) */
664
+ day(date: FnArg): FunctionBuilder<number | null>;
665
+ /** `DAYNAME()` (MySQL) */
666
+ dayName(date: FnArg): FunctionBuilder<string | null>;
667
+ /** `DAYOFMONTH()` (MySQL) */
668
+ dayOfMonth(date: FnArg): FunctionBuilder<number | null>;
669
+ /** `DAYOFWEEK()` (MySQL) */
670
+ dayOfWeek(date: FnArg): FunctionBuilder<number | null>;
671
+ /** `DAYOFYEAR()` (MySQL) */
672
+ dayOfYear(date: FnArg): FunctionBuilder<number | null>;
673
+ /** `EXTRACT()` (MySQL) */
674
+ extract(unit: FnIntervalUnit, date: FnArg): FunctionBuilder<number | null>;
675
+ /** `FROM_DAYS()` (MySQL) */
676
+ fromDays(days: FnArg): FunctionBuilder<Date | string | null>;
677
+ /** `FROM_UNIXTIME()` (MySQL) */
678
+ fromUnixTime(timestamp: FnArg, format?: FnArg): FunctionBuilder<Date | string | null>;
679
+ /** `GET_FORMAT()` (MySQL) */
680
+ getFormat(
681
+ type: 'DATE' | 'TIME' | 'DATETIME' | 'TIMESTAMP',
682
+ locale: FnArg,
683
+ ): FunctionBuilder<string | null>;
684
+ /** `HOUR()` (MySQL) */
685
+ hour(time: FnArg): FunctionBuilder<number | null>;
686
+ /** `LAST_DAY()` (MySQL) */
687
+ lastDay(date: FnArg): FunctionBuilder<Date | string | null>;
688
+ /** `LOCALTIME()` (MySQL) */
689
+ localTime(fsp?: number): FunctionBuilder<Date | string | null>;
690
+ /** `LOCALTIMESTAMP()` (MySQL) */
691
+ localTimestamp(fsp?: number): FunctionBuilder<Date | string | null>;
692
+ /** `MAKEDATE()` (MySQL) */
693
+ makeDate(year: FnArg, dayOfYear: FnArg): FunctionBuilder<Date | string | null>;
694
+ /** `MAKETIME()` (MySQL) */
695
+ makeTime(hour: FnArg, minute: FnArg, second: FnArg): FunctionBuilder<string | null>;
696
+ /** `MICROSECOND()` (MySQL) */
697
+ microsecond(time: FnArg): FunctionBuilder<number | null>;
698
+ /** `MINUTE()` (MySQL) */
699
+ minute(time: FnArg): FunctionBuilder<number | null>;
700
+ /** `MONTH()` (MySQL) */
701
+ month(date: FnArg): FunctionBuilder<number | null>;
702
+ /** `MONTHNAME()` (MySQL) */
703
+ monthName(date: FnArg): FunctionBuilder<string | null>;
704
+ /** `PERIOD_ADD()` (MySQL) */
705
+ periodAdd(period: FnArg, months: FnArg): FunctionBuilder<number | null>;
706
+ /** `PERIOD_DIFF()` (MySQL) */
707
+ periodDiff(a: FnArg, b: FnArg): FunctionBuilder<number | null>;
708
+ /** `QUARTER()` (MySQL) */
709
+ quarter(date: FnArg): FunctionBuilder<number | null>;
710
+ /** `SECOND()` (MySQL) */
711
+ second(time: FnArg): FunctionBuilder<number | null>;
712
+ /** `SEC_TO_TIME()` (MySQL) */
713
+ secToTime(seconds: FnArg): FunctionBuilder<string | null>;
714
+ /** `STR_TO_DATE()` (MySQL) */
715
+ strToDate(str: FnArg, format: FnArg): FunctionBuilder<Date | string | null>;
716
+ /** `SUBDATE()` (MySQL) */
717
+ subDate(
718
+ date: FnArg,
719
+ amount: FnArg,
720
+ unit?: FnIntervalUnit,
721
+ ): FunctionBuilder<Date | string | null>;
722
+ /** `SUBTIME()` (MySQL) */
723
+ subTime(datetime: FnArg, time: FnArg): FunctionBuilder<Date | string | null>;
724
+ /** `SYSDATE()` (MySQL) */
725
+ sysdate(fsp?: number): FunctionBuilder<Date | string | null>;
726
+ /** `TIME()` (MySQL) */
727
+ time(x: FnArg): FunctionBuilder<string | null>;
728
+ /** `TIMEDIFF()` (MySQL) */
729
+ timeDiff(a: FnArg, b: FnArg): FunctionBuilder<string | null>;
730
+ /** `TIMESTAMP()` (MySQL) */
731
+ timestamp(x: FnArg, time?: FnArg): FunctionBuilder<Date | string | null>;
732
+ /** `TIMESTAMPADD()` (MySQL) */
733
+ timestampAdd(
734
+ unit: FnTimestampUnit,
735
+ amount: FnArg,
736
+ date: FnArg,
737
+ ): FunctionBuilder<Date | string | null>;
738
+ /** `TIMESTAMPDIFF()` (MySQL) */
739
+ timestampDiff(unit: FnTimestampUnit, from: FnArg, to: FnArg): FunctionBuilder<number | null>;
740
+ /** `TIME_FORMAT()` (MySQL) */
741
+ timeFormat(time: FnArg, format: FnArg): FunctionBuilder<string | null>;
742
+ /** `TIME_TO_SEC()` (MySQL) */
743
+ timeToSec(time: FnArg): FunctionBuilder<number | null>;
744
+ /** `TO_DAYS()` (MySQL) */
745
+ toDays(date: FnArg): FunctionBuilder<number | null>;
746
+ /** `TO_SECONDS()` (MySQL) */
747
+ toSeconds(date: FnArg): FunctionBuilder<number | null>;
748
+ /** `UNIX_TIMESTAMP()` (MySQL) */
749
+ unixTimestamp(date?: FnArg): FunctionBuilder<FnNumeric | null>;
750
+ /** `UTC_DATE()` (MySQL) */
751
+ utcDate(): FunctionBuilder<Date | string | null>;
752
+ /** `UTC_TIME()` (MySQL) */
753
+ utcTime(fsp?: number): FunctionBuilder<string | null>;
754
+ /** `UTC_TIMESTAMP()` (MySQL) */
755
+ utcTimestamp(fsp?: number): FunctionBuilder<Date | string | null>;
756
+ /** `WEEK()` (MySQL) */
757
+ week(date: FnArg, mode?: FnArg): FunctionBuilder<number | null>;
758
+ /** `WEEKDAY()` (MySQL) */
759
+ weekday(date: FnArg): FunctionBuilder<number | null>;
760
+ /** `WEEKOFYEAR()` (MySQL) */
761
+ weekOfYear(date: FnArg): FunctionBuilder<number | null>;
762
+ /** `YEAR()` (MySQL) */
763
+ year(date: FnArg): FunctionBuilder<number | null>;
764
+ /** `YEARWEEK()` (MySQL) */
765
+ yearWeek(date: FnArg, mode?: FnArg): FunctionBuilder<number | null>;
766
+ /** `BIT_AND()` (MySQL, aggregate) */
767
+ bitAnd(x: FnArg): AggregateFunctionBuilder<FnNumeric | null>;
768
+ /** `BIT_OR()` (MySQL, aggregate) */
769
+ bitOr(x: FnArg): AggregateFunctionBuilder<FnNumeric | null>;
770
+ /** `BIT_XOR()` (MySQL, aggregate) */
771
+ bitXor(x: FnArg): AggregateFunctionBuilder<FnNumeric | null>;
772
+ /** `COUNT()` (portable, aggregate) */
773
+ countDistinct(...exprs: FnArg[]): AggregateFunctionBuilder<number>;
774
+ /** `GROUP_CONCAT()` (MySQL, aggregate) */
775
+ groupConcat(
776
+ exprs: FnArg | FnArg[],
777
+ options?: { distinct?: boolean; orderBy?: FnOrderBy | FnOrderBy[]; separator?: string },
778
+ ): AggregateFunctionBuilder<string | null>;
779
+ /** `JSON_ARRAYAGG()` (MySQL, aggregate) */
780
+ jsonArrayAgg(x: FnArg): AggregateFunctionBuilder<unknown[] | null>;
781
+ /** `JSON_OBJECTAGG()` (MySQL) */
782
+ jsonObjectAgg(key: FnArg, value: FnArg): FunctionBuilder<Record<string, unknown> | null>;
783
+ /** `STD()` (MySQL, aggregate) */
784
+ std(x: FnArg): AggregateFunctionBuilder<number | null>;
785
+ /** `STDDEV()` (portable, aggregate) */
786
+ stddev(x: FnArg): AggregateFunctionBuilder<number | null>;
787
+ /** `STDDEV_POP()` (portable, aggregate) */
788
+ stddevPop(x: FnArg): AggregateFunctionBuilder<number | null>;
789
+ /** `STDDEV_SAMP()` (portable, aggregate) */
790
+ stddevSamp(x: FnArg): AggregateFunctionBuilder<number | null>;
791
+ /** `VARIANCE()` (portable, aggregate) */
792
+ variance(x: FnArg): AggregateFunctionBuilder<number | null>;
793
+ /** `VAR_POP()` (portable, aggregate) */
794
+ varPop(x: FnArg): AggregateFunctionBuilder<number | null>;
795
+ /** `VAR_SAMP()` (portable, aggregate) */
796
+ varSamp(x: FnArg): AggregateFunctionBuilder<number | null>;
797
+ /** `ROW_NUMBER()` (portable, window function) */
798
+ rowNumber(): WindowFunctionBuilder<number>;
799
+ /** `RANK()` (portable, window function) */
800
+ rank(): WindowFunctionBuilder<number>;
801
+ /** `DENSE_RANK()` (portable, window function) */
802
+ denseRank(): WindowFunctionBuilder<number>;
803
+ /** `PERCENT_RANK()` (portable, window function) */
804
+ percentRank(): WindowFunctionBuilder<number>;
805
+ /** `CUME_DIST()` (portable, window function) */
806
+ cumeDist(): WindowFunctionBuilder<number>;
807
+ /** `NTILE()` (portable, window function) */
808
+ ntile(buckets: number): WindowFunctionBuilder<number>;
809
+ /** `LAG()` (portable, window function) */
810
+ lag(x: FnArg, offset?: number, defaultValue?: FnArg): WindowFunctionBuilder<unknown>;
811
+ /** `LEAD()` (portable, window function) */
812
+ lead(x: FnArg, offset?: number, defaultValue?: FnArg): WindowFunctionBuilder<unknown>;
813
+ /** `FIRST_VALUE()` (portable, window function) */
814
+ firstValue(x: FnArg): WindowFunctionBuilder<unknown>;
815
+ /** `LAST_VALUE()` (portable, window function) */
816
+ lastValue(x: FnArg): WindowFunctionBuilder<unknown>;
817
+ /** `NTH_VALUE()` (portable, window function) */
818
+ nthValue(x: FnArg, n: number): WindowFunctionBuilder<unknown>;
819
+ /** `GREATEST()` (portable) */
820
+ greatest(...values: FnArg[]): FunctionBuilder<unknown>;
821
+ /** `IF()` (MySQL) */
822
+ if(condition: FnArg, then: FnArg, otherwise: FnArg): FunctionBuilder<unknown>;
823
+ /** `IFNULL()` (MySQL) */
824
+ ifNull(value: FnArg, otherwise: FnArg): FunctionBuilder<unknown>;
825
+ /** `INTERVAL()` (MySQL) */
826
+ interval(n: FnArg, ...ns: FnArg[]): FunctionBuilder<number | null>;
827
+ /** `ISNULL()` (MySQL) */
828
+ isNull(x: FnArg): FunctionBuilder<0 | 1 | null>;
829
+ /** `LEAST()` (portable) */
830
+ least(...values: FnArg[]): FunctionBuilder<unknown>;
831
+ /** `NULLIF()` (portable) */
832
+ nullIf(a: FnArg, b: FnArg): FunctionBuilder<unknown>;
833
+ /** `CAST()` (MySQL) */
834
+ cast(x: FnArg, type: string): FunctionBuilder<unknown>;
835
+ /** `CONVERT()` (MySQL) */
836
+ convert(x: FnArg, type: string | { using: string }): FunctionBuilder<unknown>;
837
+ /** `CHARSET()` (MySQL) */
838
+ charset(str: FnArg): FunctionBuilder<string | null>;
839
+ /** `COERCIBILITY()` (MySQL) */
840
+ coercibility(str: FnArg): FunctionBuilder<number | null>;
841
+ /** `COLLATION()` (MySQL) */
842
+ collation(str: FnArg): FunctionBuilder<string | null>;
843
+ /** `CONNECTION_ID()` (MySQL) */
844
+ connectionId(): FunctionBuilder<number | null>;
845
+ /** `CURRENT_ROLE()` (MySQL) */
846
+ currentRole(): FunctionBuilder<string | null>;
847
+ /** `CURRENT_USER()` (MySQL) */
848
+ currentUser(): FunctionBuilder<string | null>;
849
+ /** `DATABASE()` (MySQL) */
850
+ database(): FunctionBuilder<string | null>;
851
+ /** `ICU_VERSION()` (MySQL) */
852
+ icuVersion(): FunctionBuilder<string | null>;
853
+ /** `LAST_INSERT_ID()` (MySQL) */
854
+ lastInsertId(x?: FnArg): FunctionBuilder<number | null>;
855
+ /** `ROLES_GRAPHML()` (MySQL) */
856
+ rolesGraphml(): FunctionBuilder<string | null>;
857
+ /** `ROW_COUNT()` (MySQL) */
858
+ rowCount(): FunctionBuilder<number | null>;
859
+ /** `SCHEMA()` (MySQL) */
860
+ schema(): FunctionBuilder<string | null>;
861
+ /** `SESSION_USER()` (MySQL) */
862
+ sessionUser(): FunctionBuilder<string | null>;
863
+ /** `SYSTEM_USER()` (MySQL) */
864
+ systemUser(): FunctionBuilder<string | null>;
865
+ /** `USER()` (MySQL) */
866
+ user(): FunctionBuilder<string | null>;
867
+ /** `VERSION()` (MySQL) */
868
+ version(): FunctionBuilder<string | null>;
869
+ /** `AES_DECRYPT()` (MySQL) */
870
+ aesDecrypt(crypt: FnArg, key: FnArg, ...options: FnArg[]): FunctionBuilder<Buffer | null>;
871
+ /** `AES_ENCRYPT()` (MySQL) */
872
+ aesEncrypt(str: FnArg, key: FnArg, ...options: FnArg[]): FunctionBuilder<Buffer | null>;
873
+ /** `COMPRESS()` (MySQL) */
874
+ compress(str: FnArg): FunctionBuilder<Buffer | null>;
875
+ /** `MD5()` (portable) */
876
+ md5(str: FnArg): FunctionBuilder<string | null>;
877
+ /** `RANDOM_BYTES()` (MySQL) */
878
+ randomBytes(length: FnArg): FunctionBuilder<Buffer | null>;
879
+ /** `SHA1()` (MySQL) */
880
+ sha1(str: FnArg): FunctionBuilder<string | null>;
881
+ /** `SHA2()` (MySQL) */
882
+ sha2(str: FnArg, hashLength: FnArg): FunctionBuilder<string | null>;
883
+ /** `STATEMENT_DIGEST()` (MySQL) */
884
+ statementDigest(statement: FnArg): FunctionBuilder<string | null>;
885
+ /** `STATEMENT_DIGEST_TEXT()` (MySQL) */
886
+ statementDigestText(statement: FnArg): FunctionBuilder<string | null>;
887
+ /** `UNCOMPRESS()` (MySQL) */
888
+ uncompress(str: FnArg): FunctionBuilder<Buffer | null>;
889
+ /** `UNCOMPRESSED_LENGTH()` (MySQL) */
890
+ uncompressedLength(str: FnArg): FunctionBuilder<number | null>;
891
+ /** `GET_LOCK()` (MySQL) */
892
+ getLock(name: FnArg, timeout: FnArg): FunctionBuilder<0 | 1 | null>;
893
+ /** `IS_FREE_LOCK()` (MySQL) */
894
+ isFreeLock(name: FnArg): FunctionBuilder<0 | 1 | null>;
895
+ /** `IS_USED_LOCK()` (MySQL) */
896
+ isUsedLock(name: FnArg): FunctionBuilder<number | null>;
897
+ /** `RELEASE_ALL_LOCKS()` (MySQL) */
898
+ releaseAllLocks(): FunctionBuilder<number | null>;
899
+ /** `RELEASE_LOCK()` (MySQL) */
900
+ releaseLock(name: FnArg): FunctionBuilder<0 | 1 | null>;
901
+ /** `ANY_VALUE()` (MySQL) */
902
+ anyValue(x: FnArg): FunctionBuilder<unknown>;
903
+ /** `BIN_TO_UUID()` (MySQL) */
904
+ binToUuid(bin: FnArg, swap?: FnArg): FunctionBuilder<string | null>;
905
+ /** `DEFAULT()` (MySQL) */
906
+ default(column: FnArg): FunctionBuilder<unknown>;
907
+ /** `GROUPING()` (MySQL) */
908
+ grouping(...exprs: FnArg[]): FunctionBuilder<number | null>;
909
+ /** `INET6_ATON()` (MySQL) */
910
+ inet6Aton(address: FnArg): FunctionBuilder<Buffer | null>;
911
+ /** `INET6_NTOA()` (MySQL) */
912
+ inet6Ntoa(address: FnArg): FunctionBuilder<string | null>;
913
+ /** `INET_ATON()` (MySQL) */
914
+ inetAton(address: FnArg): FunctionBuilder<number | null>;
915
+ /** `INET_NTOA()` (MySQL) */
916
+ inetNtoa(address: FnArg): FunctionBuilder<string | null>;
917
+ /** `IS_IPV4()` (MySQL) */
918
+ isIpv4(address: FnArg): FunctionBuilder<0 | 1 | null>;
919
+ /** `IS_IPV4_COMPAT()` (MySQL) */
920
+ isIpv4Compat(address: FnArg): FunctionBuilder<0 | 1 | null>;
921
+ /** `IS_IPV4_MAPPED()` (MySQL) */
922
+ isIpv4Mapped(address: FnArg): FunctionBuilder<0 | 1 | null>;
923
+ /** `IS_IPV6()` (MySQL) */
924
+ isIpv6(address: FnArg): FunctionBuilder<0 | 1 | null>;
925
+ /** `IS_UUID()` (MySQL) */
926
+ isUuid(uuid: FnArg): FunctionBuilder<0 | 1 | null>;
927
+ /** `SLEEP()` (MySQL) */
928
+ sleep(seconds: FnArg): FunctionBuilder<number | null>;
929
+ /** `UUID()` (MySQL) */
930
+ uuid(): FunctionBuilder<string>;
931
+ /** `UUID_SHORT()` (MySQL) */
932
+ uuidShort(): FunctionBuilder<FnNumeric>;
933
+ /** `UUID_TO_BIN()` (MySQL) */
934
+ uuidToBin(uuid: FnArg, swap?: FnArg): FunctionBuilder<Buffer | null>;
935
+ /** `BIT_COUNT()` (MySQL) */
936
+ bitCount(x: FnArg): FunctionBuilder<number | null>;
937
+ /** `FORMAT_BYTES()` (MySQL) */
938
+ formatBytes(bytes: FnArg): FunctionBuilder<string | null>;
939
+ /** `FORMAT_PICO_TIME()` (MySQL) */
940
+ formatPicoTime(time: FnArg): FunctionBuilder<string | null>;
941
+ /** `PS_CURRENT_THREAD_ID()` (MySQL) */
942
+ psCurrentThreadId(): FunctionBuilder<number | null>;
943
+ /** `PS_THREAD_ID()` (MySQL) */
944
+ psThreadId(connectionId: FnArg): FunctionBuilder<number | null>;
945
+ /** `GTID_SUBSET()` (MySQL) */
946
+ gtidSubset(set1: FnArg, set2: FnArg): FunctionBuilder<0 | 1 | null>;
947
+ /** `GTID_SUBTRACT()` (MySQL) */
948
+ gtidSubtract(set1: FnArg, set2: FnArg): FunctionBuilder<string | null>;
949
+ /** `SOURCE_POS_WAIT()` (MySQL) */
950
+ sourcePosWait(
951
+ logName: FnArg,
952
+ logPos: FnArg,
953
+ ...options: FnArg[]
954
+ ): FunctionBuilder<number | null>;
955
+ /** `WAIT_FOR_EXECUTED_GTID_SET()` (MySQL) */
956
+ waitForExecutedGtidSet(gtidSet: FnArg, timeout?: FnArg): FunctionBuilder<number | null>;
957
+ /** `EXTRACTVALUE()` (MySQL) */
958
+ extractValue(xml: FnArg, xpath: FnArg): FunctionBuilder<string | null>;
959
+ /** `UPDATEXML()` (MySQL) */
960
+ updateXml(xml: FnArg, xpath: FnArg, newXml: FnArg): FunctionBuilder<string | null>;
961
+ /** `JSON_ARRAY()` (MySQL) */
962
+ jsonArray(...values: FnJsonArg[]): FunctionBuilder<unknown[]>;
963
+ /** `JSON_ARRAY_APPEND()` (MySQL) */
964
+ jsonArrayAppend(
965
+ doc: FnJsonArg,
966
+ path: FnArg,
967
+ value: FnJsonArg,
968
+ ...pathsAndValues: FnJsonArg[]
969
+ ): FunctionBuilder<unknown>;
970
+ /** `JSON_ARRAY_INSERT()` (MySQL) */
971
+ jsonArrayInsert(
972
+ doc: FnJsonArg,
973
+ path: FnArg,
974
+ value: FnJsonArg,
975
+ ...pathsAndValues: FnJsonArg[]
976
+ ): FunctionBuilder<unknown>;
977
+ /** `JSON_CONTAINS()` (MySQL) */
978
+ jsonContains(
979
+ target: FnJsonArg,
980
+ candidate: FnJsonArg,
981
+ path?: FnArg,
982
+ ): FunctionBuilder<0 | 1 | null>;
983
+ /** `JSON_CONTAINS_PATH()` (MySQL) */
984
+ jsonContainsPath(
985
+ doc: FnJsonArg,
986
+ oneOrAll: 'one' | 'all',
987
+ ...paths: FnArg[]
988
+ ): FunctionBuilder<0 | 1 | null>;
989
+ /** `JSON_DEPTH()` (MySQL) */
990
+ jsonDepth(doc: FnJsonArg): FunctionBuilder<number | null>;
991
+ /** `JSON_EXTRACT()` (MySQL) */
992
+ jsonExtract(doc: FnJsonArg, ...paths: FnArg[]): FunctionBuilder<unknown>;
993
+ /** `JSON_INSERT()` (MySQL) */
994
+ jsonInsert(
995
+ doc: FnJsonArg,
996
+ path: FnArg,
997
+ value: FnJsonArg,
998
+ ...pathsAndValues: FnJsonArg[]
999
+ ): FunctionBuilder<unknown>;
1000
+ /** `JSON_KEYS()` (MySQL) */
1001
+ jsonKeys(doc: FnJsonArg, path?: FnArg): FunctionBuilder<string[] | null>;
1002
+ /** `JSON_LENGTH()` (MySQL) */
1003
+ jsonLength(doc: FnJsonArg, path?: FnArg): FunctionBuilder<number | null>;
1004
+ /** `JSON_MERGE_PATCH()` (MySQL) */
1005
+ jsonMergePatch(...docs: FnJsonArg[]): FunctionBuilder<unknown>;
1006
+ /** `JSON_MERGE_PRESERVE()` (MySQL) */
1007
+ jsonMergePreserve(...docs: FnJsonArg[]): FunctionBuilder<unknown>;
1008
+ /** `JSON_OBJECT()` (MySQL) */
1009
+ jsonObject(
1010
+ objectOrKeysAndValues?: { [key: string]: FnJsonArg } | FnJsonArg,
1011
+ ...keysAndValues: FnJsonArg[]
1012
+ ): FunctionBuilder<Record<string, unknown>>;
1013
+ /** `JSON_OVERLAPS()` (MySQL) */
1014
+ jsonOverlaps(a: FnJsonArg, b: FnJsonArg): FunctionBuilder<0 | 1 | null>;
1015
+ /** `JSON_PRETTY()` (MySQL) */
1016
+ jsonPretty(doc: FnJsonArg): FunctionBuilder<string | null>;
1017
+ /** `JSON_QUOTE()` (MySQL) */
1018
+ jsonQuote(str: FnArg): FunctionBuilder<string | null>;
1019
+ /** `JSON_REMOVE()` (MySQL) */
1020
+ jsonRemove(doc: FnJsonArg, ...paths: FnArg[]): FunctionBuilder<unknown>;
1021
+ /** `JSON_REPLACE()` (MySQL) */
1022
+ jsonReplace(
1023
+ doc: FnJsonArg,
1024
+ path: FnArg,
1025
+ value: FnJsonArg,
1026
+ ...pathsAndValues: FnJsonArg[]
1027
+ ): FunctionBuilder<unknown>;
1028
+ /** `JSON_SCHEMA_VALID()` (MySQL) */
1029
+ jsonSchemaValid(schema: FnJsonArg, doc: FnJsonArg): FunctionBuilder<0 | 1 | null>;
1030
+ /** `JSON_SCHEMA_VALIDATION_REPORT()` (MySQL) */
1031
+ jsonSchemaValidationReport(
1032
+ schema: FnJsonArg,
1033
+ doc: FnJsonArg,
1034
+ ): FunctionBuilder<Record<string, unknown> | null>;
1035
+ /** `JSON_SEARCH()` (MySQL) */
1036
+ jsonSearch(
1037
+ doc: FnJsonArg,
1038
+ oneOrAll: 'one' | 'all',
1039
+ search: FnArg,
1040
+ escape?: FnArg,
1041
+ ...paths: FnArg[]
1042
+ ): FunctionBuilder<string | string[] | null>;
1043
+ /** `JSON_SET()` (MySQL) */
1044
+ jsonSet(
1045
+ doc: FnJsonArg,
1046
+ path: FnArg,
1047
+ value: FnJsonArg,
1048
+ ...pathsAndValues: FnJsonArg[]
1049
+ ): FunctionBuilder<unknown>;
1050
+ /** `JSON_STORAGE_FREE()` (MySQL) */
1051
+ jsonStorageFree(doc: FnJsonArg): FunctionBuilder<number | null>;
1052
+ /** `JSON_STORAGE_SIZE()` (MySQL) */
1053
+ jsonStorageSize(doc: FnJsonArg): FunctionBuilder<number | null>;
1054
+ /** `JSON_TYPE()` (MySQL) */
1055
+ jsonType(value: FnJsonArg): FunctionBuilder<string | null>;
1056
+ /** `JSON_UNQUOTE()` (MySQL) */
1057
+ jsonUnquote(str: FnArg): FunctionBuilder<string | null>;
1058
+ /** `JSON_VALID()` (MySQL) */
1059
+ jsonValid(value: FnArg): FunctionBuilder<0 | 1 | null>;
1060
+ /** `JSON_VALUE()` (MySQL) */
1061
+ jsonValue(
1062
+ doc: FnJsonArg,
1063
+ path: FnArg,
1064
+ options?: { returning?: string },
1065
+ ): FunctionBuilder<unknown>;
1066
+ /** `MEMBER OF()` (MySQL) */
1067
+ memberOf(value: FnJsonArg, array: FnJsonArg): FunctionBuilder<0 | 1 | null>;
1068
+ // </generated:mysql-functions>
1069
+ }
1070
+
1071
+ export interface ComposeFunction {
1072
+ (...plugins: Plugin[]): Plugin;
1073
+ (plugins: Plugin[]): Plugin;
1074
+ }
1075
+
1076
+ export interface Plugin {
1077
+ <M extends typeof Model>(modelClass: M): M;
1078
+ }
1079
+
1080
+ export interface MixinFunction {
1081
+ <MC extends AnyModelConstructor>(modelClass: MC, ...plugins: Plugin[]): MC;
1082
+ <MC extends AnyModelConstructor>(modelClass: MC, plugins: Plugin[]): MC;
1083
+ }
1084
+
1085
+ interface Aliasable {
1086
+ as(alias: string): this;
1087
+ }
1088
+
1089
+ interface Castable extends Aliasable {
1090
+ castText(): this;
1091
+ castInt(): this;
1092
+ castBigInt(): this;
1093
+ castFloat(): this;
1094
+ castDecimal(): this;
1095
+ castReal(): this;
1096
+ castBool(): this;
1097
+ castJson(): this;
1098
+ castArray(): this;
1099
+ asArray(): this;
1100
+ castType(sqlType: string): this;
1101
+ castTo(sqlType: string): this;
1102
+ }
1103
+
1104
+ type Raw = RawBuilder | Knex.Raw;
1105
+ type Operator = string;
1106
+ type ColumnRef = string | Raw | ReferenceBuilder;
1107
+ /**
1108
+ * A table: a name, a model class, a subquery, or an object that maps aliases to
1109
+ * any of these (`{ p: Pet }`).
1110
+ */
1111
+ type TableRef<QB extends AnyQueryBuilder> =
1112
+ | ColumnRef
1113
+ | AnyQueryBuilder
1114
+ | CallbackVoid<QB>
1115
+ | AnyModelConstructor
1116
+ | { [alias: string]: string | AnyModelConstructor | AnyQueryBuilder | Raw };
1117
+
1118
+ type PrimitiveValue =
1119
+ | string
1120
+ | number
1121
+ | boolean
1122
+ | Date
1123
+ | Buffer
1124
+ | string[]
1125
+ | number[]
1126
+ | boolean[]
1127
+ | Date[]
1128
+ | Buffer[]
1129
+ | null;
1130
+
1131
+ type Expression<T> = T | Raw | ReferenceBuilder | ValueBuilder | AnyQueryBuilder;
1132
+
1133
+ type Id = string | number | BigInt | Buffer;
1134
+ type CompositeId = Id[];
1135
+ type MaybeCompositeId = Id | CompositeId;
1136
+
1137
+ interface ExpressionObject {
1138
+ [key: string]: Expression<PrimitiveValue>;
1139
+ }
1140
+
1141
+ interface PrimitiveValueObject {
1142
+ [key: string]: PrimitiveValue;
1143
+ }
1144
+
1145
+ interface CallbackVoid<T> {
1146
+ (this: T, arg: T): void;
1147
+ }
1148
+
1149
+ type Identity<T> = (value: T) => T;
1150
+ /**
1151
+ * A query builder of any result kind for models of type `M`.
1152
+ *
1153
+ * Use this as the parameter type of modifiers and other functions that take
1154
+ * query builders so that they accept queries of every kind (`find`,
1155
+ * `first()`, `findById()`, `patch()`, ...).
1156
+ */
1157
+ type AnyQueryBuilder<M extends Model = any> = QueryBuilder<M, any, any>;
1158
+ type AnyModelConstructor = ModelConstructor<Model>;
1159
+ type ModifierFunction<QB extends AnyQueryBuilder> = (qb: QB, ...args: any[]) => void;
1160
+ type Modifier<QB extends AnyQueryBuilder = AnyQueryBuilder> =
1161
+ | ModifierFunction<QB>
1162
+ | string
1163
+ | string[]
1164
+ | Record<string, Expression<PrimitiveValue>>;
1165
+ type OrderByDirection = 'asc' | 'desc' | 'ASC' | 'DESC';
1166
+ type OrderByNulls = 'first' | 'last';
1167
+
1168
+ interface Modifiers<QB extends AnyQueryBuilder = AnyQueryBuilder> {
1169
+ [key: string]: Modifier<QB>;
1170
+ }
1171
+
1172
+ type RelationExpression<M extends Model> = string | object;
1173
+
1174
+ /**
1175
+ * `E` if it's a valid relation expression for model `M`, otherwise a message
1176
+ * that says what's wrong with it. Expressions that aren't known at compile time
1177
+ * (like a `string`) aren't checked.
1178
+ */
1179
+ type CheckRelationExpression<M, E, CheckModifiers extends boolean = true> =
1180
+ ParseRelationExpression<E> extends infer G
1181
+ ? G extends ParseError<infer Message>
1182
+ ? Message
1183
+ : G extends GraphNode
1184
+ ? GraphErrors<M, G['children'], '', CheckModifiers> extends infer Errors
1185
+ ? [Errors] extends [never]
1186
+ ? E
1187
+ : Errors
1188
+ : never
1189
+ : E
1190
+ : never;
1191
+
1192
+ // The errors of the nodes of a relation graph of model `M`. `Path` is the path
1193
+ // of the parent node followed by a dot, or an empty string at the root.
1194
+ type GraphErrors<M, Children, Path extends string, CheckModifiers extends boolean> =
1195
+ IsUncheckedModel<M> extends true
1196
+ ? never
1197
+ : {
1198
+ [P in keyof Children & string]: Children[P] extends GraphNode
1199
+ ? NodeErrors<M, Children[P], P, Path, CheckModifiers>
1200
+ : never;
1201
+ }[keyof Children & string];
1202
+
1203
+ type NodeErrors<
1204
+ M,
1205
+ N extends GraphNode,
1206
+ Prop extends string,
1207
+ Path extends string,
1208
+ CheckModifiers extends boolean,
1209
+ > =
1210
+ N['rel'] extends RelationNameKeys<M>
1211
+ ?
1212
+ | (CheckModifiers extends true
1213
+ ? ModifierNameErrors<RelatedModel<M, N['rel']>, N['mods'], `${Path}${Prop}`>
1214
+ : never)
1215
+ | GraphErrors<RelatedModel<M, N['rel']>, N['children'], `${Path}${Prop}.`, CheckModifiers>
1216
+ : Path extends `${infer Parent}.`
1217
+ ? `Unknown relation "${N['rel']}" at "${Parent}"`
1218
+ : `Unknown relation "${N['rel']}"`;
1219
+
1220
+ // Named modifiers of a node must be modifiers of the related model, when its
1221
+ // modifiers are known.
1222
+ type ModifierNameErrors<RM, Mods extends readonly unknown[], Path extends string> = [
1223
+ KnownModifiers<RM>,
1224
+ ] extends [never]
1225
+ ? never
1226
+ : {
1227
+ [I in keyof Mods]: Mods[I] extends string
1228
+ ? Mods[I] extends keyof KnownModifiers<RM>
1229
+ ? never
1230
+ : `Unknown modifier "${Mods[I]}" for "${Path}"`
1231
+ : never;
1232
+ }[number];
1233
+
1234
+ // The names that are accepted as relations of `M`: its relation properties, and
1235
+ // the properties typed as objects, since relations are sometimes declared with
1236
+ // types that aren't models, like `programs?: Pick<Program, 'id' | 'name'>[]`.
1237
+ type RelationNameKeys<M> =
1238
+ | RelationKeys<M>
1239
+ | {
1240
+ [K in ModelDataKeys<M>]-?: K extends `$${string}`
1241
+ ? never
1242
+ : IsAnyType<M[K]> extends true
1243
+ ? never
1244
+ : NonNullable<M[K]> extends Function | Date
1245
+ ? never
1246
+ : NonNullable<M[K]> extends object
1247
+ ? K
1248
+ : never;
1249
+ }[ModelDataKeys<M>];
1250
+
1251
+ // The related model of relation `K` of model `M`.
1252
+ type RelatedModel<M, K extends keyof M> = ElementOrSelf<NonNullable<M[K]>>;
1253
+
1254
+ type ElementOrSelf<T> = T extends readonly (infer E)[] ? E : T;
1255
+
1256
+ // Models whose relations can't be known, like the related model of a relation
1257
+ // whose `modelClass` is a module path.
1258
+ type IsUncheckedModel<M> =
1259
+ IsAnyType<M> extends true
1260
+ ? true
1261
+ : [Exclude<keyof M, keyof Model>] extends [never]
1262
+ ? true
1263
+ : false;
1264
+
1265
+ /**
1266
+ * The type of model `M` with the relations of the relation expression `E`
1267
+ * loaded: `Loaded<Person, '[pets.toys, mom]'>`.
1268
+ */
1269
+ export type Loaded<M, E> = WithGraph<ModelRow<M>, M, E>;
1270
+
1271
+ // Result item `I` of model `M` after loading the relations of expression `E`.
1272
+ type WithGraph<I, M, E> =
1273
+ IsAnyType<I> extends true
1274
+ ? any
1275
+ : ParseRelationExpression<E> extends infer G
1276
+ ? G extends GraphNode
1277
+ ? G['all'] extends true
1278
+ ? MakeOpaque<I, M>
1279
+ : WithChildren<I, M, G['children']>
1280
+ : MakeOpaque<I, M>
1281
+ : never;
1282
+
1283
+ type WithChildren<I, M, Children> = [keyof Children] extends [never]
1284
+ ? I
1285
+ : [Extract<keyof Children, keyof I>] extends [never]
1286
+ ? I & LoadedRelations<I, M, Children>
1287
+ : Replace<I, M, Extract<keyof Children, keyof I>, LoadedRelations<I, M, Children>>;
1288
+
1289
+ // `I` with the properties `K` replaced by `Props`. The rows of models that keep
1290
+ // their relations (see `ModelRow`) aren't copied, since the copy couldn't be
1291
+ // used where the model is expected. `Props` is intersected with them instead.
1292
+ type Replace<I, M, K, Props> = [Row<M>] extends [ModelRow<M>] ? Without<I, K> & Props : I & Props;
1293
+
1294
+ // `I` without the properties `K`.
1295
+ type Without<I, K> = { [P in keyof I as P extends K ? never : P]: I[P] };
1296
+
1297
+ type LoadedRelations<I, M, Children> = {
1298
+ -readonly [P in keyof Children as Children[P] extends { maybe: true }
1299
+ ? never
1300
+ : P]: LoadedRelation<I, M, P, Children[P]>;
1301
+ } & MaybeLoadedRelations<I, M, Children>;
1302
+
1303
+ // Relations with a `boolean` in object notation, which may not be loaded.
1304
+ type MaybeLoadedRelations<I, M, Children> = [
1305
+ { [P in keyof Children]: Children[P] extends { maybe: true } ? P : never }[keyof Children],
1306
+ ] extends [never]
1307
+ ? unknown
1308
+ : {
1309
+ -readonly [P in keyof Children as Children[P] extends { maybe: true }
1310
+ ? P
1311
+ : never]?: LoadedRelation<I, M, P, Children[P]>;
1312
+ };
1313
+
1314
+ // The type of the relation property `P` loaded by node `N`.
1315
+ type LoadedRelation<I, M, P, N> = N extends GraphNode
1316
+ ? N['rel'] extends keyof M
1317
+ ? RelationValue<M[N['rel']], LoadedNodeRow<PreviousRow<I, P>, RelatedModel<M, N['rel']>, N>>
1318
+ : unknown
1319
+ : unknown;
1320
+
1321
+ // To-many relations are arrays. Objection sets to-one relations to `null` when
1322
+ // there's no related model, but rows must still be usable where the model is
1323
+ // expected, so the declared type decides: `Row | null` for relations declared
1324
+ // with `| null` (like the inferred ones), `Row | undefined` for optional ones.
1325
+ type RelationValue<Declared, Row> = [NonNullable<Declared>] extends [readonly any[]]
1326
+ ? Row[]
1327
+ : [Extract<NonNullable<Declared>, readonly any[]>] extends [never]
1328
+ ? null extends Declared
1329
+ ? Row | null
1330
+ : undefined extends Declared
1331
+ ? Row | undefined
1332
+ : Row
1333
+ : Row | Row[] | null;
1334
+
1335
+ // The row of a relation that an earlier call already loaded, so that calls
1336
+ // add to each other like they do at runtime.
1337
+ type PreviousRow<I, P> = P extends keyof I
1338
+ ? {} extends Pick<I, P>
1339
+ ? never
1340
+ : ElementOrSelf<NonNullable<I[P]>>
1341
+ : never;
1342
+
1343
+ // The row of the related model `RM` loaded by node `N`, starting from `Previous`.
1344
+ type LoadedNodeRow<Previous, RM, N extends GraphNode> = WithChildren<
1345
+ ApplyNodeModifiers<
1346
+ [Previous] extends [never] ? ModelRow<RM> : Previous,
1347
+ RM,
1348
+ N['recursive'] extends true ? ['~opaque'] : N['all'] extends true ? ['~opaque'] : N['mods']
1349
+ >,
1350
+ RM,
1351
+ N['children']
1352
+ >;
1353
+
1354
+ type ApplyNodeModifiers<I, RM, Mods> = Mods extends readonly [infer First, ...infer Rest]
1355
+ ? ApplyNodeModifiers<ModifiedItem<I, RM, First>, RM, Rest>
1356
+ : I;
1357
+
1358
+ // The item after a modifier. A modifier function that returns the query builder
1359
+ // adds what it loaded. Anything else may load relations the types can't see.
1360
+ type ModifiedItem<I, M, Modifier> = Modifier extends (...args: any[]) => infer Ret
1361
+ ? ReturnedItem<I, M, Ret>
1362
+ : [KnownModifiers<M>] extends [never]
1363
+ ? MakeOpaque<I, M>
1364
+ : Modifier extends keyof KnownModifiers<M>
1365
+ ? ModifiedItem<I, M, KnownModifiers<M>[Modifier]>
1366
+ : MakeOpaque<I, M>;
1367
+
1368
+ type ReturnedItem<I, M, Ret> = Ret extends { '~state': infer S extends QueryBuilderState }
1369
+ ? IsAnyType<S['item']> extends true
1370
+ ? MakeOpaque<I, M>
1371
+ : S extends { opaque: true }
1372
+ ? MakeOpaque<MergeLoaded<I, M, S['item']>, M>
1373
+ : MergeLoaded<I, M, S['item']>
1374
+ : MakeOpaque<I, M>;
1375
+
1376
+ // Adds to `I` the relations `Other` has loaded: its required relation
1377
+ // properties and the properties that aren't properties of the model (aliases).
1378
+ type MergeLoaded<I, M, Other> = [LoadedKeys<M, Other>] extends [never]
1379
+ ? I
1380
+ : [Extract<LoadedKeys<M, Other>, keyof I>] extends [never]
1381
+ ? I & Only<Other, LoadedKeys<M, Other>>
1382
+ : Replace<I, M, LoadedKeys<M, Other>, Only<Other, LoadedKeys<M, Other>>>;
1383
+
1384
+ // Like `Pick`, but shown as an object type in messages.
1385
+ type Only<T, K> = { [P in keyof T as P extends K ? P : never]: T[P] };
1386
+
1387
+ type LoadedKeys<M, Other> =
1388
+ | {
1389
+ [K in keyof Other]-?: K extends RelationKeys<M>
1390
+ ? {} extends Pick<Other, K>
1391
+ ? never
1392
+ : K
1393
+ : never;
1394
+ }[keyof Other]
1395
+ | Exclude<keyof Other, keyof M>;
1396
+
1397
+ // The query builder `QB` after loading the relations of expression `E`.
1398
+ type WithGraphQueryBuilder<QB extends AnyQueryBuilder, E> = QB['~state'] extends {
1399
+ cast: true;
1400
+ }
1401
+ ? OpaqueQueryBuilder<QB>
1402
+ : ParseRelationExpression<E> extends GraphNode
1403
+ ? ItemQueryBuilder<QB, WithGraph<QB['~state']['item'], GraphModel<QB>, E>>
1404
+ : OpaqueQueryBuilder<QB>;
1405
+
1406
+ // An interface instead of a static method, so that it isn't compared every
1407
+ // time a model class is compared with another one.
1408
+ interface StaticFetchGraphMethod {
1409
+ <
1410
+ MC extends Constructor<Model>,
1411
+ T extends PartialModelObject<Extract<ModelInstance<MC>, Model>>,
1412
+ const E extends RelationExpression<Extract<ModelInstance<MC>, Model>>,
1413
+ >(
1414
+ this: MC,
1415
+ modelOrObject: T,
1416
+ expression: CheckRelationExpression<ModelInstance<MC>, E>,
1417
+ options?: FetchGraphOptions,
1418
+ ): StaticFetchGraphQueryBuilder<MC, T, E, 'one'>;
1419
+ <
1420
+ MC extends Constructor<Model>,
1421
+ T extends PartialModelObject<Extract<ModelInstance<MC>, Model>>,
1422
+ const E extends RelationExpression<Extract<ModelInstance<MC>, Model>>,
1423
+ >(
1424
+ this: MC,
1425
+ modelOrObject: T[],
1426
+ expression: CheckRelationExpression<ModelInstance<MC>, E>,
1427
+ options?: FetchGraphOptions,
1428
+ ): StaticFetchGraphQueryBuilder<MC, T, E, 'many'>;
1429
+ }
1430
+
1431
+ type StaticFetchGraphQueryBuilder<MC, T, E, Kind extends 'one' | 'many'> =
1432
+ Extract<ModelInstance<MC>, Model> extends infer M extends Model
1433
+ ? [M] extends [never]
1434
+ ? any
1435
+ : FetchGraphQueryBuilder<QueryBuilderType<M>, M, T, E, Kind>
1436
+ : any;
1437
+
1438
+ // The query builder of `fetchGraph()` for objects of type `T` of model `M`.
1439
+ // Plain objects are turned into models.
1440
+ type FetchGraphQueryBuilder<QB extends AnyQueryBuilder, M, T, E, Kind extends 'one' | 'many'> =
1441
+ WithGraph<T extends Model ? T : M, M, E> extends infer I
1442
+ ? RebindQueryBuilder<
1443
+ QB,
1444
+ ModelType<QB>,
1445
+ Kind extends 'one' ? I : I[],
1446
+ ParseRelationExpression<E> extends GraphNode
1447
+ ? QueryBuilderItemState<I>
1448
+ : OpaqueItemState<I>
1449
+ >
1450
+ : never;
1451
+
1452
+ // The query builder `QB` with result items of type `I`.
1453
+ type ItemQueryBuilder<QB extends AnyQueryBuilder, I> = RebindQueryBuilder<
1454
+ QB,
1455
+ ModelType<QB>,
1456
+ ReplaceResultItem<ResultType<QB>, I>,
1457
+ QB['~state'] extends { opaque: true } ? OpaqueItemState<I> : QueryBuilderItemState<I>
1458
+ >;
1459
+
1460
+ // The query builder `QB` after a modifier that returned `Ret`.
1461
+ type ModifiedQueryBuilder<QB extends AnyQueryBuilder, Ret> = Ret extends {
1462
+ '~state': infer S extends QueryBuilderState;
1463
+ }
1464
+ ? IsAnyType<S['item']> extends true
1465
+ ? OpaqueQueryBuilder<QB>
1466
+ : S extends { opaque: true }
1467
+ ? OpaqueQueryBuilder<
1468
+ ItemQueryBuilder<QB, MergeLoaded<QB['~state']['item'], GraphModel<QB>, S['item']>>
1469
+ >
1470
+ : ItemQueryBuilder<QB, MergeLoaded<QB['~state']['item'], GraphModel<QB>, S['item']>>
1471
+ : OpaqueQueryBuilder<QB>;
1472
+
1473
+ /**
1474
+ * If T is an array, returns the item type, otherwise returns T.
1475
+ */
1476
+ type ItemType<T> = T extends Array<unknown> ? T[number] : T;
1477
+
1478
+ /**
1479
+ * Type for keys of non-function properties of T.
1480
+ */
1481
+ type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T];
1482
+
1483
+ /**
1484
+ * Type that attempts to only select the user-defined model properties.
1485
+ */
1486
+ type DataPropertyNames<T> = Exclude<NonFunctionPropertyNames<T>, 'QueryBuilderType'>;
1487
+
1488
+ /**
1489
+ * Removes `undefined` from a type.
1490
+ */
1491
+ type Defined<T> = Exclude<T, undefined>;
1492
+
1493
+ /**
1494
+ * A Pojo version of model.
1495
+ */
1496
+ type ModelObject<T extends Model> = Pick<T, DataPropertyNames<T>>;
1497
+
1498
+ /**
1499
+ * Any object that has some of the properties of model class T match this type.
1500
+ */
1501
+ type PartialModelObject<T extends Model> = {
1502
+ [K in DataPropertyNames<T>]?: Defined<T[K]> extends Model
1503
+ ? T[K]
1504
+ : Defined<T[K]> extends Array<infer I>
1505
+ ? I extends Model
1506
+ ? I[]
1507
+ : Expression<T[K]>
1508
+ : Expression<T[K]>;
1509
+ };
1510
+
1511
+ type JsonFieldKey<T> = `${JsonColumnName<T>}:${string}`;
1512
+
1513
+ /**
1514
+ * Checks an object for `patch()`, `update()` and `merge()` that sets fields of JSON
1515
+ * columns one at a time: `patch({ 'payload:courseName': 'Physics' })`. The other keys
1516
+ * must be properties of the model. Keys that aren't allowed get the type `never`.
1517
+ */
1518
+ type CheckModelUpdate<M extends Model, U> = [Extract<keyof U, `${string}:${string}`>] extends [
1519
+ never,
1520
+ ]
1521
+ ? // Objects without field keys are checked by the plain overload, which gives better
1522
+ // errors and is cheaper for values like subqueries.
1523
+ never
1524
+ : {
1525
+ [K in keyof U]: K extends `${string}:${string}`
1526
+ ? K extends JsonFieldKey<M>
1527
+ ? U[K]
1528
+ : never
1529
+ : K extends keyof PartialModelObject<M>
1530
+ ? PartialModelObject<M>[K]
1531
+ : never;
1532
+ };
1533
+
1534
+ /**
1535
+ * Additional optional parameters that may be used in graphs.
1536
+ */
1537
+ type GraphParameters = {
1538
+ '#dbRef'?: MaybeCompositeId;
1539
+ '#ref'?: string;
1540
+ '#id'?: string;
1541
+ };
1542
+
1543
+ /**
1544
+ * Just like PartialModelObject but this is applied recursively to relations.
1545
+ */
1546
+ type PartialModelGraph<M, T = M & GraphParameters> = T extends any
1547
+ ? {
1548
+ [K in DataPropertyNames<T>]?: null extends T[K]
1549
+ ? PartialModelGraphField<NonNullable<T[K]>> | null // handle nullable BelongsToOneRelations
1550
+ : PartialModelGraphField<T[K]>;
1551
+ }
1552
+ : never;
1553
+
1554
+ type PartialModelGraphField<F> =
1555
+ Defined<F> extends Model
1556
+ ? PartialModelGraph<Defined<F>>
1557
+ : Defined<F> extends Array<infer I>
1558
+ ? I extends Model
1559
+ ? PartialModelGraph<I>[]
1560
+ : Expression<F>
1561
+ : Expression<F>;
1562
+
1563
+ /**
1564
+ * Extracts the property names (excluding relations) of a model class.
1565
+ */
1566
+ type ModelProps<T extends Model> = Exclude<
1567
+ {
1568
+ [K in ModelDataKeys<T>]-?: NonNullable<T[K]> extends Model | readonly Model[]
1569
+ ? never
1570
+ : NonNullable<T[K]> extends Array<infer I>
1571
+ ? I extends Model
1572
+ ? never
1573
+ : K
1574
+ : T[K] extends Function
1575
+ ? never
1576
+ : K;
1577
+ }[ModelDataKeys<T>],
1578
+ undefined
1579
+ >;
1580
+
1581
+ /**
1582
+ * The keys of a model, without the ones objection uses internally. They are left out
1583
+ * before looking at the property types, since `QueryBuilderType` refers back to the
1584
+ * model.
1585
+ */
1586
+ type ModelDataKeys<T> = Exclude<keyof T, 'QueryBuilderType' | `~${string}`>;
1587
+
1588
+ /**
1589
+ * Extracts the relation names of the a model class.
1590
+ */
1591
+ type ModelRelations<T extends Model> = Defined<
1592
+ {
1593
+ [K in keyof T]?: NonNullable<T[K]> extends Model | readonly Model[]
1594
+ ? K
1595
+ : NonNullable<T[K]> extends Array<infer I>
1596
+ ? I extends Model
1597
+ ? K
1598
+ : never
1599
+ : never;
1600
+ }[keyof T]
1601
+ >;
1602
+
1603
+ /**
1604
+ * Given a model property type, returns a query builer type of
1605
+ * correct kind if the property is a model or a model array.
1606
+ */
1607
+ type RelatedQueryBuilder<T> = T extends Model
1608
+ ? // A to-one relation query returns `undefined` if there is no related model.
1609
+ MaybeSingleQueryBuilder<RowQueryBuilder<QueryBuilderType<T>, T>>
1610
+ : T extends Array<infer I>
1611
+ ? I extends Model
1612
+ ? RowQueryBuilder<QueryBuilderType<I>, I>
1613
+ : never
1614
+ : never;
1615
+
1616
+ /**
1617
+ * Just like RelatedQueryBuilder but always returns an array
1618
+ * query builder even if the property type is a model and not
1619
+ * an array of models.
1620
+ */
1621
+ type ArrayRelatedQueryBuilder<T> = T extends Model
1622
+ ? RowQueryBuilder<QueryBuilderType<T>, T>
1623
+ : T extends Array<infer I>
1624
+ ? I extends Model
1625
+ ? RowQueryBuilder<QueryBuilderType<I>, I>
1626
+ : never
1627
+ : never;
1628
+
1629
+ /**
1630
+ * Gets the query builder type for a model type.
1631
+ */
1632
+ type QueryBuilderType<T extends { QueryBuilderType: any }> = T['QueryBuilderType'];
1633
+
1634
+ /**
1635
+ * Gets the model type from a query builder type.
1636
+ */
1637
+ type ModelType<T extends { ModelType: any }> = T['ModelType'];
1638
+
1639
+ /**
1640
+ * Gets the result type from a query builder type.
1641
+ */
1642
+ type ResultType<T extends { ResultType: any }> = T['ResultType'];
1643
+
1644
+ type IsAnyType<T> = 0 extends 1 & T ? true : false;
1645
+
1646
+ /**
1647
+ * The type of the items of a query result `R`. For example `Person` for
1648
+ * `Person[]`, `Person | undefined` and `Page<Person>`. For results without
1649
+ * items (`number`), returns `M`.
1650
+ */
1651
+ type ResultItemOf<R, M = unknown> =
1652
+ IsAnyType<R> extends true
1653
+ ? any
1654
+ : [R] extends [number]
1655
+ ? M
1656
+ : [R] extends [readonly (infer I)[]]
1657
+ ? I
1658
+ : [R] extends [Page<infer I>]
1659
+ ? I
1660
+ : Exclude<R, undefined>;
1661
+
1662
+ type IsSingleResult<R> =
1663
+ IsAnyType<R> extends true
1664
+ ? false
1665
+ : [R] extends [number]
1666
+ ? false
1667
+ : [R] extends [readonly any[]]
1668
+ ? false
1669
+ : [R] extends [Page<any>]
1670
+ ? false
1671
+ : true;
1672
+
1673
+ /**
1674
+ * The type-level state of a query builder. It's kept when the result kind
1675
+ * changes (for example when `first()` or `patch()` is called).
1676
+ */
1677
+ interface QueryBuilderState {
1678
+ // The type of the result items, for example `Person` when the result is
1679
+ // `Person[]`, `Person | undefined` or `Page<Person>`.
1680
+ item: unknown;
1681
+ // `true` when something ran that may have loaded relations the types can't
1682
+ // see, like a modifier that doesn't return the query builder. Only opaque
1683
+ // states have it, so that opaque query builders can be assigned to
1684
+ // variables of the others.
1685
+ opaque?: true;
1686
+ // `true` after `castTo(ModelClass)`.
1687
+ cast?: true;
1688
+ }
1689
+
1690
+ type QueryBuilderItemState<T> = { item: T };
1691
+
1692
+ type OpaqueItemState<T> = { item: T; opaque: true };
1693
+
1694
+ // The state after `castTo(ModelClass)`.
1695
+ type CastItemState<T> = { item: T; opaque: true; cast: true };
1696
+
1697
+ /**
1698
+ * A model as a query returns it: without the relations the query didn't load.
1699
+ * Loaded relations are added by `withGraphFetched()` and the other graph methods.
1700
+ *
1701
+ * Models whose rows couldn't be used where the model is expected keep their
1702
+ * relations: models that declare a relation as required (`pets!: Pet[]`
1703
+ * instead of `pets?: Pet[]`), and models with `private` or `protected` members.
1704
+ */
1705
+ export type ModelRow<M> = [RequiredRelationKeys<M>] extends [never]
1706
+ ? Row<M> extends M
1707
+ ? Row<M>
1708
+ : M
1709
+ : M;
1710
+
1711
+ type RequiredRelationKeys<M> = {
1712
+ [K in RelationKeys<M>]: {} extends Pick<M, K> ? never : K;
1713
+ }[RelationKeys<M>];
1714
+
1715
+ type Row<M> = { [K in keyof M as K extends RelationKeys<M> ? never : K]: M[K] };
1716
+
1717
+ // The keys of the relation properties of `M`. Unlike `ModelRelations`, this
1718
+ // ignores properties typed as `any`.
1719
+ type RelationKeys<M> = {
1720
+ [K in keyof M]-?: IsAnyType<M[K]> extends true
1721
+ ? never
1722
+ : NonNullable<M[K]> extends ModelLike | readonly ModelLike[]
1723
+ ? K
1724
+ : never;
1725
+ }[keyof M];
1726
+
1727
+ // Checking for a few members of `Model` is much cheaper than comparing with
1728
+ // `Model`, which compares the types of all its methods.
1729
+ type ModelLike = { $modelClass: unknown; $relatedQuery: unknown; $fetchGraph: unknown };
1730
+
1731
+ // Adds back the relations of `M` that `I` doesn't have, as optional
1732
+ // properties, for results that may contain relations the types can't see.
1733
+ // A row without loaded relations becomes the model itself.
1734
+ type MakeOpaque<I, M> = [Exclude<RelationKeys<M>, keyof I>] extends [never]
1735
+ ? I
1736
+ : [Exclude<keyof I, keyof M> | Extract<keyof I, RelationKeys<M>>] extends [never]
1737
+ ? M
1738
+ : I & { [K in Exclude<RelationKeys<M>, keyof I>]?: M[K] };
1739
+
1740
+ // The query builder `QB` after something ran that may have loaded relations
1741
+ // the types can't see.
1742
+ type OpaqueQueryBuilder<QB extends AnyQueryBuilder> = QB['~state'] extends { opaque: true }
1743
+ ? QB
1744
+ : RebindQueryBuilder<
1745
+ QB,
1746
+ ModelType<QB>,
1747
+ ReplaceResultItem<
1748
+ ResultType<QB>,
1749
+ MakeOpaque<QB['~state']['item'], RelationsModel<ModelType<QB>>>
1750
+ >,
1751
+ OpaqueItemState<MakeOpaque<QB['~state']['item'], RelationsModel<ModelType<QB>>>>
1752
+ >;
1753
+
1754
+ // The query builder `QB` for model `M` with rows as the result items.
1755
+ type RowQueryBuilder<
1756
+ QB extends AnyQueryBuilder,
1757
+ M extends Model,
1758
+ I = ModelRow<M>,
1759
+ > = RebindQueryBuilder<QB, M, I[], QueryBuilderItemState<I>>;
1760
+
1761
+ /**
1762
+ * The state of a query builder whose result type `R` was given explicitly,
1763
+ * as in `QueryBuilder<Person, Person | undefined>`.
1764
+ */
1765
+ // This is a conditional type so that it resolves to `QueryBuilderItemState`,
1766
+ // whose instances only differ by the item type. This makes for example
1767
+ // `DefaultQueryBuilderState<M, M[]>` and `DefaultQueryBuilderState<M, M | undefined>`
1768
+ // the same type.
1769
+ type DefaultQueryBuilderState<M, R> = [R] extends [never]
1770
+ ? QueryBuilderItemState<never>
1771
+ : QueryBuilderItemState<ResultItemOf<R, M>>;
1772
+
1773
+ /**
1774
+ * Returns the query builder type `QB` (including custom query builder
1775
+ * subclasses) for model `M`, result `R` and state `S`.
1776
+ */
1777
+ type RebindQueryBuilder<
1778
+ QB extends AnyQueryBuilder,
1779
+ M extends Model,
1780
+ R,
1781
+ S extends QueryBuilderState = QB['~S'],
1782
+ > = (QB['~rebind'] & { '~args': [M, R, S] })['~rebind'];
1783
+
1784
+ /**
1785
+ * Gets the single item query builder type for a query builder.
1786
+ */
1787
+ type SingleQueryBuilder<QB extends AnyQueryBuilder> = QB['~one'];
1788
+
1789
+ /**
1790
+ * Gets the single or undefined item query builder type for a query builder.
1791
+ */
1792
+ type MaybeSingleQueryBuilder<QB extends AnyQueryBuilder> = QB['~maybe'];
1793
+
1794
+ /**
1795
+ * Gets the multi-item query builder type for a query builder.
1796
+ */
1797
+ type ArrayQueryBuilder<QB extends AnyQueryBuilder> = QB['~many'];
1798
+
1799
+ /**
1800
+ * Gets the number query builder type for a query builder.
1801
+ */
1802
+ type NumberQueryBuilder<QB extends AnyQueryBuilder> = QB['~count'];
1803
+
1804
+ /**
1805
+ * Gets the page query builder type for a query builder.
1806
+ */
1807
+ type PageQueryBuilder<QB extends AnyQueryBuilder> = QB['~page'];
1808
+
1809
+ // `runAfter` replaces the result with whatever the callback returns, also
1810
+ // when it returns nothing.
1811
+ type RunAfterResult<T> = [Awaited<T>] extends [void] ? undefined : Awaited<T>;
1812
+
1813
+ // Replaces the item type of result `R` with `I`, keeping the result kind.
1814
+ type ReplaceResultItem<R, I> =
1815
+ IsAnyType<R> extends true ? any : [R] extends [never] ? never : ReplaceResultMember<R, I>;
1816
+
1817
+ // Each member of a union like `Person[] | Person | number | undefined`.
1818
+ type ReplaceResultMember<R, I> = R extends number
1819
+ ? number
1820
+ : R extends readonly any[]
1821
+ ? I[]
1822
+ : R extends Page<any>
1823
+ ? Page<I>
1824
+ : R extends undefined | null
1825
+ ? R
1826
+ : I;
1827
+
1828
+ /**
1829
+ * The query builder type of the static `query()` method of model class `MC`.
1830
+ * This is based on the static `QueryBuilder` property, which decides the
1831
+ * query builder class at runtime.
1832
+ */
1833
+ // `I` is the type of the rows.
1834
+ type ModelClassQueryBuilder<MC, M extends Model, I = ModelRow<M>> = MC extends {
1835
+ QueryBuilder: { prototype: infer QB };
1836
+ }
1837
+ ? keyof QueryBuilderType<M> extends keyof QB
1838
+ ? // The static `QueryBuilder` creates query builders of the declared
1839
+ // `QueryBuilderType` (only the keys are compared, which is much faster).
1840
+ RowQueryBuilder<QueryBuilderType<M>, M, I>
1841
+ : // `QueryBuilderType` was declared, but the static `QueryBuilder` creates
1842
+ // some other query builders. Trust the class that is used at runtime.
1843
+ InitialQueryBuilder<QB, M, I>
1844
+ : RowQueryBuilder<QueryBuilderType<M>, M, I>;
1845
+
1846
+ type InitialQueryBuilder<QB, M extends Model, I> = QB extends { '~rebind': any }
1847
+ ? (QB['~rebind'] & { '~args': [M, I[], QueryBuilderItemState<I>] })['~rebind']
1848
+ : QB;
1849
+
1850
+ interface ForClassMethod {
1851
+ <M extends Model>(modelClass: ModelConstructor<M>): RowQueryBuilder<QueryBuilderType<M>, M>;
1852
+ }
1853
+
1854
+ /**
1855
+ * https://vincit.github.io/objection.js/api/types/#type-fieldexpression
1856
+ */
1857
+ type FieldExpression = string;
1858
+
1859
+ type JsonObjectOrFieldExpression = object | object[] | FieldExpression;
1860
+
1861
+ type Selection<QB extends AnyQueryBuilder> = ColumnRef | AnyQueryBuilder | CallbackVoid<QB>;
1862
+
1863
+ interface SelectMethod<QB extends AnyQueryBuilder> {
1864
+ // These must come first so that we get autocomplete.
1865
+ <QBP extends QB>(...columns: ModelProps<ModelType<QBP>>[]): QB;
1866
+ <QBP extends QB>(columns: ModelProps<ModelType<QBP>>[]): QB;
1867
+
1868
+ <QBP extends QB>(...columns: Selection<QBP>[]): QB;
1869
+ <QBP extends QB>(columns: Selection<QBP>[]): QB;
1870
+
1871
+ // Allows things like `select(1)`, not sure if we should be more specific here?
1872
+ <QBP extends QB>(...args: any[]): QB;
1873
+ }
1874
+
1875
+ interface AsMethod<QB extends AnyQueryBuilder> {
1876
+ (alias: string): QB;
1877
+ }
1878
+
1879
+ interface FromMethod<QB extends AnyQueryBuilder> {
1880
+ (table: TableRef<QB>): QB;
1881
+ }
1882
+
1883
+ interface FromRawMethod<QB extends AnyQueryBuilder> extends RawInterface<QB> {}
1884
+
1885
+ interface JsonExtraction {
1886
+ column: string | Raw | Knex.QueryBuilder;
1887
+ path: string;
1888
+ alias?: string;
1889
+ singleValue?: boolean;
1890
+ }
1891
+
1892
+ interface JsonExtract<QB extends AnyQueryBuilder> {
1893
+ // These must come first so that we get autocomplete.
1894
+ <QBP extends QB>(
1895
+ column: ModelProps<ModelType<QBP>>,
1896
+ path: string,
1897
+ alias?: string,
1898
+ singleValue?: boolean,
1899
+ ): QB;
1900
+
1901
+ (column: ColumnRef, path: string, alias?: string, singleValue?: boolean): QB;
1902
+ (column: JsonExtraction[] | any[][], singleValue?: boolean): QB;
1903
+ }
1904
+
1905
+ interface JsonSet<QB extends AnyQueryBuilder> {
1906
+ // These must come first so that we get autocomplete.
1907
+ <QBP extends QB>(
1908
+ column: ModelProps<ModelType<QBP>>,
1909
+ path: string,
1910
+ value: any,
1911
+ alias?: string,
1912
+ ): QB;
1913
+
1914
+ (column: ColumnRef, path: string, value: any, alias?: string): QB;
1915
+ }
1916
+
1917
+ interface JsonInsert<QB extends AnyQueryBuilder> {
1918
+ // These must come first so that we get autocomplete.
1919
+ <QBP extends QB>(
1920
+ column: ModelProps<ModelType<QBP>>,
1921
+ path: string,
1922
+ value: any,
1923
+ alias?: string,
1924
+ ): QB;
1925
+
1926
+ (column: ColumnRef, path: string, value: any, alias?: string): QB;
1927
+ }
1928
+
1929
+ interface JsonRemove<QB extends AnyQueryBuilder> {
1930
+ // These must come first so that we get autocomplete.
1931
+ <QBP extends QB>(column: ModelProps<ModelType<QBP>>, path: string, alias?: string): QB;
1932
+
1933
+ (column: ColumnRef, path: string, alias?: string): QB;
1934
+ }
1935
+
1936
+ interface WhereMethod<QB extends AnyQueryBuilder> {
1937
+ // These must come first so that we get autocomplete.
1938
+ <QBP extends QB>(
1939
+ col: ModelProps<ModelType<QBP>>,
1940
+ op: Operator,
1941
+ expr: Expression<PrimitiveValue>,
1942
+ ): QB;
1943
+
1944
+ <QBP extends QB>(col: ModelProps<ModelType<QBP>>, expr: Expression<PrimitiveValue>): QB;
1945
+
1946
+ (col: ColumnRef, op: Operator, expr: Expression<PrimitiveValue>): QB;
1947
+ (col: ColumnRef, expr: Expression<PrimitiveValue>): QB;
1948
+
1949
+ (condition: boolean): QB;
1950
+ (cb: CallbackVoid<QB>): QB;
1951
+ (raw: Raw): QB;
1952
+ <QBA extends AnyQueryBuilder>(qb: QBA): QB;
1953
+
1954
+ (obj: PartialModelObject<ModelType<QB>>): QB;
1955
+ // We must allow any keys in the object. The previous type
1956
+ // is kind of useless, but maybe one day vscode and other
1957
+ // tools can autocomplete using it.
1958
+ (obj: object): QB;
1959
+ }
1960
+
1961
+ interface WhereRawMethod<QB extends AnyQueryBuilder> extends RawInterface<QB> {}
1962
+
1963
+ interface WhereWrappedMethod<QB extends AnyQueryBuilder> {
1964
+ (cb: CallbackVoid<QB>): QB;
1965
+ }
1966
+
1967
+ interface WhereExistsMethod<QB extends AnyQueryBuilder> {
1968
+ (cb: CallbackVoid<QB>): QB;
1969
+ (raw: Raw): QB;
1970
+ <QBA extends AnyQueryBuilder>(qb: QBA): QB;
1971
+ }
1972
+
1973
+ interface WhereInMethod<QB extends AnyQueryBuilder> {
1974
+ // These must come first so that we get autocomplete.
1975
+ <QBP extends QB>(col: ModelProps<ModelType<QBP>>, expr: Expression<PrimitiveValue>): QB;
1976
+ <QBP extends QB>(col: ModelProps<ModelType<QBP>>, cb: CallbackVoid<QB>): QB;
1977
+ <QBP extends QB>(col: ModelProps<ModelType<QBP>>, qb: AnyQueryBuilder): QB;
1978
+
1979
+ (col: ColumnRef | ColumnRef[], expr: readonly Expression<PrimitiveValue>[]): QB;
1980
+ (col: ColumnRef | ColumnRef[], cb: CallbackVoid<QB>): QB;
1981
+ (col: ColumnRef | ColumnRef[], qb: AnyQueryBuilder): QB;
1982
+ }
1983
+
1984
+ interface WhereBetweenMethod<QB extends AnyQueryBuilder> {
1985
+ (column: ColumnRef, range: [Expression<PrimitiveValue>, Expression<PrimitiveValue>]): QB;
1986
+ }
1987
+
1988
+ interface WhereNullMethod<QB extends AnyQueryBuilder> {
1989
+ (column: ColumnRef): QB;
1990
+ }
1991
+
1992
+ interface WhereColumnMethod<QB extends AnyQueryBuilder> {
1993
+ // These must come first so that we get autocomplete.
1994
+ <QBP extends QB>(col1: ModelProps<ModelType<QBP>>, op: Operator, col2: ColumnRef): QB;
1995
+ <QBP extends QB>(col1: ModelProps<ModelType<QBP>>, col2: ColumnRef): QB;
1996
+
1997
+ (col1: ColumnRef, op: Operator, col2: ColumnRef): QB;
1998
+ (col1: ColumnRef, col2: ColumnRef): QB;
1999
+ }
2000
+
2001
+ interface WhereJsonObject<QB extends AnyQueryBuilder> {
2002
+ // These must come first so that we get autocomplete.
2003
+ <QBP extends QB>(col: ModelProps<ModelType<QBP>>, value: any): QB;
2004
+
2005
+ (col: ColumnRef, value: any): QB;
2006
+ }
2007
+
2008
+ interface WhereJsonPath<QB extends AnyQueryBuilder> {
2009
+ // These must come first so that we get autocomplete.
2010
+ <QBP extends QB>(
2011
+ col: ModelProps<ModelType<QBP>>,
2012
+ jsonPath: string,
2013
+ operator: string,
2014
+ value: any,
2015
+ ): QB;
2016
+
2017
+ (col: ColumnRef, jsonPath: string, operator: string, value: any): QB;
2018
+ }
2019
+
2020
+ interface WhereJsonMethod<QB extends AnyQueryBuilder> {
2021
+ (
2022
+ fieldExpression: FieldExpression,
2023
+ jsonObjectOrFieldExpression: JsonObjectOrFieldExpression,
2024
+ ): QB;
2025
+ }
2026
+
2027
+ interface WhereFieldExpressionMethod<QB extends AnyQueryBuilder> {
2028
+ (fieldExpression: FieldExpression): QB;
2029
+ }
2030
+
2031
+ interface WhereJsonExpressionMethod<QB extends AnyQueryBuilder> {
2032
+ (fieldExpression: FieldExpression, keys: string | string[]): QB;
2033
+ }
2034
+
2035
+ interface WhereJsonField<QB extends AnyQueryBuilder> {
2036
+ (
2037
+ fieldExpression: FieldExpression,
2038
+ operator: string,
2039
+ value: boolean | number | string | null,
2040
+ ): QB;
2041
+ }
2042
+
2043
+ interface WhereCompositeMethod<QB extends AnyQueryBuilder> {
2044
+ (column: ColumnRef[], op: Operator, expr: readonly Expression<PrimitiveValue>[]): QB;
2045
+ (column: ColumnRef, expr: Expression<PrimitiveValue>): QB;
2046
+ (column: ColumnRef, op: Operator, expr: Expression<PrimitiveValue>): QB;
2047
+ (column: ColumnRef[], expr: readonly Expression<PrimitiveValue>[]): QB;
2048
+ (column: ColumnRef[], qb: AnyQueryBuilder): QB;
2049
+ }
2050
+
2051
+ interface WhereInCompositeMethod<QB extends AnyQueryBuilder> {
2052
+ (column: ColumnRef, expr: readonly Expression<PrimitiveValue>[]): QB;
2053
+ (column: ColumnRef, qb: AnyQueryBuilder): QB;
2054
+ (column: ColumnRef[], expr: readonly Expression<PrimitiveValue>[][]): QB;
2055
+ (column: ColumnRef[], qb: AnyQueryBuilder): QB;
2056
+ }
2057
+
2058
+ type QBOrCallback<QB extends AnyQueryBuilder> = AnyQueryBuilder | CallbackVoid<QB>;
2059
+
2060
+ interface BaseSetOperations<QB extends AnyQueryBuilder> {
2061
+ (callbackOrBuilder: QBOrCallback<QB>, wrap?: boolean): QB;
2062
+ (callbacksOrBuilders: QBOrCallback<QB>[], wrap?: boolean): QB;
2063
+ }
2064
+
2065
+ interface SetOperationsMethod<QB extends AnyQueryBuilder> extends BaseSetOperations<QB> {
2066
+ (...callbacksOrBuilders: QBOrCallback<QB>[]): QB;
2067
+ }
2068
+
2069
+ interface UnionMethod<QB extends AnyQueryBuilder> extends BaseSetOperations<QB> {
2070
+ (arg1: QBOrCallback<QB>, wrap?: boolean): QB;
2071
+ (arg1: QBOrCallback<QB>, arg2: QBOrCallback<QB>, wrap?: boolean): QB;
2072
+ (arg1: QBOrCallback<QB>, arg2: QBOrCallback<QB>, arg3: QBOrCallback<QB>, wrap?: boolean): QB;
2073
+ (
2074
+ arg1: QBOrCallback<QB>,
2075
+ arg2: QBOrCallback<QB>,
2076
+ arg3: QBOrCallback<QB>,
2077
+ arg4: QBOrCallback<QB>,
2078
+ wrap?: boolean,
2079
+ ): QB;
2080
+ (
2081
+ arg1: QBOrCallback<QB>,
2082
+ arg2: QBOrCallback<QB>,
2083
+ arg3: QBOrCallback<QB>,
2084
+ arg4: QBOrCallback<QB>,
2085
+ arg5: QBOrCallback<QB>,
2086
+ wrap?: boolean,
2087
+ ): QB;
2088
+ (
2089
+ arg1: QBOrCallback<QB>,
2090
+ arg2: QBOrCallback<QB>,
2091
+ arg3: QBOrCallback<QB>,
2092
+ arg4: QBOrCallback<QB>,
2093
+ arg5: QBOrCallback<QB>,
2094
+ arg6: QBOrCallback<QB>,
2095
+ wrap?: boolean,
2096
+ ): QB;
2097
+ (
2098
+ arg1: QBOrCallback<QB>,
2099
+ arg2: QBOrCallback<QB>,
2100
+ arg3: QBOrCallback<QB>,
2101
+ arg4: QBOrCallback<QB>,
2102
+ arg5: QBOrCallback<QB>,
2103
+ arg6: QBOrCallback<QB>,
2104
+ arg7: QBOrCallback<QB>,
2105
+ wrap?: boolean,
2106
+ ): QB;
2107
+ }
2108
+
2109
+ interface WithMethod<QB extends AnyQueryBuilder> {
2110
+ (alias: string, expr: CallbackVoid<QB> | AnyQueryBuilder | Raw): QB;
2111
+ }
2112
+
2113
+ interface JoinRelatedOptions {
2114
+ alias?: string | boolean;
2115
+ aliases?: Record<string, string>;
2116
+ }
2117
+
2118
+ interface JoinRelatedMethod<QB extends AnyQueryBuilder> {
2119
+ <const E extends RelationExpression<ModelType<QB>>>(
2120
+ expr: CheckRelationExpression<GraphModel<QB>, E, ChecksModifierNames<QB>>,
2121
+ opt?: JoinRelatedOptions,
2122
+ ): QB;
2123
+ }
2124
+
2125
+ interface JoinMethod<QB extends AnyQueryBuilder> {
2126
+ (table: TableRef<QB>, leftCol: ColumnRef, op: Operator, rightCol: ColumnRef): QB;
2127
+ (table: TableRef<QB>, leftCol: ColumnRef, rightCol: ColumnRef): QB;
2128
+ (table: TableRef<QB>, cb: CallbackVoid<JoinBuilder>): QB;
2129
+ (table: TableRef<QB>, raw: Raw): QB;
2130
+ (raw: Raw): QB;
2131
+ }
2132
+
2133
+ interface CrossJoinMethod<QB extends AnyQueryBuilder> extends JoinMethod<QB> {
2134
+ (table: TableRef<QB>): QB;
2135
+ }
2136
+
2137
+ type JoinValue = PrimitiveValue | Raw | ReferenceBuilder | ValueBuilder | AnyQueryBuilder;
2138
+
2139
+ interface JoinOnMethod {
2140
+ (column1: ColumnRef, column2: ColumnRef): JoinBuilder;
2141
+ (column1: ColumnRef, operator: Operator, column2: ColumnRef): JoinBuilder;
2142
+ (columns: { [column: string]: ColumnRef }): JoinBuilder;
2143
+ (callback: CallbackVoid<JoinBuilder>): JoinBuilder;
2144
+ (raw: Raw): JoinBuilder;
2145
+ }
2146
+
2147
+ interface JoinOnValMethod {
2148
+ (column: ColumnRef, value: JoinValue): JoinBuilder;
2149
+ (column: ColumnRef, operator: Operator, value: JoinValue): JoinBuilder;
2150
+ }
2151
+
2152
+ interface JoinOnInMethod {
2153
+ (column: ColumnRef, values: readonly JoinValue[] | Raw | AnyQueryBuilder): JoinBuilder;
2154
+ }
2155
+
2156
+ interface JoinOnNullMethod {
2157
+ (column: ColumnRef): JoinBuilder;
2158
+ }
2159
+
2160
+ interface JoinOnExistsMethod {
2161
+ (query: CallbackVoid<AnyQueryBuilder> | AnyQueryBuilder): JoinBuilder;
2162
+ }
2163
+
2164
+ interface JoinOnBetweenMethod {
2165
+ (column: ColumnRef, range: readonly [JoinValue, JoinValue]): JoinBuilder;
2166
+ }
2167
+
2168
+ interface JoinOnJsonPathEqualsMethod {
2169
+ (
2170
+ columnFirst: ColumnRef,
2171
+ jsonPathFirst: string,
2172
+ columnSecond: ColumnRef,
2173
+ jsonPathSecond: string,
2174
+ ): JoinBuilder;
2175
+ }
2176
+
2177
+ /**
2178
+ * The builder passed to join callbacks. Unlike knex's `JoinClause`, every column can
2179
+ * be a `ref()` or `Model.ref()`.
2180
+ */
2181
+ export interface JoinBuilder {
2182
+ on: JoinOnMethod;
2183
+ andOn: JoinOnMethod;
2184
+ orOn: JoinOnMethod;
2185
+
2186
+ onVal: JoinOnValMethod;
2187
+ andOnVal: JoinOnValMethod;
2188
+ orOnVal: JoinOnValMethod;
2189
+
2190
+ onIn: JoinOnInMethod;
2191
+ andOnIn: JoinOnInMethod;
2192
+ orOnIn: JoinOnInMethod;
2193
+ onNotIn: JoinOnInMethod;
2194
+ andOnNotIn: JoinOnInMethod;
2195
+ orOnNotIn: JoinOnInMethod;
2196
+
2197
+ onNull: JoinOnNullMethod;
2198
+ andOnNull: JoinOnNullMethod;
2199
+ orOnNull: JoinOnNullMethod;
2200
+ onNotNull: JoinOnNullMethod;
2201
+ andOnNotNull: JoinOnNullMethod;
2202
+ orOnNotNull: JoinOnNullMethod;
2203
+
2204
+ onExists: JoinOnExistsMethod;
2205
+ andOnExists: JoinOnExistsMethod;
2206
+ orOnExists: JoinOnExistsMethod;
2207
+ onNotExists: JoinOnExistsMethod;
2208
+ andOnNotExists: JoinOnExistsMethod;
2209
+ orOnNotExists: JoinOnExistsMethod;
2210
+
2211
+ onBetween: JoinOnBetweenMethod;
2212
+ andOnBetween: JoinOnBetweenMethod;
2213
+ orOnBetween: JoinOnBetweenMethod;
2214
+ onNotBetween: JoinOnBetweenMethod;
2215
+ andOnNotBetween: JoinOnBetweenMethod;
2216
+ orOnNotBetween: JoinOnBetweenMethod;
2217
+
2218
+ onJsonPathEquals: JoinOnJsonPathEqualsMethod;
2219
+ andOnJsonPathEquals: JoinOnJsonPathEqualsMethod;
2220
+ orOnJsonPathEquals: JoinOnJsonPathEqualsMethod;
2221
+
2222
+ using(columns: string | readonly string[] | Raw | { [key: string]: string | Raw }): JoinBuilder;
2223
+ type(type: string): JoinBuilder;
2224
+ }
2225
+
2226
+ interface JoinRawMethod<QB extends AnyQueryBuilder> extends RawInterface<QB> {}
2227
+
2228
+ interface IncrementDecrementMethod<QB extends AnyQueryBuilder> {
2229
+ (column: string, amount?: number): QB;
2230
+ }
2231
+
2232
+ interface AggregateMethod<QB extends AnyQueryBuilder> {
2233
+ (column: ColumnRef): QB;
2234
+ }
2235
+
2236
+ interface CountMethod<QB extends AnyQueryBuilder> {
2237
+ (column?: ColumnRef, options?: { as: string }): QB;
2238
+ (aliasToColumnDict: { [alias: string]: string | string[] }): QB;
2239
+ (...columns: ColumnRef[]): QB;
2240
+ }
2241
+
2242
+ interface GroupByMethod<QB extends AnyQueryBuilder> {
2243
+ (...columns: ColumnRef[]): QB;
2244
+ (columns: ColumnRef[]): QB;
2245
+ }
2246
+
2247
+ interface OrderByDescriptor {
2248
+ column: ColumnRef;
2249
+ order?: OrderByDirection;
2250
+ nulls?: OrderByNulls;
2251
+ }
2252
+
2253
+ type ColumnRefOrOrderByDescriptor = ColumnRef | OrderByDescriptor;
2254
+
2255
+ interface OrderByMethod<QB extends AnyQueryBuilder> {
2256
+ (column: ColumnRef, order?: OrderByDirection, nulls?: OrderByNulls): QB;
2257
+ (columns: ColumnRefOrOrderByDescriptor[]): QB;
2258
+ }
2259
+
2260
+ interface OrderByRawMethod<QB extends AnyQueryBuilder> extends RawInterface<QB> {}
2261
+
2262
+ interface FirstMethod {
2263
+ <QB extends AnyQueryBuilder>(
2264
+ this: QB,
2265
+ ): [ResultType<QB>] extends [readonly any[]] ? MaybeSingleQueryBuilder<QB> : QB;
2266
+ }
2267
+
2268
+ type ForIdValue = MaybeCompositeId | AnyQueryBuilder;
2269
+
2270
+ interface WithGraphMethod<QB extends AnyQueryBuilder> {
2271
+ <const E extends RelationExpression<ModelType<QB>>>(
2272
+ expr: CheckRelationExpression<GraphModel<QB>, E, ChecksModifierNames<QB>>,
2273
+ options?: GraphOptions,
2274
+ ): WithGraphQueryBuilder<QB, E>;
2275
+ }
2276
+
2277
+ // The model whose relations the graph methods of `QB` use, or `any` if they're
2278
+ // not known.
2279
+ type GraphModel<QB extends AnyQueryBuilder> = QB['~state'] extends { cast: true }
2280
+ ? any
2281
+ : RelationsModel<ModelType<QB>>;
2282
+
2283
+ // The model with the relations of `M`. Generic code like
2284
+ // `<M extends Model>(query: QueryBuilder<M, M[]>)` can infer a row type as the
2285
+ // model type, but rows still have the `QueryBuilderType` of their model.
2286
+ type RelationsModel<M> =
2287
+ IsAnyType<M> extends true
2288
+ ? any
2289
+ : M extends { QueryBuilderType: { ModelType: infer RM } }
2290
+ ? IsAnyType<RM> extends true
2291
+ ? M
2292
+ : RM
2293
+ : M;
2294
+
2295
+ interface AllowGraphMethod<QB extends AnyQueryBuilder> {
2296
+ <const E extends RelationExpression<ModelType<QB>>>(
2297
+ expr: CheckRelationExpression<GraphModel<QB>, E, ChecksModifierNames<QB>>,
2298
+ ): QB;
2299
+ }
2300
+
2301
+ interface IdentityMethod<QB extends AnyQueryBuilder> {
2302
+ (): QB;
2303
+ }
2304
+
2305
+ interface OneArgMethod<T, QB extends AnyQueryBuilder> {
2306
+ (arg: T): QB;
2307
+ }
2308
+
2309
+ interface StringReturningMethod {
2310
+ (): string;
2311
+ }
2312
+
2313
+ interface BooleanReturningMethod {
2314
+ (): boolean;
2315
+ }
2316
+
2317
+ interface HasMethod {
2318
+ (selector: string | RegExp): boolean;
2319
+ }
2320
+
2321
+ interface ClearMethod<QB extends AnyQueryBuilder> {
2322
+ (selector: string | RegExp): QB;
2323
+ }
2324
+
2325
+ interface ColumnInfoMethod<QB extends AnyQueryBuilder> {
2326
+ (): Promise<Knex.ColumnInfo>;
2327
+ }
2328
+
2329
+ interface TableRefForMethod {
2330
+ (modelClass: ModelClass<Model> | typeof Model): string;
2331
+ }
2332
+
2333
+ interface AliasForMethod<QB extends AnyQueryBuilder> {
2334
+ (modelClassOrTableName: string | AnyModelConstructor, alias: string): QB;
2335
+ }
2336
+
2337
+ interface ModelClassMethod<M extends Model> {
2338
+ (): ModelClass<M>;
2339
+ }
2340
+
2341
+ interface ReturningMethod {
2342
+ <QB extends AnyQueryBuilder>(
2343
+ this: QB,
2344
+ column: string | Raw | (string | Raw)[],
2345
+ ): [ResultType<QB>] extends [number] ? ArrayQueryBuilder<QB> : QB;
2346
+ }
2347
+
2348
+ interface TimeoutOptions {
2349
+ cancel: boolean;
2350
+ }
2351
+
2352
+ interface TimeoutMethod<QB extends AnyQueryBuilder> {
2353
+ (ms: number, options?: TimeoutOptions): QB;
2354
+ }
2355
+
2356
+ export interface Page<T> {
2357
+ total: number;
2358
+ results: T[];
2359
+ }
2360
+
2361
+ interface RunBeforeCallback<QB extends AnyQueryBuilder> {
2362
+ (this: QB, result: any, query: QB): any;
2363
+ }
2364
+
2365
+ interface RunBeforeMethod<QB extends AnyQueryBuilder> {
2366
+ (cb: RunBeforeCallback<QB>): QB;
2367
+ }
2368
+
2369
+ interface RunAfterCallback<QB extends AnyQueryBuilder, T = unknown> {
2370
+ (this: QB, result: ResultType<QB>, query: QB): T;
2371
+ }
2372
+
2373
+ interface RunAfterMethod<QB extends AnyQueryBuilder> {
2374
+ // The callback's return value replaces the result of the query.
2375
+ <T>(
2376
+ cb: RunAfterCallback<QB, T>,
2377
+ ): RebindQueryBuilder<
2378
+ QB,
2379
+ ModelType<QB>,
2380
+ RunAfterResult<T>,
2381
+ QueryBuilderItemState<ResultItemOf<RunAfterResult<T>, ModelType<QB>>>
2382
+ >;
2383
+ }
2384
+
2385
+ interface OnBuildMethod<QB extends AnyQueryBuilder> {
2386
+ (cb: CallbackVoid<QB>): QB;
2387
+ }
2388
+
2389
+ interface OnBuildKnexCallback<QB extends AnyQueryBuilder> {
2390
+ (this: QB, knexQuery: Knex.QueryBuilder, query: QB): void;
2391
+ }
2392
+
2393
+ interface OnBuildKnexMethod<QB extends AnyQueryBuilder> {
2394
+ (cb: OnBuildKnexCallback<QB>): QB;
2395
+ }
2396
+
2397
+ interface OnErrorCallback<QB extends AnyQueryBuilder> {
2398
+ (this: QB, error: Error, query: QB): any;
2399
+ }
2400
+
2401
+ interface OnErrorMethod<QB extends AnyQueryBuilder> {
2402
+ (cb: OnErrorCallback<QB>): QB;
2403
+ }
2404
+
2405
+ export interface InsertGraphOptions {
2406
+ relate?: boolean | string[];
2407
+ allowRefs?: boolean;
2408
+ }
2409
+
2410
+ // The result of a graph insert or upsert has the relations of the input graph.
2411
+ interface InsertGraphMethod<M extends Model> {
2412
+ <QB extends AnyQueryBuilder>(
2413
+ this: QB,
2414
+ graph: PartialModelGraph<M>,
2415
+ options?: InsertGraphOptions,
2416
+ ): SingleQueryBuilder<OpaqueQueryBuilder<QB>>;
2417
+
2418
+ <QB extends AnyQueryBuilder>(
2419
+ this: QB,
2420
+ graph: PartialModelGraph<M>[],
2421
+ options?: InsertGraphOptions,
2422
+ ): ArrayQueryBuilder<OpaqueQueryBuilder<QB>>;
2423
+ }
2424
+
2425
+ export interface UpsertGraphOptions {
2426
+ relate?: boolean | string[];
2427
+ unrelate?: boolean | string[];
2428
+ insertMissing?: boolean | string[];
2429
+ update?: boolean | string[];
2430
+ noInsert?: boolean | string[];
2431
+ noUpdate?: boolean | string[];
2432
+ noDelete?: boolean | string[];
2433
+ noRelate?: boolean | string[];
2434
+ noUnrelate?: boolean | string[];
2435
+ allowRefs?: boolean;
2436
+ }
2437
+
2438
+ interface UpsertGraphMethod<M extends Model> {
2439
+ <QB extends AnyQueryBuilder>(
2440
+ this: QB,
2441
+ graph: PartialModelGraph<M>[],
2442
+ options?: UpsertGraphOptions,
2443
+ ): ArrayQueryBuilder<OpaqueQueryBuilder<QB>>;
2444
+
2445
+ <QB extends AnyQueryBuilder>(
2446
+ this: QB,
2447
+ graph: PartialModelGraph<M>,
2448
+ options?: UpsertGraphOptions,
2449
+ ): SingleQueryBuilder<OpaqueQueryBuilder<QB>>;
2450
+ }
2451
+
2452
+ interface GraphExpressionObjectMethod<QB extends AnyQueryBuilder> {
2453
+ (): any;
2454
+ }
2455
+
2456
+ export interface GraphOptions {
2457
+ minimize?: boolean;
2458
+ separator?: string;
2459
+ aliases?: { [key: string]: string };
2460
+ joinOperation?: string;
2461
+ maxBatchSize?: number;
2462
+ }
2463
+
2464
+ // The expression refers to the relations of the graph by their names, which can
2465
+ // be aliases. The modifier gets the query builder of the related model when the
2466
+ // expression is a single relation path like `'pets.toys'`.
2467
+ interface ModifyGraphMethod<QB extends AnyQueryBuilder> {
2468
+ // With the related model type given explicitly: `modifyGraph<Pet>(expr, modifier)`.
2469
+ <RM extends Model = never>(
2470
+ expr: [RM] extends [never] ? never : RelationExpression<ModelType<QB>>,
2471
+ modifier: Modifier<QueryBuilderType<RM>>,
2472
+ ): QB;
2473
+ <const E extends RelationExpression<ModelType<QB>>>(
2474
+ expr: CheckGraphPath<QB['~state']['item'], GraphModel<QB>, E>,
2475
+ modifier: Modifier<GraphPathQueryBuilder<QB['~state']['item'], GraphModel<QB>, E>>,
2476
+ ): QB;
2477
+ }
2478
+
2479
+ type CheckGraphPath<I, M, E> =
2480
+ ParseRelationExpression<E> extends infer G
2481
+ ? G extends ParseError<infer Message>
2482
+ ? Message
2483
+ : G extends GraphNode
2484
+ ? GraphPathErrors<I, M, G['children'], ''> extends infer Errors
2485
+ ? [Errors] extends [never]
2486
+ ? E
2487
+ : Errors
2488
+ : never
2489
+ : E
2490
+ : never;
2491
+
2492
+ type GraphPathErrors<I, M, Children, Path extends string> =
2493
+ IsUncheckedModel<M> extends true
2494
+ ? never
2495
+ : {
2496
+ [P in keyof Children & string]: Children[P] extends GraphNode
2497
+ ? GraphPathStep<I, M, P, Children[P]> extends infer Step
2498
+ ? [Step] extends [never]
2499
+ ? Path extends `${infer Parent}.`
2500
+ ? `Unknown relation "${P}" at "${Parent}"`
2501
+ : `Unknown relation "${P}"`
2502
+ : Step extends [infer NextI, infer RM]
2503
+ ? GraphPathErrors<NextI, RM, Children[P]['children'], `${Path}${P}.`>
2504
+ : never
2505
+ : never
2506
+ : never;
2507
+ }[keyof Children & string];
2508
+
2509
+ // The item and the model of the relation called `P` in the graph of item `I`:
2510
+ // a relation of `M`, or an alias that was loaded.
2511
+ type GraphPathStep<I, M, P, N extends GraphNode> =
2512
+ N['rel'] extends RelationNameKeys<M>
2513
+ ? [
2514
+ [PreviousRow<I, P>] extends [never]
2515
+ ? ModelRow<RelatedModel<M, N['rel']>>
2516
+ : PreviousRow<I, P>,
2517
+ RelatedModel<M, N['rel']>,
2518
+ ]
2519
+ : P extends keyof I
2520
+ ? ElementOrSelf<NonNullable<I[P]>> extends infer Row
2521
+ ? [Row, ModelOfRow<Row>]
2522
+ : never
2523
+ : never;
2524
+
2525
+ type ModelOfRow<Row> = Row extends { QueryBuilderType: { ModelType: infer RM } } ? RM : Model;
2526
+
2527
+ type GraphPathQueryBuilder<I, M, E> =
2528
+ ParseRelationExpression<E> extends infer G extends GraphNode
2529
+ ? GraphPathTarget<I, M, G['children']> extends infer Target
2530
+ ? [Target] extends [never]
2531
+ ? AnyQueryBuilder
2532
+ : Target extends [any, infer RM extends Model]
2533
+ ? RowQueryBuilder<QueryBuilderType<RM>, RM>
2534
+ : AnyQueryBuilder
2535
+ : AnyQueryBuilder
2536
+ : AnyQueryBuilder;
2537
+
2538
+ // The item and the model at the end of a single relation path.
2539
+ type GraphPathTarget<I, M, Children> = [keyof Children] extends [never]
2540
+ ? never
2541
+ : IsUnion<keyof Children> extends true
2542
+ ? never
2543
+ : {
2544
+ [P in keyof Children]: Children[P] extends GraphNode
2545
+ ? GraphPathStep<I, M, P, Children[P]> extends [infer NextI, infer RM]
2546
+ ? [keyof Children[P]['children']] extends [never]
2547
+ ? [NextI, RM]
2548
+ : GraphPathTarget<NextI, RM, Children[P]['children']>
2549
+ : never
2550
+ : never;
2551
+ }[keyof Children];
2552
+
2553
+ type IsUnion<T, U = T> = T extends any ? ([U] extends [T] ? false : true) : never;
2554
+
2555
+ interface ContextMethod<QB extends AnyQueryBuilder> {
2556
+ (context: object): QB;
2557
+ (): QueryContext;
2558
+ }
2559
+
2560
+ interface ClearContextMethod<QB extends AnyQueryBuilder> {
2561
+ (): QB;
2562
+ }
2563
+
2564
+ type ModifierArgs<F> = F extends (qb: any, ...args: infer A) => any ? A : unknown[];
2565
+
2566
+ // A modifier function written for models of type `PM` can be used with any
2567
+ // query builder for models of type `PM` regardless of the result kind. Only
2568
+ // the model type of the query builder parameter is checked.
2569
+ type CheckModifierModel<QB extends AnyQueryBuilder, F> = F extends (
2570
+ qb: infer P,
2571
+ ...args: any[]
2572
+ ) => any
2573
+ ? P extends { ModelType: infer PM }
2574
+ ? IsAnyType<P> extends true
2575
+ ? unknown
2576
+ : QB['ModelType'] extends PM
2577
+ ? unknown
2578
+ : // Modifiers for a subtype of the model, like a row type with
2579
+ // computed columns, are allowed too.
2580
+ PM extends QB['ModelType']
2581
+ ? unknown
2582
+ : { '~error': 'The modifier is for a different model than the query' }
2583
+ : unknown
2584
+ : unknown;
2585
+
2586
+ // Modifiers may load relations the types can't see, so the result may contain
2587
+ // any relation of the model.
2588
+ interface ModifyMethod<QB extends AnyQueryBuilder> {
2589
+ <Ret>(modifier: (qb: QB) => Ret): ModifiedQueryBuilder<QB, Ret>;
2590
+ <F extends (qb: any, ...args: any[]) => unknown>(
2591
+ modifier: F & CheckModifierModel<QB, F>,
2592
+ ...args: ModifierArgs<F>
2593
+ ): ModifiedQueryBuilder<QB, ReturnType<F>>;
2594
+ (modifier: object & Record<string, Expression<PrimitiveValue>>): OpaqueQueryBuilder<QB>;
2595
+ // The arguments are passed to every modifier of the list.
2596
+ <const L extends readonly (string | ((qb: any, ...args: any[]) => unknown))[]>(
2597
+ modifiers: L & CheckModifierList<QB, L>,
2598
+ ...args: unknown[]
2599
+ ): OpaqueQueryBuilder<QB>;
2600
+ // Named modifiers are checked when the model's static `modifiers` are known.
2601
+ <const N extends string>(
2602
+ modifier: N & CheckModifierName<QB, N>,
2603
+ ...args: NamedModifierArgs<QB, N>
2604
+ ): OpaqueQueryBuilder<QB>;
2605
+ }
2606
+
2607
+ // Names are checked unless the query builder is opaque: something the types
2608
+ // can't see may have added modifiers with `modifiers()`.
2609
+ type ChecksModifierNames<QB extends AnyQueryBuilder> = QB['~state'] extends { opaque: true }
2610
+ ? false
2611
+ : true;
2612
+
2613
+ type QueryModifiers<QB extends AnyQueryBuilder> =
2614
+ ChecksModifierNames<QB> extends true ? KnownModifiers<ModelType<QB>> : never;
2615
+
2616
+ type ModifierNameOf<QB extends AnyQueryBuilder> = [QueryModifiers<QB>] extends [never]
2617
+ ? string
2618
+ : keyof QueryModifiers<QB> & string;
2619
+
2620
+ type NamedModifierArgs<QB extends AnyQueryBuilder, N> = [QueryModifiers<QB>] extends [never]
2621
+ ? unknown[]
2622
+ : N extends keyof QueryModifiers<QB>
2623
+ ? ModifierArgs<QueryModifiers<QB>[N]>
2624
+ : unknown[];
2625
+
2626
+ type CheckModifierName<QB extends AnyQueryBuilder, N> =
2627
+ N extends ModifierNameOf<QB> ? unknown : { '~error': `Unknown modifier "${N & string}"` };
2628
+
2629
+ type CheckModifierList<QB extends AnyQueryBuilder, L> = {
2630
+ [I in keyof L]: L[I] extends string
2631
+ ? L[I] extends ModifierNameOf<QB>
2632
+ ? unknown
2633
+ : { '~error': `Unknown modifier "${L[I]}"` }
2634
+ : CheckModifierModel<QB, L[I]>;
2635
+ };
2636
+
2637
+ interface ModifiersMethod<QB extends AnyQueryBuilder> {
2638
+ // Named modifiers added here aren't known to the types, so they aren't checked
2639
+ // after this.
2640
+ (modifiers: Modifiers): OpaqueQueryBuilder<QB>;
2641
+ (): QB;
2642
+ }
2643
+
2644
+ export interface Pojo {
2645
+ [key: string]: any;
2646
+ }
2647
+
2648
+ export interface CatchablePromiseLike<R> extends PromiseLike<R> {
2649
+ catch<FR = never>(
2650
+ onrejected?: ((reason: any) => FR | PromiseLike<FR>) | undefined | null,
2651
+ ): Promise<R | FR>;
2652
+ }
2653
+
2654
+ export class QueryBuilder<
2655
+ M extends Model,
2656
+ R = M[],
2657
+ S extends QueryBuilderState = DefaultQueryBuilderState<M, R>,
2658
+ > implements CatchablePromiseLike<R>
2659
+ {
2660
+ static forClass: ForClassMethod;
2661
+
2662
+ /**
2663
+ * Type-only members used to compute the type of the query builder after
2664
+ * methods that change the result type, like `first()` or `patch()`.
2665
+ *
2666
+ * A custom query builder subclass only needs to redeclare `'~rebind'`:
2667
+ *
2668
+ * ```ts
2669
+ * class MyQueryBuilder<
2670
+ * M extends Model,
2671
+ * R = M[],
2672
+ * S extends QueryBuilderState = DefaultQueryBuilderState<M, R>,
2673
+ * > extends QueryBuilder<M, R, S> {
2674
+ * declare '~rebind': MyQueryBuilder<this['~M'], this['~R'], this['~S']>;
2675
+ * }
2676
+ * ```
2677
+ */
2678
+ '~args': unknown;
2679
+ '~M': this['~args'] extends [any, any, any] ? this['~args'][0] : any;
2680
+ '~R': this['~args'] extends [any, any, any] ? this['~args'][1] : any;
2681
+ '~S': this['~args'] extends [any, any, any] ? this['~args'][2] : any;
2682
+ '~rebind': QueryBuilder<this['~M'], this['~R'], this['~S']>;
2683
+
2684
+ // The query builder types for each result kind. These are members (instead
2685
+ // of type aliases) so that comparing a custom query builder to its base
2686
+ // class doesn't need to expand them.
2687
+ // The members use `this` instead of the type parameters, so that they are
2688
+ // the same when TypeScript compares two query builder types.
2689
+ '~state': S;
2690
+ '~many': RebindQueryBuilder<this, this['ModelType'], this['~state']['item'][], this['~state']>;
2691
+ '~maybe': RebindQueryBuilder<
2692
+ this,
2693
+ this['ModelType'],
2694
+ this['~state']['item'] | undefined,
2695
+ this['~state']
2696
+ >;
2697
+ '~one': RebindQueryBuilder<this, this['ModelType'], this['~state']['item'], this['~state']>;
2698
+ '~count': RebindQueryBuilder<this, this['ModelType'], number, this['~state']>;
2699
+ '~page': RebindQueryBuilder<
2700
+ this,
2701
+ this['ModelType'],
2702
+ Page<this['~state']['item']>,
2703
+ this['~state']
2704
+ >;
2705
+
2706
+ select: SelectMethod<this>;
2707
+ columns: SelectMethod<this>;
2708
+ column: SelectMethod<this>;
2709
+ distinct: SelectMethod<this>;
2710
+ distinctOn: SelectMethod<this>;
2711
+ as: AsMethod<this>;
2712
+
2713
+ from: FromMethod<this>;
2714
+ table: FromMethod<this>;
2715
+ into: FromMethod<this>;
2716
+ fromRaw: FromRawMethod<this>;
2717
+
2718
+ jsonExtract: JsonExtract<this>;
2719
+ jsonSet: JsonSet<this>;
2720
+ jsonInsert: JsonInsert<this>;
2721
+ jsonRemove: JsonRemove<this>;
2722
+
2723
+ where: WhereMethod<this>;
2724
+ andWhere: WhereMethod<this>;
2725
+ orWhere: WhereMethod<this>;
2726
+ whereNot: WhereMethod<this>;
2727
+ andWhereNot: WhereMethod<this>;
2728
+ orWhereNot: WhereMethod<this>;
2729
+ whereLike: WhereMethod<this>;
2730
+ andWhereLike: WhereMethod<this>;
2731
+ orWhereLike: WhereMethod<this>;
2732
+ whereILike: WhereMethod<this>;
2733
+ andWhereILike: WhereMethod<this>;
2734
+ orWhereILike: WhereMethod<this>;
2735
+
2736
+ /**
2737
+ * Makes the query match no rows: `where (1 = 0)`.
2738
+ */
2739
+ none(): this;
2740
+ whereRaw: WhereRawMethod<this>;
2741
+ orWhereRaw: WhereRawMethod<this>;
2742
+ andWhereRaw: WhereRawMethod<this>;
2743
+
2744
+ whereWrapped: WhereWrappedMethod<this>;
2745
+ havingWrapped: WhereWrappedMethod<this>;
2746
+
2747
+ whereExists: WhereExistsMethod<this>;
2748
+ orWhereExists: WhereExistsMethod<this>;
2749
+ whereNotExists: WhereExistsMethod<this>;
2750
+ orWhereNotExists: WhereExistsMethod<this>;
2751
+
2752
+ whereIn: WhereInMethod<this>;
2753
+ orWhereIn: WhereInMethod<this>;
2754
+ whereNotIn: WhereInMethod<this>;
2755
+ orWhereNotIn: WhereInMethod<this>;
2756
+
2757
+ whereBetween: WhereBetweenMethod<this>;
2758
+ orWhereBetween: WhereBetweenMethod<this>;
2759
+ andWhereBetween: WhereBetweenMethod<this>;
2760
+ whereNotBetween: WhereBetweenMethod<this>;
2761
+ orWhereNotBetween: WhereBetweenMethod<this>;
2762
+ andWhereNotBetween: WhereBetweenMethod<this>;
2763
+
2764
+ whereNull: WhereNullMethod<this>;
2765
+ orWhereNull: WhereNullMethod<this>;
2766
+ whereNotNull: WhereNullMethod<this>;
2767
+ orWhereNotNull: WhereNullMethod<this>;
2768
+
2769
+ whereColumn: WhereColumnMethod<this>;
2770
+ orWhereColumn: WhereColumnMethod<this>;
2771
+ andWhereColumn: WhereColumnMethod<this>;
2772
+ whereNotColumn: WhereColumnMethod<this>;
2773
+ orWhereNotColumn: WhereColumnMethod<this>;
2774
+ andWhereNotColumn: WhereColumnMethod<this>;
2775
+
2776
+ whereJsonObject: WhereJsonObject<this>;
2777
+ orWhereJsonObject: WhereJsonObject<this>;
2778
+ andWhereJsonObject: WhereJsonObject<this>;
2779
+ whereNotJsonObject: WhereJsonObject<this>;
2780
+ orWhereNotJsonObject: WhereJsonObject<this>;
2781
+ andWhereNotJsonObject: WhereJsonObject<this>;
2782
+
2783
+ whereJsonPath: WhereJsonPath<this>;
2784
+ orWhereJsonPath: WhereJsonPath<this>;
2785
+ andWhereJsonPath: WhereJsonPath<this>;
2786
+
2787
+ whereJsonSupersetOf: WhereJsonMethod<this>;
2788
+ andWhereJsonSupersetOf: WhereJsonMethod<this>;
2789
+ orWhereJsonSupersetOf: WhereJsonMethod<this>;
2790
+ whereJsonNotSupersetOf: WhereJsonMethod<this>;
2791
+ andWhereJsonNotSupersetOf: WhereJsonMethod<this>;
2792
+ orWhereJsonNotSupersetOf: WhereJsonMethod<this>;
2793
+ whereJsonSubsetOf: WhereJsonMethod<this>;
2794
+ andWhereJsonSubsetOf: WhereJsonMethod<this>;
2795
+ orWhereJsonSubsetOf: WhereJsonMethod<this>;
2796
+ whereJsonNotSubsetOf: WhereJsonMethod<this>;
2797
+ andWhereJsonNotSubsetOf: WhereJsonMethod<this>;
2798
+ orWhereJsonNotSubsetOf: WhereJsonMethod<this>;
2799
+ whereJsonIsArray: WhereFieldExpressionMethod<this>;
2800
+ orWhereJsonIsArray: WhereFieldExpressionMethod<this>;
2801
+ whereJsonNotArray: WhereFieldExpressionMethod<this>;
2802
+ orWhereJsonNotArray: WhereFieldExpressionMethod<this>;
2803
+ whereJsonIsObject: WhereFieldExpressionMethod<this>;
2804
+ orWhereJsonIsObject: WhereFieldExpressionMethod<this>;
2805
+ whereJsonNotObject: WhereFieldExpressionMethod<this>;
2806
+ orWhereJsonNotObject: WhereFieldExpressionMethod<this>;
2807
+ /**
2808
+ * MySQL only: `JSON_OVERLAPS(field, value)`. True when two arrays share an item,
2809
+ * two objects share a key-value pair, or an array contains a scalar.
2810
+ */
2811
+ whereJsonOverlaps: WhereJsonMethod<this>;
2812
+ andWhereJsonOverlaps: WhereJsonMethod<this>;
2813
+ orWhereJsonOverlaps: WhereJsonMethod<this>;
2814
+ /**
2815
+ * MySQL only: the negation of `whereJsonOverlaps`. A NULL or missing field doesn't
2816
+ * overlap anything, so it's found.
2817
+ */
2818
+ whereJsonNotOverlaps: WhereJsonMethod<this>;
2819
+ andWhereJsonNotOverlaps: WhereJsonMethod<this>;
2820
+ orWhereJsonNotOverlaps: WhereJsonMethod<this>;
2821
+ whereJsonHasAny: WhereJsonExpressionMethod<this>;
2822
+ orWhereJsonHasAny: WhereJsonExpressionMethod<this>;
2823
+ whereJsonHasAll: WhereJsonExpressionMethod<this>;
2824
+ orWhereJsonHasAll: WhereJsonExpressionMethod<this>;
2825
+
2826
+ having: WhereMethod<this>;
2827
+ andHaving: WhereMethod<this>;
2828
+ orHaving: WhereMethod<this>;
2829
+
2830
+ havingRaw: WhereRawMethod<this>;
2831
+ orHavingRaw: WhereRawMethod<this>;
2832
+
2833
+ havingIn: WhereInMethod<this>;
2834
+ orHavingIn: WhereInMethod<this>;
2835
+ havingNotIn: WhereInMethod<this>;
2836
+ orHavingNotIn: WhereInMethod<this>;
2837
+
2838
+ havingNull: WhereNullMethod<this>;
2839
+ orHavingNull: WhereNullMethod<this>;
2840
+ havingNotNull: WhereNullMethod<this>;
2841
+ orHavingNotNull: WhereNullMethod<this>;
2842
+
2843
+ havingExists: WhereExistsMethod<this>;
2844
+ orHavingExists: WhereExistsMethod<this>;
2845
+ havingNotExists: WhereExistsMethod<this>;
2846
+ orHavingNotExists: WhereExistsMethod<this>;
2847
+
2848
+ havingBetween: WhereBetweenMethod<this>;
2849
+ orHavingBetween: WhereBetweenMethod<this>;
2850
+ havingNotBetween: WhereBetweenMethod<this>;
2851
+ orHavingNotBetween: WhereBetweenMethod<this>;
2852
+
2853
+ whereComposite: WhereCompositeMethod<this>;
2854
+ whereInComposite: WhereInCompositeMethod<this>;
2855
+ whereNotInComposite: WhereInCompositeMethod<this>;
2856
+
2857
+ union: UnionMethod<this>;
2858
+ unionAll: UnionMethod<this>;
2859
+ intersect: SetOperationsMethod<this>;
2860
+ except: SetOperationsMethod<this>;
2861
+
2862
+ with: WithMethod<this>;
2863
+ withRecursive: WithMethod<this>;
2864
+ withWrapped: WithMethod<this>;
2865
+ withMaterialized: WithMethod<this>;
2866
+ withNotMaterialized: WithMethod<this>;
2867
+
2868
+ joinRelated: JoinRelatedMethod<this>;
2869
+ innerJoinRelated: JoinRelatedMethod<this>;
2870
+ outerJoinRelated: JoinRelatedMethod<this>;
2871
+ leftJoinRelated: JoinRelatedMethod<this>;
2872
+ leftOuterJoinRelated: JoinRelatedMethod<this>;
2873
+ rightJoinRelated: JoinRelatedMethod<this>;
2874
+ rightOuterJoinRelated: JoinRelatedMethod<this>;
2875
+ fullOuterJoinRelated: JoinRelatedMethod<this>;
2876
+
2877
+ join: JoinMethod<this>;
2878
+ joinRaw: JoinRawMethod<this>;
2879
+ innerJoin: JoinMethod<this>;
2880
+ leftJoin: JoinMethod<this>;
2881
+ leftOuterJoin: JoinMethod<this>;
2882
+ rightJoin: JoinMethod<this>;
2883
+ rightOuterJoin: JoinMethod<this>;
2884
+ outerJoin: JoinMethod<this>;
2885
+ fullOuterJoin: JoinMethod<this>;
2886
+ crossJoin: CrossJoinMethod<this>;
2887
+
2888
+ count: CountMethod<this>;
2889
+ countDistinct: CountMethod<this>;
2890
+ min: AggregateMethod<this>;
2891
+ max: AggregateMethod<this>;
2892
+ sum: AggregateMethod<this>;
2893
+ sumDistinct: AggregateMethod<this>;
2894
+ avg: AggregateMethod<this>;
2895
+ avgDistinct: AggregateMethod<this>;
2896
+ increment: IncrementDecrementMethod<this>;
2897
+ decrement: IncrementDecrementMethod<this>;
2898
+ first(): IsAnyType<R> extends true ? any : [R] extends [readonly any[]] ? this['~maybe'] : this;
2899
+
2900
+ orderBy: OrderByMethod<this>;
2901
+ orderByRaw: OrderByRawMethod<this>;
2902
+
2903
+ groupBy: GroupByMethod<this>;
2904
+ groupByRaw: RawInterface<this>;
2905
+
2906
+ findById(id: MaybeCompositeId): this['~maybe'];
2907
+ findByIds(ids: MaybeCompositeId[]): this;
2908
+ findOne: WhereMethod<this['~maybe']>;
2909
+
2910
+ execute(): Promise<R>;
2911
+ // `castTo()` only changes the types. The relations of the graph methods are
2912
+ // still the relations of the original model, so they aren't checked after it.
2913
+ castTo<MC extends Model>(
2914
+ modelClass: ModelConstructor<MC>,
2915
+ ): RebindQueryBuilder<this, MC, ReplaceResultItem<R, MC>, CastItemState<MC>>;
2916
+ castTo<T>(): RebindQueryBuilder<this, M, T, QueryBuilderItemState<ResultItemOf<T, M>>>;
2917
+
2918
+ // For generic code (like custom query builder methods) where the model type
2919
+ // isn't known: `this.update<{ deletedAt: Date }>({ deletedAt: new Date() })`.
2920
+ // These overloads come first so that the errors of the other overloads are
2921
+ // the ones that are reported.
2922
+ update<T extends object = never>(update: NoInfer<T>): this['~count'];
2923
+ update<U extends object>(update: U & CheckModelUpdate<M, U>): this['~count'];
2924
+ update(update: PartialModelObject<M>): this['~count'];
2925
+ update(): this['~count'];
2926
+ updateAndFetch<U extends object>(update: U & CheckModelUpdate<M, U>): this['~one'];
2927
+ updateAndFetch(update: PartialModelObject<M>): this['~one'];
2928
+ updateAndFetchById<U extends object>(
2929
+ id: MaybeCompositeId,
2930
+ update: U & CheckModelUpdate<M, U>,
2931
+ ): this['~one'];
2932
+ updateAndFetchById(id: MaybeCompositeId, update: PartialModelObject<M>): this['~one'];
2933
+
2934
+ // For generic code (like custom query builder methods) where the model type
2935
+ // isn't known: `this.patch<{ deletedAt: Date }>({ deletedAt: new Date() })`.
2936
+ patch<T extends object = never>(update: NoInfer<T>): this['~count'];
2937
+ patch<U extends object>(update: U & CheckModelUpdate<M, U>): this['~count'];
2938
+ patch(update: PartialModelObject<M>): this['~count'];
2939
+ patch(): this['~count'];
2940
+ patchAndFetch<U extends object>(update: U & CheckModelUpdate<M, U>): this['~one'];
2941
+ patchAndFetch(update: PartialModelObject<M>): this['~one'];
2942
+ patchAndFetchById<U extends object>(
2943
+ id: MaybeCompositeId,
2944
+ update: U & CheckModelUpdate<M, U>,
2945
+ ): this['~one'];
2946
+ patchAndFetchById(id: MaybeCompositeId, update: PartialModelObject<M>): this['~one'];
2947
+
2948
+ del(): this['~count'];
2949
+ delete(): this['~count'];
2950
+ deleteById(id: MaybeCompositeId): this['~count'];
2951
+
2952
+ // For generic code where the model type isn't known.
2953
+ insert<T extends object = never>(insert: NoInfer<T>): this['~one'];
2954
+ insert<T extends object = never>(insert: NoInfer<T>[]): this['~many'];
2955
+ insert(insert: PartialModelObject<M>[]): this['~many'];
2956
+ insert(): this['~one'];
2957
+ // The error of the last overload is reported, so this one is last.
2958
+ insert(insert: PartialModelObject<M>): this['~one'];
2959
+
2960
+ onConflict(column?: ColumnRef | ColumnRef[] | true): this;
2961
+ ignore(): this;
2962
+ merge<U extends object>(merge: U & CheckModelUpdate<M, U>): this;
2963
+ merge(merge?: PartialModelObject<M> | string[]): this;
2964
+
2965
+ insertAndFetch(insert: PartialModelObject<M>): this['~one'];
2966
+ insertAndFetch(insert: PartialModelObject<M>[]): this['~many'];
2967
+ insertAndFetch(): this['~one'];
2968
+
2969
+ relate(
2970
+ ids: MaybeCompositeId | MaybeCompositeId[] | PartialModelObject<M> | PartialModelObject<M>[],
2971
+ ): this['~count'];
2972
+
2973
+ unrelate(): this['~count'];
2974
+ for(ids: ForIdValue | ForIdValue[]): this;
2975
+
2976
+ withGraphFetched: WithGraphMethod<this>;
2977
+ withGraphJoined: WithGraphMethod<this>;
2978
+
2979
+ truncate(): Promise<void>;
2980
+ allowGraph: AllowGraphMethod<this>;
2981
+
2982
+ throwIfNotFound(arg?: any): IsSingleResult<R> extends true ? this['~one'] : this;
2983
+
2984
+ returning(
2985
+ column: string | Raw | (string | Raw)[],
2986
+ ): IsAnyType<R> extends true ? any : [R] extends [number] ? this['~many'] : this;
2987
+ forUpdate: IdentityMethod<this>;
2988
+ forShare: IdentityMethod<this>;
2989
+ forNoKeyUpdate: IdentityMethod<this>;
2990
+ forKeyShare: IdentityMethod<this>;
2991
+ skipLocked: IdentityMethod<this>;
2992
+ noWait: IdentityMethod<this>;
2993
+ skipUndefined: IdentityMethod<this>;
2994
+ debug: IdentityMethod<this>;
2995
+ alias: OneArgMethod<string, this>;
2996
+ aliasFor: AliasForMethod<this>;
2997
+ withSchema: OneArgMethod<string, this>;
2998
+ modelClass: ModelClassMethod<M>;
2999
+ tableNameFor: TableRefForMethod;
3000
+ tableRefFor: TableRefForMethod;
3001
+ reject: OneArgMethod<any, this>;
3002
+ resolve: OneArgMethod<any, this>;
3003
+ transacting: OneArgMethod<TransactionOrKnex, this>;
3004
+ connection: OneArgMethod<TransactionOrKnex, this>;
3005
+ timeout: TimeoutMethod<this>;
3006
+ columnInfo: ColumnInfoMethod<this>;
3007
+
3008
+ toKnexQuery<T extends {} = ModelObject<M>>(): Knex.QueryBuilder<T, T[]>;
3009
+ knex(knex?: Knex): Knex;
3010
+ clone(): this;
3011
+
3012
+ page(page: number, pageSize: number): this['~page'];
3013
+ range(): this['~page'];
3014
+ range(start: number, end: number): this['~page'];
3015
+ offset(offset: number): this;
3016
+ limit(limit: number): this;
3017
+ resultSize(): Promise<number>;
3018
+
3019
+ runBefore: RunBeforeMethod<this>;
3020
+ runAfter: RunAfterMethod<this>;
3021
+
3022
+ onBuild: OnBuildMethod<this>;
3023
+ onBuildKnex: OnBuildKnexMethod<this>;
3024
+ onError: OnErrorMethod<this>;
3025
+
3026
+ insertGraph: InsertGraphMethod<M>;
3027
+ insertGraphAndFetch: InsertGraphMethod<M>;
3028
+
3029
+ upsertGraph: UpsertGraphMethod<M>;
3030
+ upsertGraphAndFetch: UpsertGraphMethod<M>;
3031
+
3032
+ graphExpressionObject: GraphExpressionObjectMethod<this>;
3033
+
3034
+ modifyGraph: ModifyGraphMethod<this>;
3035
+
3036
+ context: ContextMethod<this>;
3037
+ clearContext: ClearContextMethod<this>;
3038
+
3039
+ modify: ModifyMethod<this>;
3040
+ modifiers: ModifiersMethod<this>;
3041
+
3042
+ isFind: BooleanReturningMethod;
3043
+ isExecutable: BooleanReturningMethod;
3044
+ isInsert: BooleanReturningMethod;
3045
+ isUpdate: BooleanReturningMethod;
3046
+ isDelete: BooleanReturningMethod;
3047
+ isRelate: BooleanReturningMethod;
3048
+ isUnrelate: BooleanReturningMethod;
3049
+ isInternal: BooleanReturningMethod;
3050
+ hasWheres: BooleanReturningMethod;
3051
+ hasSelects: BooleanReturningMethod;
3052
+ hasWithGraph: BooleanReturningMethod;
3053
+
3054
+ has: HasMethod;
3055
+ clear: ClearMethod<this>;
3056
+
3057
+ clearSelect: IdentityMethod<this>;
3058
+ clearOrder: IdentityMethod<this>;
3059
+ clearWhere: IdentityMethod<this>;
3060
+ clearWithGraph: IdentityMethod<this>;
3061
+ clearAllowGraph: IdentityMethod<this>;
3062
+
3063
+ ModelType: M;
3064
+ ResultType: R;
3065
+
3066
+ then<R1 = R, R2 = never>(
3067
+ onfulfilled?: ((value: R) => R1 | PromiseLike<R1>) | undefined | null,
3068
+ onrejected?: ((reason: any) => R2 | PromiseLike<R2>) | undefined | null,
3069
+ ): Promise<R1 | R2>;
3070
+
3071
+ catch<FR = never>(
3072
+ onrejected?: ((reason: any) => FR | PromiseLike<FR>) | undefined | null,
3073
+ ): Promise<R | FR>;
3074
+ }
3075
+
3076
+ type X<T> = Promise<T>;
3077
+
3078
+ interface FetchGraphOptions {
3079
+ transaction?: TransactionOrKnex;
3080
+ skipFetched?: boolean;
3081
+ }
3082
+
3083
+ interface TraverserFunction {
3084
+ (model: Model, parentModel: Model, relationName: string): void;
3085
+ }
3086
+
3087
+ type ArrayQueryBuilderThunk<M extends Model> = () => ArrayQueryBuilder<QueryBuilderType<M>>;
3088
+ type CancelQueryThunk = (result: any) => void;
3089
+
3090
+ export interface StaticHookArguments<M extends Model, R = any> {
3091
+ asFindQuery: ArrayQueryBuilderThunk<M>;
3092
+ cancelQuery: CancelQueryThunk;
3093
+ context: QueryContext;
3094
+ transaction: TransactionOrKnex;
3095
+ relation?: Relation;
3096
+ modelOptions?: ModelOptions;
3097
+ items: Model[];
3098
+ inputItems: M[];
3099
+ result?: R;
3100
+ }
3101
+
3102
+ export type Transaction = Knex.Transaction;
3103
+ export type TransactionOrKnex = Transaction | Knex;
3104
+
3105
+ export interface RelationMappings {
3106
+ [relationName: string]: RelationMapping<any>;
3107
+ }
3108
+
3109
+ export type RelationMappingsThunk = () => RelationMappings;
3110
+
3111
+ type ModelClassFactory = () => AnyModelConstructor;
3112
+ type ModelClassSpecifier = ModelClassFactory | AnyModelConstructor | string;
3113
+ type RelationMappingHook<M extends Model> = (
3114
+ model: M,
3115
+ context: QueryContext,
3116
+ ) => Promise<void> | void;
3117
+ type StringOrReferenceBuilder = string | ReferenceBuilder;
3118
+ type RelationMappingColumnRef = StringOrReferenceBuilder | readonly StringOrReferenceBuilder[];
3119
+
3120
+ export interface RelationMapping<M extends Model> {
3121
+ relation: RelationType;
3122
+ modelClass: ModelClassSpecifier;
3123
+ join: RelationJoin;
3124
+ modify?: Modifier<QueryBuilderType<M>>;
3125
+ filter?: Modifier<QueryBuilderType<M>>;
3126
+ beforeInsert?: RelationMappingHook<M>;
3127
+ }
3128
+
3129
+ export interface RelationJoin {
3130
+ from: RelationMappingColumnRef;
3131
+ to: RelationMappingColumnRef;
3132
+ through?: RelationThrough<any>;
3133
+ }
3134
+
3135
+ export interface RelationThrough<M extends Model> {
3136
+ from: RelationMappingColumnRef;
3137
+ to: RelationMappingColumnRef;
3138
+ extra?: string | readonly string[] | Readonly<Record<string, string>>;
3139
+ modelClass?: ModelClassSpecifier;
3140
+ modify?: Modifier<QueryBuilderType<M>>;
3141
+ filter?: Modifier<QueryBuilderType<M>>;
3142
+ beforeInsert?: RelationMappingHook<M>;
3143
+ }
3144
+
3145
+ type RelationCardinality = 'one' | 'many';
3146
+
3147
+ export interface RelationType<C extends RelationCardinality = RelationCardinality>
3148
+ extends Constructor<Relation> {
3149
+ // Type-only: whether the relation is to one model or to many models.
3150
+ '~cardinality'?: C;
3151
+ }
3152
+
3153
+ /**
3154
+ * The relation mappings of model class `MC`, as written in its static
3155
+ * `relationMappings` property (an object or a function that returns one).
3156
+ * `{}` when they can't be inferred, for example when the property has the
3157
+ * type annotation `RelationMappings` or `RelationMappingsThunk`.
3158
+ */
3159
+ export type RelationMappingsOf<MC> = MC extends { relationMappings: infer R }
3160
+ ? InferredRelationMappings<R extends (...args: any[]) => infer O ? O : R>
3161
+ : {};
3162
+
3163
+ type InferredRelationMappings<T> =
3164
+ IsAnyType<T> extends true ? {} : string extends keyof T ? {} : T;
3165
+
3166
+ // The model class of a relation mapping's `modelClass`: a class, or a
3167
+ // function that returns one. `never` for module paths, whose class can't
3168
+ // be known.
3169
+ type RelatedModelClassOf<C> =
3170
+ IsAnyType<C> extends true
3171
+ ? never
3172
+ : C extends abstract new (...args: any[]) => Model
3173
+ ? C
3174
+ : C extends () => infer K
3175
+ ? K extends abstract new (...args: any[]) => Model
3176
+ ? K
3177
+ : never
3178
+ : never;
3179
+
3180
+ type RelatedModelOf<C> = [RelatedModelClassOf<C>] extends [never]
3181
+ ? Model
3182
+ : ModelInstance<RelatedModelClassOf<C>>;
3183
+
3184
+ // `join.through.extra` as an object of `{ property: column }`.
3185
+ type RelationExtraColumns<E> = E extends string
3186
+ ? { [K in E]: K }
3187
+ : E extends readonly (infer N extends string)[]
3188
+ ? { [K in N]: K }
3189
+ : E extends Readonly<Record<string, string>>
3190
+ ? E
3191
+ : {};
3192
+
3193
+ type RelationExtraProps<Mapping> = Mapping extends {
3194
+ join: { through: infer Through };
3195
+ }
3196
+ ? Through extends { extra: infer E }
3197
+ ? RelationExtraColumns<E> extends infer Columns
3198
+ ? string extends keyof Columns
3199
+ ? // The names of the columns are not known, for example when they
3200
+ // were inferred as `string[]`. Use `defineRelations` to keep them.
3201
+ {}
3202
+ : {
3203
+ -readonly [P in keyof Columns]: Through extends { modelClass: infer C }
3204
+ ? Columns[P] extends keyof RelatedModelOf<C>
3205
+ ? RelatedModelOf<C>[Columns[P]]
3206
+ : unknown
3207
+ : unknown;
3208
+ }
3209
+ : {}
3210
+ : {}
3211
+ : {};
3212
+
3213
+ type WithRelationExtraProps<M, Extra> = {} extends Extra ? M : M & Extra;
3214
+
3215
+ /**
3216
+ * The type of the relation property of a relation mapping.
3217
+ */
3218
+ export type RelationPropertyType<Mapping> = Mapping extends {
3219
+ relation: infer Type;
3220
+ modelClass: infer C;
3221
+ }
3222
+ ? WithRelationExtraProps<RelatedModelOf<C>, RelationExtraProps<Mapping>> extends infer Related
3223
+ ? Type extends { '~cardinality'?: infer Cardinality }
3224
+ ? [NonNullable<Cardinality>] extends ['many']
3225
+ ? Related[]
3226
+ : [NonNullable<Cardinality>] extends ['one']
3227
+ ? Related | null
3228
+ : Related | Related[] | null
3229
+ : Related | Related[] | null
3230
+ : never
3231
+ : never;
3232
+
3233
+ /**
3234
+ * The relation properties of model class `MC`, inferred from its
3235
+ * `relationMappings`. Use it to add the relation properties to the model's
3236
+ * instances without declaring each of them:
3237
+ *
3238
+ * ```ts
3239
+ * class Person extends Model {
3240
+ * static relationMappings = () => ({ pets: { ... } });
3241
+ * }
3242
+ *
3243
+ * interface Person extends RelationsOf<typeof Person> {}
3244
+ * ```
3245
+ */
3246
+ export type RelationsOf<MC> = {
3247
+ [K in keyof RelationMappingsOf<MC>]?: RelationPropertyType<RelationMappingsOf<MC>[K]>;
3248
+ };
3249
+
3250
+ type InferredRelationProps<MC, I> = {
3251
+ [K in Exclude<keyof RelationMappingsOf<MC>, keyof I>]?: RelationPropertyType<
3252
+ RelationMappingsOf<MC>[K]
3253
+ >;
3254
+ };
3255
+
3256
+ /**
3257
+ * The instance type of model class `MC`, including the relation properties
3258
+ * inferred from its `relationMappings` that the class doesn't declare.
3259
+ */
3260
+ export type ModelInstance<MC> = MC extends abstract new (...args: any[]) => infer I
3261
+ ? WithModelModifiers<
3262
+ MC,
3263
+ [Exclude<keyof RelationMappingsOf<MC>, keyof I>] extends [never]
3264
+ ? I
3265
+ : I & InferredRelationProps<MC, I>
3266
+ >
3267
+ : never;
3268
+
3269
+ // Named modifiers are static, so the types of the instances carry them for the
3270
+ // query builders, which only know the instance type.
3271
+ type WithModelModifiers<MC, I> = [ModifiersOf<MC>] extends [never] ? I : I & ModelModifiers<MC>;
3272
+
3273
+ interface ModelModifiers<MC> {
3274
+ '~modifiers'?: ModifiersOf<MC>;
3275
+ }
3276
+
3277
+ // The named modifiers of model class `MC` from its static `modifiers`, or
3278
+ // `never` when their names can't be known (like with the type `Modifiers`).
3279
+ type ModifiersOf<MC> = MC extends { modifiers: infer Mods }
3280
+ ? IsAnyType<Mods> extends true
3281
+ ? never
3282
+ : string extends keyof Mods
3283
+ ? never
3284
+ : Mods
3285
+ : never;
3286
+
3287
+ // The named modifiers of model `M`, or `never` when they're not known.
3288
+ type KnownModifiers<M> =
3289
+ RelationsModel<M> extends infer RM
3290
+ ? IsAnyType<RM> extends true
3291
+ ? never
3292
+ : '~modifiers' extends keyof RM
3293
+ ? NonNullable<RM['~modifiers' & keyof RM]>
3294
+ : never
3295
+ : never;
3296
+
3297
+ /**
3298
+ * The names of the relations of model class `MC` inferred from its
3299
+ * `relationMappings`.
3300
+ */
3301
+ type RelationNamesOf<MC> = keyof RelationMappingsOf<MC> & string;
3302
+
3303
+ // The query builder of a relation for the static `relatedQuery()`.
3304
+ type RelationQueryBuilder<Mapping> = Mapping extends { modelClass: infer C }
3305
+ ? [RelatedModelClassOf<C>] extends [never]
3306
+ ? QueryBuilder<Model>
3307
+ : ModelClassQueryBuilder<
3308
+ RelatedModelClassOf<C>,
3309
+ Extract<
3310
+ WithRelationExtraProps<
3311
+ ModelInstance<RelatedModelClassOf<C>>,
3312
+ RelationExtraProps<Mapping>
3313
+ >,
3314
+ Model
3315
+ >,
3316
+ WithRelationExtraProps<
3317
+ ModelRow<ModelInstance<RelatedModelClassOf<C>>>,
3318
+ RelationExtraProps<Mapping>
3319
+ >
3320
+ >
3321
+ : QueryBuilder<Model>;
3322
+
3323
+ // Shown in the error message when a relation name isn't known.
3324
+ type UnknownRelationName = {
3325
+ '~error': 'Unknown relation. Pass the related model type explicitly for relation names that can not be checked: relatedQuery<Pet>(name)';
3326
+ };
3327
+
3328
+ type RelationMappingsDefinition = { readonly [relationName: string]: RelationMapping<any> };
3329
+
3330
+ export interface DefineRelationsFunction {
3331
+ /**
3332
+ * Returns the relation mappings as is. Use it to define `relationMappings`
3333
+ * so that the types of the relations can be inferred exactly:
3334
+ *
3335
+ * ```ts
3336
+ * static relationMappings = defineRelations(() => ({
3337
+ * movies: {
3338
+ * relation: Model.ManyToManyRelation,
3339
+ * modelClass: Movie,
3340
+ * join: {
3341
+ * from: 'persons.id',
3342
+ * through: { from: 'persons_movies.personId', to: 'persons_movies.movieId', extra: ['role'] },
3343
+ * to: 'movies.id',
3344
+ * },
3345
+ * },
3346
+ * }));
3347
+ * ```
3348
+ */
3349
+ <const T extends RelationMappingsDefinition>(relationMappings: () => T): () => T;
3350
+ <const T extends RelationMappingsDefinition>(relationMappings: T): T;
3351
+ }
3352
+
3353
+ export interface Relation {
3354
+ name: string;
3355
+ ownerModelClass: typeof Model;
3356
+ relatedModelClass: typeof Model;
3357
+ ownerProp: RelationProperty;
3358
+ relatedProp: RelationProperty;
3359
+ joinModelClass: typeof Model;
3360
+ joinTable: string;
3361
+ joinTableOwnerProp: RelationProperty;
3362
+ joinTableRelatedProp: RelationProperty;
3363
+ }
3364
+
3365
+ export interface RelationProperty {
3366
+ size: number;
3367
+ modelClass: typeof Model;
3368
+ props: string[];
3369
+ cols: string[];
3370
+ }
3371
+
3372
+ export interface Relations {
3373
+ [name: string]: Relation;
3374
+ }
3375
+
3376
+ export interface QueryContext {
3377
+ transaction: Transaction;
3378
+ [key: string]: any;
3379
+ }
3380
+
3381
+ export interface ModelOptions {
3382
+ patch?: boolean;
3383
+ skipValidation?: boolean;
3384
+ old?: object;
3385
+ }
3386
+
3387
+ export interface CloneOptions {
3388
+ shallow?: boolean;
3389
+ }
3390
+
3391
+ export interface ToJsonOptions extends CloneOptions {
3392
+ virtuals?: boolean | string[];
3393
+ }
3394
+
3395
+ export interface ValidatorContext {
3396
+ [key: string]: any;
3397
+ }
3398
+
3399
+ export interface ValidatorArgs {
3400
+ ctx: ValidatorContext;
3401
+ model: Model;
3402
+ json: Pojo;
3403
+ options: ModelOptions;
3404
+ }
3405
+
3406
+ export class Validator {
3407
+ beforeValidate(args: ValidatorArgs): void;
3408
+ validate(args: ValidatorArgs): Pojo;
3409
+ afterValidate(args: ValidatorArgs): void;
3410
+ }
3411
+
3412
+ export interface AjvConfig {
3413
+ onCreateAjv(ajv: Ajv): void;
3414
+ options?: AjvOptions;
3415
+ }
3416
+
3417
+ export class AjvValidator extends Validator {
3418
+ constructor(config: AjvConfig);
3419
+ }
3420
+
3421
+ export interface SnakeCaseMappersOptions {
3422
+ upperCase?: boolean;
3423
+ underscoreBeforeDigits?: boolean;
3424
+ underscoreBetweenUppercaseLetters?: boolean;
3425
+ }
3426
+
3427
+ export interface ColumnNameMappers {
3428
+ parse(json: Pojo): Pojo;
3429
+ format(json: Pojo): Pojo;
3430
+ }
3431
+
3432
+ export interface SnakeCaseMappersFactory {
3433
+ (options?: SnakeCaseMappersOptions): ColumnNameMappers;
3434
+ }
3435
+
3436
+ export interface KnexMappers {
3437
+ wrapIdentifier(identifier: string, origWrap: Identity<string>): string;
3438
+ postProcessResponse(response: any): any;
3439
+ }
3440
+
3441
+ export interface KnexSnakeCaseMappersFactory {
3442
+ (options?: SnakeCaseMappersOptions): KnexMappers;
3443
+ }
3444
+
3445
+ export type ValidationErrorType =
3446
+ | 'ModelValidation'
3447
+ | 'RelationExpression'
3448
+ | 'UnallowedRelation'
3449
+ | 'InvalidGraph';
3450
+
3451
+ export class ValidationError extends Error {
3452
+ constructor(args: CreateValidationErrorArgs & { modelClass?: ModelClass<Model> });
3453
+
3454
+ statusCode: number;
3455
+ message: string;
3456
+ data?: ErrorHash | any;
3457
+ type: ValidationErrorType | string;
3458
+ modelClass: ModelClass<Model>;
3459
+ }
3460
+
3461
+ export interface ValidationErrorItem {
3462
+ message: string;
3463
+ keyword: string;
3464
+ params: Pojo;
3465
+ }
3466
+
3467
+ export interface ErrorHash {
3468
+ [columnName: string]: ValidationErrorItem[];
3469
+ }
3470
+
3471
+ export interface CreateValidationErrorArgs {
3472
+ statusCode?: number;
3473
+ message?: string;
3474
+ data?: ErrorHash | any;
3475
+ // This can be any string for custom errors. ValidationErrorType is there
3476
+ // only to document the default values objection uses internally.
3477
+ type: ValidationErrorType | string;
3478
+ }
3479
+
3480
+ export class NotFoundError extends Error {
3481
+ constructor(args: CreateNotFoundErrorArgs & { modelClass?: ModelClass<Model> });
3482
+
3483
+ statusCode: number;
3484
+ data?: any;
3485
+ type: 'NotFound';
3486
+ modelClass: ModelClass<Model>;
3487
+ }
3488
+
3489
+ export interface CreateNotFoundErrorArgs {
3490
+ statusCode?: number;
3491
+ message?: string;
3492
+ data?: any;
3493
+ [key: string]: any;
3494
+ }
3495
+
3496
+ export interface TableMetadata {
3497
+ columns: Array<string>;
3498
+ }
3499
+
3500
+ export interface TableMetadataOptions {
3501
+ table: string;
3502
+ }
3503
+
3504
+ export interface FetchTableMetadataOptions {
3505
+ knex?: Knex;
3506
+ force?: boolean;
3507
+ table?: string;
3508
+ }
3509
+
3510
+ export interface Constructor<T> {
3511
+ new (): T;
3512
+ }
3513
+
3514
+ interface PrototypeType<T> extends Function {
3515
+ prototype: T;
3516
+ }
3517
+
3518
+ interface ConstructorFunctionType<T = any> extends PrototypeType<T> {
3519
+ new (...args: any[]): T;
3520
+ }
3521
+
3522
+ // for internal use on generic static this deduction, copied from https://github.com/microsoft/TypeScript/issues/5863#issuecomment-1483978415
3523
+ type ConstructorType<T = unknown, Static extends Record<string, any> = PrototypeType<T>> = (
3524
+ | ConstructorFunctionType<T>
3525
+ | PrototypeType<T>
3526
+ ) & {
3527
+ [Key in keyof Static]: Static[Key];
3528
+ };
3529
+
3530
+ export interface ModelConstructor<M extends Model> extends Constructor<M> {}
3531
+
3532
+ export interface ModelClass<M extends Model> extends ModelConstructor<M> {
3533
+ QueryBuilder: typeof QueryBuilder;
3534
+
3535
+ tableName: string;
3536
+ idColumn: string | string[];
3537
+ jsonSchema: JSONSchema;
3538
+ relationMappings: RelationMappings | RelationMappingsThunk;
3539
+ modelPaths: string[];
3540
+ jsonAttributes: string[];
3541
+ virtualAttributes: string[];
3542
+ uidProp: string;
3543
+ uidRefProp: string;
3544
+ dbRefProp: string;
3545
+ propRefRegex: RegExp;
3546
+ pickJsonSchemaProperties: boolean;
3547
+ relatedFindQueryMutates: boolean;
3548
+ relatedInsertQueryMutates: boolean;
3549
+ useLimitInFirst: boolean;
3550
+ modifiers: Modifiers;
3551
+ columnNameMappers: ColumnNameMappers;
3552
+
3553
+ raw: RawFunction;
3554
+ ref: ReferenceFunction;
3555
+ fn: FunctionFunction;
3556
+
3557
+ BelongsToOneRelation: RelationType<'one'>;
3558
+ HasOneRelation: RelationType<'one'>;
3559
+ HasManyRelation: RelationType<'many'>;
3560
+ ManyToManyRelation: RelationType<'many'>;
3561
+ HasOneThroughRelation: RelationType<'one'>;
3562
+
3563
+ defaultGraphOptions?: GraphOptions;
3564
+
3565
+ query(this: Constructor<M>, trxOrKnex?: TransactionOrKnex): QueryBuilderType<M>;
3566
+
3567
+ relatedQuery<K extends keyof M>(
3568
+ relationName: K,
3569
+ trxOrKnex?: TransactionOrKnex,
3570
+ ): NoInfer<ArrayRelatedQueryBuilder<M[K]>>;
3571
+
3572
+ // For relation names that can't be checked. The model type of the
3573
+ // relation must be given explicitly: `relatedQuery<Pet>(relationName)`.
3574
+ relatedQuery<RM extends Model = never>(
3575
+ relationName: [RM] extends [never] ? UnknownRelationName : string,
3576
+ trxOrKnex?: TransactionOrKnex,
3577
+ ): RowQueryBuilder<QueryBuilderType<RM>, RM>;
3578
+
3579
+ fromJson(json: object, opt?: ModelOptions): M;
3580
+ fromDatabaseJson(json: object): M;
3581
+
3582
+ columnNameToPropertyName(columnName: string): string;
3583
+ propertyNameToColumnName(propertyName: string): string;
3584
+
3585
+ createValidator(): Validator;
3586
+ createValidationError(args: CreateValidationErrorArgs): Error;
3587
+ createNotFoundError(queryContext: QueryContext, args: CreateNotFoundErrorArgs): Error;
3588
+
3589
+ tableMetadata(opt?: TableMetadataOptions): TableMetadata;
3590
+ fetchTableMetadata(opt?: FetchTableMetadataOptions): Promise<TableMetadata>;
3591
+
3592
+ knex(knex?: Knex): Knex;
3593
+ knexQuery(): Knex.QueryBuilder;
3594
+ startTransaction(knexOrTransaction?: TransactionOrKnex): Promise<Transaction>;
3595
+
3596
+ transaction<T>(callback: (trx: Transaction) => Promise<T>): Promise<T>;
3597
+ transaction<T>(
3598
+ trxOrKnex: TransactionOrKnex,
3599
+ callback: (trx: Transaction) => Promise<T>,
3600
+ ): Promise<T>;
3601
+
3602
+ bindKnex(trxOrKnex: TransactionOrKnex): this;
3603
+ bindTransaction(trxOrKnex: TransactionOrKnex): this;
3604
+
3605
+ fetchGraph<T extends PartialModelObject<M>, const E extends RelationExpression<M>>(
3606
+ modelOrObject: T,
3607
+ expression: CheckRelationExpression<M, E>,
3608
+ options?: FetchGraphOptions,
3609
+ ): FetchGraphQueryBuilder<QueryBuilderType<M>, M, T, E, 'one'>;
3610
+
3611
+ fetchGraph<T extends PartialModelObject<M>, const E extends RelationExpression<M>>(
3612
+ modelOrObject: T[],
3613
+ expression: CheckRelationExpression<M, E>,
3614
+ options?: FetchGraphOptions,
3615
+ ): FetchGraphQueryBuilder<QueryBuilderType<M>, M, T, E, 'many'>;
3616
+
3617
+ getRelations(): Relations;
3618
+ getRelation(name: string): Relation;
3619
+
3620
+ traverse(models: Model | Model[], traverser: TraverserFunction): void;
3621
+ traverse(
3622
+ filterConstructor: ModelConstructor<Model>,
3623
+ models: Model | Model[],
3624
+ traverser: TraverserFunction,
3625
+ ): void;
3626
+ traverseAsync(models: Model | Model[], traverser: TraverserFunction): Promise<void>;
3627
+ traverseAsync(
3628
+ filterConstructor: ModelConstructor<Model>,
3629
+ models: Model | Model[],
3630
+ traverser: TraverserFunction,
3631
+ ): Promise<void>;
3632
+
3633
+ beforeFind(args: StaticHookArguments<any>): any;
3634
+ afterFind(args: StaticHookArguments<any>): any;
3635
+ beforeInsert(args: StaticHookArguments<any>): any;
3636
+ afterInsert(args: StaticHookArguments<any>): any;
3637
+ beforeUpdate(args: StaticHookArguments<any>): any;
3638
+ afterUpdate(args: StaticHookArguments<any>): any;
3639
+ beforeDelete(args: StaticHookArguments<any>): any;
3640
+ afterDelete(args: StaticHookArguments<any>): any;
3641
+ }
3642
+
3643
+ export class Model {
3644
+ // This allows model classes to be used as the base class of mixins.
3645
+ constructor(...args: any[]);
3646
+
3647
+ static QueryBuilder: typeof QueryBuilder;
3648
+
3649
+ static tableName: string;
3650
+ static idColumn: string | string[];
3651
+ static jsonSchema: JSONSchema;
3652
+ static relationMappings: RelationMappings | RelationMappingsThunk;
3653
+ static modelPaths: string[];
3654
+ static jsonAttributes: string[];
3655
+ static virtualAttributes: string[];
3656
+ static uidProp: string;
3657
+ static uidRefProp: string;
3658
+ static dbRefProp: string;
3659
+ static propRefRegex: RegExp;
3660
+ static pickJsonSchemaProperties: boolean;
3661
+ static relatedFindQueryMutates: boolean;
3662
+ static relatedInsertQueryMutates: boolean;
3663
+ static useLimitInFirst: boolean;
3664
+ static modifiers: Modifiers;
3665
+ static columnNameMappers: ColumnNameMappers;
3666
+
3667
+ static raw: RawFunction;
3668
+ /**
3669
+ * A reference to a column of this model, qualified with the table (or the alias
3670
+ * of the table) in the query. The column must be a property of the model. Pass the
3671
+ * expression as a type argument for columns the model doesn't declare:
3672
+ * `Person.ref<'legacy_column'>('legacy_column')`.
3673
+ */
3674
+ static ref<E extends string = never>(
3675
+ expression: [E] extends [never] ? never : NoInfer<E>,
3676
+ ): ReferenceBuilder;
3677
+ static ref<MC extends AnyModelConstructor, E extends RefExpression<ModelInstance<MC>>>(
3678
+ this: MC,
3679
+ expression: E,
3680
+ ): ReferenceBuilder<RefValue<ModelInstance<MC>, E>>;
3681
+ static fn: FunctionFunction;
3682
+
3683
+ static BelongsToOneRelation: RelationType<'one'>;
3684
+ static HasOneRelation: RelationType<'one'>;
3685
+ static HasManyRelation: RelationType<'many'>;
3686
+ static ManyToManyRelation: RelationType<'many'>;
3687
+ static HasOneThroughRelation: RelationType<'one'>;
3688
+
3689
+ static defaultGraphOptions?: GraphOptions;
3690
+
3691
+ static query<MC extends Constructor<Model>>(
3692
+ this: MC,
3693
+ trxOrKnex?: TransactionOrKnex,
3694
+ ): ModelClassQueryBuilder<MC, Extract<ModelInstance<MC>, Model>>;
3695
+
3696
+ static relatedQuery<MC extends Constructor<Model>, K extends RelationNamesOf<MC>>(
3697
+ this: MC,
3698
+ relationName: K,
3699
+ trxOrKnex?: TransactionOrKnex,
3700
+ ): RelationQueryBuilder<RelationMappingsOf<MC>[K]>;
3701
+
3702
+ static relatedQuery<M extends Model, K extends keyof M>(
3703
+ this: ConstructorType<M>,
3704
+ relationName: K,
3705
+ trxOrKnex?: TransactionOrKnex,
3706
+ ): NoInfer<ArrayRelatedQueryBuilder<M[K]>>;
3707
+
3708
+ // For relation names that can't be checked. The model type of the
3709
+ // relation must be given explicitly: `relatedQuery<Pet>(relationName)`.
3710
+ static relatedQuery<RM extends Model = never>(
3711
+ relationName: [RM] extends [never] ? UnknownRelationName : string,
3712
+ trxOrKnex?: TransactionOrKnex,
3713
+ ): RowQueryBuilder<QueryBuilderType<RM>, RM>;
3714
+
3715
+ static fromJson<MC extends Constructor<Model>>(
3716
+ this: MC,
3717
+ json: object,
3718
+ opt?: ModelOptions,
3719
+ ): ModelInstance<MC>;
3720
+ static fromJson<M extends Model>(this: Constructor<M>, json: object, opt?: ModelOptions): M;
3721
+ static fromDatabaseJson<MC extends Constructor<Model>>(
3722
+ this: MC,
3723
+ json: object,
3724
+ ): ModelInstance<MC>;
3725
+ static fromDatabaseJson<M extends Model>(this: Constructor<M>, json: object): M;
3726
+
3727
+ static columnNameToPropertyName(columnName: string): string;
3728
+ static propertyNameToColumnName(propertyName: string): string;
3729
+
3730
+ static createValidator(): Validator;
3731
+ static createValidationError(args: CreateValidationErrorArgs): Error;
3732
+ static createNotFoundError(queryContext: QueryContext, args: CreateNotFoundErrorArgs): Error;
3733
+
3734
+ static tableMetadata(opt?: TableMetadataOptions): TableMetadata;
3735
+ static fetchTableMetadata(opt?: FetchTableMetadataOptions): Promise<TableMetadata>;
3736
+
3737
+ static knex(knex?: Knex): Knex;
3738
+ static knexQuery(): Knex.QueryBuilder;
3739
+ static startTransaction(knexOrTransaction?: TransactionOrKnex): Promise<Transaction>;
3740
+
3741
+ static transaction<T>(callback: (trx: Transaction) => Promise<T>): Promise<T>;
3742
+ static transaction<T>(
3743
+ trxOrKnex: TransactionOrKnex | undefined,
3744
+ callback: (trx: Transaction) => Promise<T>,
3745
+ ): Promise<T>;
3746
+
3747
+ static bindKnex<M>(this: M, trxOrKnex: TransactionOrKnex): M;
3748
+ static bindTransaction<M>(this: M, trxOrKnex: TransactionOrKnex): M;
3749
+
3750
+ static fetchGraph: StaticFetchGraphMethod;
3751
+
3752
+ static getRelations(): Relations;
3753
+ static getRelation(name: string): Relation;
3754
+
3755
+ static traverse(models: Model | Model[], traverser: TraverserFunction): void;
3756
+ static traverse(
3757
+ filterConstructor: typeof Model,
3758
+ models: Model | Model[],
3759
+ traverser: TraverserFunction,
3760
+ ): void;
3761
+ static traverseAsync(models: Model | Model[], traverser: TraverserFunction): Promise<void>;
3762
+ static traverseAsync(
3763
+ filterConstructor: typeof Model,
3764
+ models: Model | Model[],
3765
+ traverser: TraverserFunction,
3766
+ ): Promise<void>;
3767
+
3768
+ static beforeFind(args: StaticHookArguments<any>): any;
3769
+ static afterFind(args: StaticHookArguments<any>): any;
3770
+ static beforeInsert(args: StaticHookArguments<any>): any;
3771
+ static afterInsert(args: StaticHookArguments<any>): any;
3772
+ static beforeUpdate(args: StaticHookArguments<any>): any;
3773
+ static afterUpdate(args: StaticHookArguments<any>): any;
3774
+ static beforeDelete(args: StaticHookArguments<any>): any;
3775
+ static afterDelete(args: StaticHookArguments<any>): any;
3776
+
3777
+ $modelClass: ModelClass<this>;
3778
+
3779
+ $relatedQuery<K extends keyof this>(
3780
+ relationName: K,
3781
+ trxOrKnex?: TransactionOrKnex,
3782
+ ): NoInfer<RelatedQueryBuilder<this[K]>>;
3783
+
3784
+ // For relation names that can't be checked. The model type of the
3785
+ // relation must be given explicitly: `$relatedQuery<Pet>(relationName)`.
3786
+ $relatedQuery<RM extends Model = never>(
3787
+ relationName: [RM] extends [never] ? UnknownRelationName : string,
3788
+ trxOrKnex?: TransactionOrKnex,
3789
+ ): RowQueryBuilder<QueryBuilderType<RM>, RM>;
3790
+
3791
+ $query(trxOrKnex?: TransactionOrKnex): SingleQueryBuilder<QueryBuilderType<this>>;
3792
+
3793
+ $id(id: any): void;
3794
+ $id(): any;
3795
+
3796
+ // `this` is a type parameter so that the signature is the same for every model,
3797
+ // which makes comparing models much faster.
3798
+ $fetchGraph<T extends Model, const E extends RelationExpression<Model>>(
3799
+ this: T,
3800
+ expression: CheckRelationExpression<ModelOfRow<T>, E>,
3801
+ options?: FetchGraphOptions,
3802
+ ): FetchGraphQueryBuilder<QueryBuilderType<T>, ModelOfRow<T>, T, E, 'one'>;
3803
+
3804
+ $formatDatabaseJson(json: Pojo): Pojo;
3805
+ $parseDatabaseJson(json: Pojo): Pojo;
3806
+
3807
+ $formatJson(json: Pojo): Pojo;
3808
+ $parseJson(json: Pojo, opt?: ModelOptions): Pojo;
3809
+
3810
+ $beforeValidate(jsonSchema: JSONSchema, json: Pojo, opt: ModelOptions): JSONSchema;
3811
+ $validate(json?: Pojo, opt?: ModelOptions): Pojo; // may throw ValidationError if validation fails
3812
+ $afterValidate(json: Pojo, opt: ModelOptions): void; // may throw ValidationError if validation fails
3813
+
3814
+ $beforeInsert(queryContext: QueryContext): Promise<any> | void;
3815
+ $afterInsert(queryContext: QueryContext): Promise<any> | void;
3816
+ $afterUpdate(opt: ModelOptions, queryContext: QueryContext): Promise<any> | void;
3817
+ $beforeUpdate(opt: ModelOptions, queryContext: QueryContext): Promise<any> | void;
3818
+ $afterFind(queryContext: QueryContext): Promise<any> | void;
3819
+ $beforeDelete(queryContext: QueryContext): Promise<any> | void;
3820
+ $afterDelete(queryContext: QueryContext): Promise<any> | void;
3821
+
3822
+ $toDatabaseJson(): Pojo;
3823
+ $toJson(opt?: ToJsonOptions): ModelObject<this>;
3824
+ toJSON(opt?: ToJsonOptions): ModelObject<this>;
3825
+
3826
+ $setJson(json: object, opt?: ModelOptions): this;
3827
+ $setDatabaseJson(json: object): this;
3828
+
3829
+ $setRelated<RM extends Model>(
3830
+ relation: String | Relation,
3831
+ related: RM | RM[] | null | undefined,
3832
+ ): this;
3833
+
3834
+ $appendRelated<RM extends Model>(
3835
+ relation: String | Relation,
3836
+ related: RM | RM[] | null | undefined,
3837
+ ): this;
3838
+
3839
+ $set(obj: Pojo): this;
3840
+ $clone(opt?: CloneOptions): this;
3841
+ $traverse(filterConstructor: typeof Model, traverser: TraverserFunction): this;
3842
+ $traverse(traverser: TraverserFunction): this;
3843
+ $traverseAsync(filterConstructor: typeof Model, traverser: TraverserFunction): Promise<this>;
3844
+ $traverseAsync(traverser: TraverserFunction): Promise<this>;
3845
+ $omitFromJson(keys: string | string[] | { [key: string]: boolean }): this;
3846
+ $omitFromDatabaseJson(keys: string | string[] | { [key: string]: boolean }): this;
3847
+
3848
+ $knex(): Knex;
3849
+ $transaction(): Knex;
3850
+
3851
+ QueryBuilderType: QueryBuilder<this, this[], QueryBuilderItemState<this>>;
3852
+ }
3853
+
3854
+ /**
3855
+ * Overloading is required here until the following issues (at least) are resolved:
3856
+ *
3857
+ * - https://github.com/microsoft/TypeScript/issues/1360
3858
+ * - https://github.com/Microsoft/TypeScript/issues/5453
3859
+ *
3860
+ * @tutorial https://vincit.github.io/objection.js/guide/transactions.html#creating-a-transaction
3861
+ */
3862
+ export interface transaction {
3863
+ start(knexOrModel: Knex | AnyModelConstructor): Promise<Transaction>;
3864
+
3865
+ <MC1 extends AnyModelConstructor, ReturnValue>(
3866
+ modelClass1: MC1,
3867
+ callback: (boundModelClass: MC1, trx?: Transaction) => Promise<ReturnValue>,
3868
+ ): Promise<ReturnValue>;
3869
+
3870
+ <MC1 extends AnyModelConstructor, MC2 extends AnyModelConstructor, ReturnValue>(
3871
+ modelClass1: MC1,
3872
+ modelClass2: MC2,
3873
+ callback: (
3874
+ boundModelClass1: MC1,
3875
+ boundModelClass2: MC2,
3876
+ trx?: Transaction,
3877
+ ) => Promise<ReturnValue>,
3878
+ ): Promise<ReturnValue>;
3879
+
3880
+ <
3881
+ MC1 extends AnyModelConstructor,
3882
+ MC2 extends AnyModelConstructor,
3883
+ MC3 extends AnyModelConstructor,
3884
+ ReturnValue,
3885
+ >(
3886
+ modelClass1: MC1,
3887
+ modelClass2: MC2,
3888
+ modelClass3: MC3,
3889
+ callback: (
3890
+ boundModelClass1: MC1,
3891
+ boundModelClass2: MC2,
3892
+ boundModelClass3: MC3,
3893
+ trx?: Transaction,
3894
+ ) => Promise<ReturnValue>,
3895
+ ): Promise<ReturnValue>;
3896
+
3897
+ <
3898
+ MC1 extends AnyModelConstructor,
3899
+ MC2 extends AnyModelConstructor,
3900
+ MC3 extends AnyModelConstructor,
3901
+ MC4 extends AnyModelConstructor,
3902
+ ReturnValue,
3903
+ >(
3904
+ modelClass1: MC1,
3905
+ modelClass2: MC2,
3906
+ modelClass3: MC3,
3907
+ modelClass4: MC4,
3908
+ callback: (
3909
+ boundModelClass1: MC1,
3910
+ boundModelClass2: MC2,
3911
+ boundModelClass3: MC3,
3912
+ boundModelClass4: MC4,
3913
+ trx?: Transaction,
3914
+ ) => Promise<ReturnValue>,
3915
+ ): Promise<ReturnValue>;
3916
+
3917
+ <
3918
+ MC1 extends AnyModelConstructor,
3919
+ MC2 extends AnyModelConstructor,
3920
+ MC3 extends AnyModelConstructor,
3921
+ MC4 extends AnyModelConstructor,
3922
+ MC5 extends AnyModelConstructor,
3923
+ ReturnValue,
3924
+ >(
3925
+ modelClass1: MC1,
3926
+ modelClass2: MC2,
3927
+ modelClass3: MC3,
3928
+ modelClass4: MC4,
3929
+ modelClass5: MC5,
3930
+ callback: (
3931
+ boundModelClass1: MC1,
3932
+ boundModelClass2: MC2,
3933
+ boundModelClass3: MC3,
3934
+ boundModelClass4: MC4,
3935
+ boundModelClass5: MC5,
3936
+ trx?: Transaction,
3937
+ ) => Promise<ReturnValue>,
3938
+ ): Promise<ReturnValue>;
3939
+
3940
+ <ReturnValue>(
3941
+ knex: Knex,
3942
+ callback: (trx: Transaction) => Promise<ReturnValue>,
3943
+ ): Promise<ReturnValue>;
3944
+ }
3945
+
3946
+ interface initialize {
3947
+ (knex: Knex, modelClasses: AnyModelConstructor[]): Promise<void>;
3948
+ (modelClasses: AnyModelConstructor[]): Promise<void>;
3949
+ }
3950
+
3951
+ /**
3952
+ * JSON Schema 7
3953
+ * Draft 07
3954
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01
3955
+ *
3956
+ * These definitions were written by
3957
+ *
3958
+ * Boris Cherny https://github.com/bcherny,
3959
+ * Cyrille Tuzi https://github.com/cyrilletuzi,
3960
+ * Lucian Buzzo https://github.com/lucianbuzzo,
3961
+ * Roland Groza https://github.com/rolandjitsu.
3962
+ *
3963
+ * https://www.npmjs.com/package/@types/json-schema
3964
+ */
3965
+
3966
+ /**
3967
+ * Primitive type
3968
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1
3969
+ */
3970
+ export type JSONSchemaTypeName =
3971
+ | 'string'
3972
+ | 'number'
3973
+ | 'integer'
3974
+ | 'boolean'
3975
+ | 'object'
3976
+ | 'array'
3977
+ | 'null'
3978
+ | string;
3979
+
3980
+ export type JSONSchemaType = JSONSchemaArray[] | boolean | number | null | object | string;
3981
+
3982
+ // Workaround for infinite type recursion
3983
+ // https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540
3984
+ export interface JSONSchemaArray extends Array<JSONSchemaType> {}
3985
+
3986
+ /**
3987
+ * Meta schema
3988
+ *
3989
+ * Recommended values:
3990
+ * - 'http://json-schema.org/schema#'
3991
+ * - 'http://json-schema.org/hyper-schema#'
3992
+ * - 'http://json-schema.org/draft-07/schema#'
3993
+ * - 'http://json-schema.org/draft-07/hyper-schema#'
3994
+ *
3995
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5
3996
+ */
3997
+ export type JSONSchemaVersion = string;
3998
+
3999
+ /**
4000
+ * JSON Schema v7
4001
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01
4002
+ */
4003
+ export type JSONSchemaDefinition = JSONSchema | boolean;
4004
+ export interface JSONSchema {
4005
+ $id?: string;
4006
+ $ref?: string;
4007
+ $schema?: JSONSchemaVersion;
4008
+ $comment?: string;
4009
+
4010
+ /**
4011
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1
4012
+ */
4013
+ type?: JSONSchemaTypeName | JSONSchemaTypeName[];
4014
+ enum?: JSONSchemaType[];
4015
+ const?: JSONSchemaType;
4016
+
4017
+ /**
4018
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.2
4019
+ */
4020
+ multipleOf?: number;
4021
+ maximum?: number;
4022
+ exclusiveMaximum?: number;
4023
+ minimum?: number;
4024
+ exclusiveMinimum?: number;
4025
+
4026
+ /**
4027
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.3
4028
+ */
4029
+ maxLength?: number;
4030
+ minLength?: number;
4031
+ pattern?: string;
4032
+
4033
+ /**
4034
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.4
4035
+ */
4036
+ items?: JSONSchemaDefinition | JSONSchemaDefinition[];
4037
+ additionalItems?: JSONSchemaDefinition;
4038
+ maxItems?: number;
4039
+ minItems?: number;
4040
+ uniqueItems?: boolean;
4041
+ contains?: JSONSchema;
4042
+
4043
+ /**
4044
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.5
4045
+ */
4046
+ maxProperties?: number;
4047
+ minProperties?: number;
4048
+ required?: string[];
4049
+ properties?: {
4050
+ [key: string]: JSONSchemaDefinition;
4051
+ };
4052
+ patternProperties?: {
4053
+ [key: string]: JSONSchemaDefinition;
4054
+ };
4055
+ additionalProperties?: JSONSchemaDefinition;
4056
+ dependencies?: {
4057
+ [key: string]: JSONSchemaDefinition | string[];
4058
+ };
4059
+ propertyNames?: JSONSchemaDefinition;
4060
+
4061
+ /**
4062
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.6
4063
+ */
4064
+ if?: JSONSchemaDefinition;
4065
+ then?: JSONSchemaDefinition;
4066
+ else?: JSONSchemaDefinition;
4067
+
4068
+ /**
4069
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.7
4070
+ */
4071
+ allOf?: JSONSchemaDefinition[];
4072
+ anyOf?: JSONSchemaDefinition[];
4073
+ oneOf?: JSONSchemaDefinition[];
4074
+ not?: JSONSchemaDefinition;
4075
+
4076
+ /**
4077
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-7
4078
+ */
4079
+ format?: string;
4080
+
4081
+ /**
4082
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-8
4083
+ */
4084
+ contentMediaType?: string;
4085
+ contentEncoding?: string;
4086
+
4087
+ /**
4088
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-9
4089
+ */
4090
+ definitions?: {
4091
+ [key: string]: JSONSchemaDefinition;
4092
+ };
4093
+
4094
+ /**
4095
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-10
4096
+ */
4097
+ title?: string;
4098
+ description?: string;
4099
+ default?: JSONSchemaType;
4100
+ readOnly?: boolean;
4101
+ writeOnly?: boolean;
4102
+ examples?: JSONSchemaType;
4103
+ }
4104
+ }