/
database.ts
350 lines (305 loc) · 8.58 KB
/
database.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/*
* @adonisjs/lucid
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import { Knex } from 'knex'
import { Exception } from '@poppinss/utils'
import {
DialectContract,
QueryClientContract,
TransactionClientContract,
} from '../../types/database.js'
import { DBQueryCallback, DatabaseQueryBuilderContract } from '../../types/querybuilder.js'
import { Chainable } from './chainable.js'
import { QueryRunner } from '../../query_runner/index.js'
import { SimplePaginator } from '../paginator/simple_paginator.js'
import * as errors from '../../errors.js'
/**
* Wrapping the user function for a query callback and give them
* a new instance of the `DatabaseQueryBuilder` and not
* knex.QueryBuilder
*/
const queryCallback: DBQueryCallback = (userFn, keysResolver) => {
return (builder: Knex.QueryBuilder) => {
/**
* Sub queries don't need the client, since client is used to execute the query
* and sub-queries are not executed separately. That's why we just pass
* an empty object.
*
* Other option is to have this method for each instance of the class, but this
* is waste of resources.
*/
const query = new DatabaseQueryBuilder(builder, {} as any, keysResolver)
userFn(query)
query['applyWhere']()
}
}
/**
* Database query builder exposes the API to construct and run queries for selecting,
* updating and deleting records.
*/
export class DatabaseQueryBuilder extends Chainable implements DatabaseQueryBuilderContract {
/**
* Custom data someone want to send to the profiler and the
* query event
*/
private customReporterData: any
/**
* Control whether to debug the query or not. The initial
* value is inherited from the query client
*/
private debugQueries: boolean
/**
* Required by macroable
*/
protected static macros = {}
protected static getters = {}
constructor(
builder: Knex.QueryBuilder,
public client: QueryClientContract,
public keysResolver?: (columnName: string) => string
) {
super(builder, queryCallback, keysResolver)
this.debugQueries = this.client.debug
}
/**
* Ensures that we are not executing `update` or `del` when using read only
* client
*/
private ensureCanPerformWrites() {
if (this.client && this.client.mode === 'read') {
throw new Exception('Updates and deletes cannot be performed in read mode')
}
}
/**
* Returns the log data
*/
private getQueryData() {
return {
connection: this.client.connectionName,
inTransaction: this.client.isTransaction,
...this.customReporterData,
}
}
/**
* Define custom reporter data. It will be merged with
* the existing data
*/
reporterData(data: any) {
this.customReporterData = data
return this
}
/**
* Delete rows under the current query
*/
del(returning?: string | string[]): this {
this.ensureCanPerformWrites()
returning ? this.knexQuery.del(returning) : this.knexQuery.del()
return this
}
/**
* Alias for [[del]]
*/
delete(returning?: string | string[]): this {
return this.del(returning)
}
/**
* Clone the current query builder
*/
clone(): DatabaseQueryBuilder {
const clonedQuery = new DatabaseQueryBuilder(this.knexQuery.clone(), this.client)
this.applyQueryFlags(clonedQuery)
clonedQuery.debug(this.debugQueries)
this.customReporterData && clonedQuery.reporterData(this.customReporterData)
return clonedQuery
}
/**
* Define returning columns
*/
returning(columns: any): this {
if (this.client.dialect.supportsReturningStatement) {
columns = Array.isArray(columns)
? columns.map((column) => this.resolveKey(column))
: this.resolveKey(columns)
this.knexQuery.returning(columns)
}
return this
}
/**
* Perform update by incrementing value for a given column. Increments
* can be clubbed with `update` as well
*/
increment(column: any, counter?: any): this {
this.ensureCanPerformWrites()
this.knexQuery.increment(this.resolveKey(column, true), counter)
return this
}
/**
* Perform update by decrementing value for a given column. Decrements
* can be clubbed with `update` as well
*/
decrement(column: any, counter?: any): this {
this.ensureCanPerformWrites()
this.knexQuery.decrement(this.resolveKey(column, true), counter)
return this
}
/**
* Perform update
*/
update(column: any, value?: any, returning?: string | string[]): this {
this.ensureCanPerformWrites()
if (value === undefined && returning === undefined) {
this.knexQuery.update(this.resolveKey(column, true))
} else if (returning === undefined) {
this.knexQuery.update(this.resolveKey(column), value)
} else {
this.knexQuery.update(this.resolveKey(column), value, returning)
}
return this
}
/**
* Fetch and return first results from the results set. This method
* will implicitly set a `limit` on the query
*/
async first(): Promise<any> {
const result = await this.limit(1)['exec']()
return result[0] || null
}
/**
* Fetch and return first results from the results set. This method
* will implicitly set a `limit` on the query
*/
async firstOrFail(): Promise<any> {
const row = await this.first()
if (!row) {
throw new errors.E_ROW_NOT_FOUND()
}
return row
}
/**
* Define a query to constraint to be defined when condition is truthy
*/
ifDialect(
dialects: DialectContract['name'] | DialectContract['name'][],
matchCallback: (query: this) => any,
noMatchCallback?: (query: this) => any
): this {
dialects = Array.isArray(dialects) ? dialects : [dialects]
if (dialects.includes(this.client.dialect.name)) {
matchCallback(this)
} else if (noMatchCallback) {
noMatchCallback(this)
}
return this
}
/**
* Define a query to constraint to be defined when condition is falsy
*/
unlessDialect(
dialects: DialectContract['name'] | DialectContract['name'][],
matchCallback: (query: this) => any,
noMatchCallback?: (query: this) => any
): this {
dialects = Array.isArray(dialects) ? dialects : [dialects]
if (!dialects.includes(this.client.dialect.name)) {
matchCallback(this)
} else if (noMatchCallback) {
noMatchCallback(this)
}
return this
}
/**
* Turn on/off debugging for this query
*/
debug(debug: boolean): this {
this.debugQueries = debug
return this
}
/**
* Define query timeout
*/
timeout(time: number, options?: { cancel: boolean }): this {
this.knexQuery['timeout'](time, options)
return this
}
/**
* Returns SQL query as a string
*/
toQuery(): string {
this.applyWhere()
return this.knexQuery.toQuery()
}
/**
* @deprecated
* Do not use this method. Instead create a query using the
* transaction client directly.
*
* ```ts
* trx.query()
* ```
*/
useTransaction(transaction: TransactionClientContract): this {
this.knexQuery.transacting(transaction.knexClient)
return this
}
/**
* Executes the query
*/
async exec(): Promise<any> {
this.applyWhere()
return new QueryRunner(this.client, this.debugQueries, this.getQueryData()).run(this.knexQuery)
}
/**
* Paginate through rows inside a given table
*/
async paginate(page: number, perPage: number = 20) {
/**
* Cast to number
*/
page = Number(page)
perPage = Number(perPage)
const countQuery = this.client
.query()
.from(this.clone().clearOrder().clearLimit().clearOffset().as('subQuery'))
.count('* as total')
const aggregates = await countQuery.exec()
const total = aggregates[0].total
const results = total > 0 ? await this.forPage(page, perPage).exec() : []
return new SimplePaginator(total, perPage, page, ...results)
}
/**
* Get sql representation of the query
*/
toSQL(): Knex.Sql {
this.applyWhere()
return this.knexQuery.toSQL()
}
/**
* Implementation of `then` for the promise API
*/
then(resolve: any, reject?: any): any {
return this.exec().then(resolve, reject)
}
/**
* Implementation of `catch` for the promise API
*/
catch(reject: any): any {
return this.exec().catch(reject)
}
/**
* Implementation of `finally` for the promise API
*/
finally(fulfilled: any) {
return this.exec().finally(fulfilled)
}
/**
* Required when Promises are extended
*/
get [Symbol.toStringTag]() {
return this.constructor.name
}
}