UNPKG

23.3 kBTypeScriptView Raw
1/// <reference types="node" />
2declare module '@ioc:Adonis/Lucid/Database' {
3 import { Knex } from 'knex';
4 import { DialectContract, QueryClientContract, TransactionClientContract } from '@ioc:Adonis/Lucid/Database';
5 /**
6 * Extracted from ts-essentials
7 */
8 type Dictionary<T, K extends string | number = string> = {
9 [key in K]: T;
10 };
11 /**
12 * Get one or many of a generic
13 */
14 type OneOrMany<T> = T | T[];
15 /**
16 * Allowing a generic value along with raw query instance or a subquery
17 * instance
18 */
19 type ValueWithSubQueries<T> = T | ChainableContract | RawQuery;
20 /**
21 * Acceptable raw queries
22 */
23 type RawQuery = RawBuilderContract | RawQueryBuilderContract | Knex.Raw | Knex.RawQueryBuilder;
24 /**
25 * A known set of values allowed when defining values for different
26 * clauses
27 */
28 type StrictValues = string | number | boolean | Date | Array<string> | Array<number> | Array<Date> | Array<boolean> | Buffer | RawQuery | ReferenceBuilderContract;
29 /**
30 * Strict set of allowed values except the raw queries
31 */
32 type StrictValuesWithoutRaw = Exclude<StrictValues, RawQuery>;
33 /**
34 * Shape of raw query bindings
35 */
36 type RawQueryBindings = {
37 [key: string]: StrictValues;
38 } | StrictValues[];
39 /**
40 * A builder method to allow raw queries. However, the return type is the
41 * instance of current query builder. This is used for `.{verb}Raw` methods.
42 */
43 interface RawQueryFn<Builder extends ChainableContract> {
44 (sql: string | RawQuery): Builder;
45 (sql: string, bindings: RawQueryBindings): Builder;
46 }
47 /**
48 * Query callback is used to write wrapped queries. We get rid of `this` from
49 * knex, since it makes everything confusing.
50 */
51 type QueryCallback<Builder> = (builder: Builder) => void;
52 /**
53 * Shape of the function accepted by the chainable query builder to
54 * pass lucid query builder to wrapped callbacks like
55 * `.where(function () {})`.
56 *
57 * - This method will accept the wrapped callback
58 * - Return a new method, that is accepted by Knex.
59 * - When knex calls that method, this method will invoke the user wrapped
60 * callback, but instead of passing the knex query builder, it will
61 * pass the appropriate lucid query builder.
62 */
63 type DBQueryCallback = (userFn: QueryCallback<ChainableContract>, keysResolver?: (columnName: string) => string) => (builder: Knex.QueryBuilder) => void;
64 /**
65 * Possible signatures for a select method on database query builder.
66 */
67 interface DatabaseQueryBuilderSelect<Builder extends ChainableContract> {
68 /**
69 * Selecting columns as a dictionary with key as the alias and value is
70 * the original column.
71 */
72 (columns: Dictionary<string, string>): Builder;
73 /**
74 * An array of values with subqueries
75 */
76 (columns: ValueWithSubQueries<string | number>[]): Builder;
77 /**
78 * A spread of array arguments
79 */
80 (...columns: ValueWithSubQueries<string | number>[]): Builder;
81 /**
82 * Wildcard selector.
83 */
84 (column: '*'): Builder;
85 }
86 /**
87 * Possible signatures for adding a where clause
88 */
89 interface Where<Builder extends ChainableContract> {
90 /**
91 * Callback for wrapped clauses
92 */
93 (callback: QueryCallback<Builder>): Builder;
94 /**
95 * Passing an object of named key-value pair
96 */
97 (clause: Dictionary<any, string>): Builder;
98 /**
99 * Key-value pair. The value can also be a subquery
100 */
101 (key: string | RawQuery, value: StrictValues | ChainableContract): Builder;
102 (key: string | RawQuery, operator: string, value: StrictValues | ChainableContract): Builder;
103 }
104 /**
105 * Possible signatures for adding a where column clause
106 */
107 interface WhereColumn<Builder extends ChainableContract> {
108 /**
109 * Key-value pair.
110 */
111 (column: string | RawQuery, comparisonColumn: string): Builder;
112 (column: string | RawQuery, operator: string, comparisonColumn: string): Builder;
113 }
114 /**
115 * Possible signatures for adding where in clause.
116 */
117 interface WhereIn<Builder extends ChainableContract> {
118 /**
119 * Column name and array of values
120 */
121 (K: string | RawQuery, value: StrictValues[]): Builder;
122 /**
123 * Column names and array of values as an 2d array
124 */
125 (K: string[], value: StrictValues[][]): Builder;
126 /**
127 * Column name with a subquery for a callback that yields an array of
128 * results
129 */
130 (k: string | RawQuery, subquery: ChainableContract | QueryCallback<Builder> | RawBuilderContract | RawQuery): Builder;
131 /**
132 * Column names along with a subquery that yields an array
133 */
134 (k: string[], subquery: ChainableContract | RawBuilderContract | RawQuery): Builder;
135 }
136 /**
137 * Possible signatures for adding whereNull clause.
138 */
139 interface WhereNull<Builder extends ChainableContract> {
140 (key: string | RawQuery): Builder;
141 }
142 /**
143 * Possibles signatures for adding a where exists clause
144 */
145 interface WhereExists<Builder extends ChainableContract> {
146 (callback: QueryCallback<Builder> | ChainableContract | RawBuilderContract | RawQuery): Builder;
147 }
148 /**
149 * Possibles signatures for adding a where between clause
150 */
151 interface WhereBetween<Builder extends ChainableContract> {
152 /**
153 * Accept any string as a key for supporting prefix columns
154 */
155 (key: string | RawQuery, value: [StrictValues | ChainableContract, StrictValues | ChainableContract]): Builder;
156 }
157 /**
158 * Possible signatures for join query
159 */
160 interface Join<Builder extends ChainableContract> {
161 /**
162 * Defining the join table with primary and secondary columns
163 * to match
164 */
165 (table: string, primaryColumn: string, secondaryColumn: string): Builder;
166 /**
167 * Defining the join table with primary and secondary columns
168 * to match, where secondary column is output of a raw query
169 */
170 (table: string, primaryColumn: string, raw: RawQuery): Builder;
171 /**
172 * Defining the join table with primary and secondary columns
173 * to match with a custom operator
174 */
175 (table: string, primaryColumn: string, operator: string, secondaryColumn: string): Builder;
176 /**
177 * Join with a callback. The callback receives an array of join class from
178 * knex directly.
179 */
180 (table: string, callback: Knex.JoinCallback): Builder;
181 }
182 /**
183 * Possible signatures for a distinct clause
184 */
185 interface Distinct<Builder extends ChainableContract> {
186 (columns: string[]): Builder;
187 (...columns: string[]): Builder;
188 (column: '*'): Builder;
189 }
190 /**
191 * The signatures are same as the `distinct` method. For subqueries and
192 * raw queries, one must use `groupByRaw`.
193 */
194 interface GroupBy<Builder extends ChainableContract> extends Distinct<Builder> {
195 }
196 /**
197 * Possible signatures for aggregate functions. Aggregates will push to the
198 * result set. Unlike knex, we force defining aliases for each aggregate.
199 */
200 interface Aggregate<Builder extends ChainableContract> {
201 /**
202 * Accepting column with the alias for the count.
203 */
204 (column: OneOrMany<ValueWithSubQueries<string>>, alias?: string): Builder;
205 /**
206 * Accepting an object for multiple counts in a single query.
207 */
208 (columns: Dictionary<OneOrMany<ValueWithSubQueries<string>>, string>): Builder;
209 }
210 /**
211 * Possible signatures for orderBy method.
212 */
213 interface OrderBy<Builder extends ChainableContract> {
214 /**
215 * Order by a column and optional direction
216 */
217 (column: string | ChainableContract | RawBuilderContract | RawQuery, direction?: 'asc' | 'desc'): Builder;
218 /**
219 * Order by multiple columns in default direction
220 */
221 (columns: string[]): Builder;
222 /**
223 * Order by multiple columns and custom direction for each of them
224 */
225 (columns: {
226 column: string | ChainableContract | RawBuilderContract | RawQuery;
227 order?: 'asc' | 'desc';
228 }[]): Builder;
229 }
230 /**
231 * Possible signatures for a union clause
232 */
233 interface Union<Builder extends ChainableContract> {
234 (callback: OneOrMany<QueryCallback<Builder>>, wrap?: boolean): Builder;
235 (subquery: OneOrMany<ChainableContract | RawQuery>, wrap?: boolean): Builder;
236 }
237 /**
238 * Same signature as union
239 */
240 interface UnionAll<Builder extends ChainableContract> extends Union<Builder> {
241 }
242 /**
243 * Same signature as union
244 */
245 interface Intersect<Builder extends ChainableContract> extends Union<Builder> {
246 }
247 /**
248 * Possible signatures for having clause
249 */
250 interface Having<Builder extends ChainableContract> {
251 /**
252 * A subquery callback
253 */
254 (callback: QueryCallback<Builder> | RawBuilderContract | RawQuery): Builder;
255 /**
256 * Key operator and value. Value can be a subquery as well
257 */
258 (key: string | RawQuery, operator: string, value: StrictValues | ChainableContract | RawBuilderContract | RawQuery): Builder;
259 }
260 /**
261 * Possible signatures for `having in` clause.
262 */
263 interface HavingIn<Builder extends ChainableContract> {
264 /**
265 * Key and an array of literal values, raw queries or
266 * subqueries.
267 */
268 (key: string | RawQuery, value: (StrictValues | ChainableContract | RawBuilderContract | RawQuery)[]): Builder;
269 /**
270 * Key, along with a query callback
271 */
272 (key: string | RawQuery, callback: QueryCallback<Builder>): Builder;
273 }
274 /**
275 * Possible signatures for `having null` clause
276 */
277 interface HavingNull<Builder extends ChainableContract> extends WhereNull<Builder> {
278 }
279 /**
280 * Possible signatures for `having exists` clause
281 */
282 interface HavingExists<Builder extends ChainableContract> {
283 /**
284 * A query callback or a sub query
285 */
286 (callback: QueryCallback<Builder> | ChainableContract): Builder;
287 }
288 /**
289 * Possible signatures for having between
290 */
291 interface HavingBetween<Builder extends ChainableContract> extends WhereBetween<Builder> {
292 }
293 /**
294 * Possible signatures of `with` CTE
295 */
296 interface With<Builder extends ChainableContract> {
297 (alias: string, query: RawQuery | ChainableContract | QueryCallback<Builder>): Builder;
298 }
299 /**
300 * Possible signatures for defining table for a select query.
301 */
302 interface FromTable<Builder extends ChainableContract> {
303 (table: string | Dictionary<string, string> | QueryCallback<Builder> | ChainableContract): Builder;
304 }
305 /**
306 * Possible signatures for the `returning` method.
307 */
308 interface Returning<Builder> {
309 (column: OneOrMany<string>): Builder;
310 }
311 /**
312 * Possible signatures for performing an update
313 */
314 interface Update<Builder extends ChainableContract> {
315 /**
316 * Accepts an array of object of named key/value pair and returns an array
317 * of Generic return columns.
318 */
319 (values: Dictionary<any, string>, returning?: OneOrMany<string>): Builder;
320 /**
321 * Accepts a key-value pair to update.
322 */
323 (column: string, value: any, returning?: OneOrMany<string>): Builder;
324 }
325 /**
326 * Possible signatures for incrementing/decrementing
327 * values
328 */
329 interface Counter<Builder extends ChainableContract> {
330 (column: string, counter?: number): Builder;
331 (values: Dictionary<number, string>): Builder;
332 }
333 /**
334 * Possible signatures for an insert query
335 */
336 interface Insert<Builder extends InsertQueryBuilderContract> {
337 (values: Dictionary<any, string>): Builder;
338 }
339 /**
340 * Possible signatures for doing multiple inserts in a single query
341 */
342 interface MultiInsert<Builder extends InsertQueryBuilderContract> {
343 (values: Dictionary<any, string>[]): Builder;
344 }
345 /**
346 * The chainable contract has all the methods that can be chained
347 * to build a query. This interface will never have any
348 * methods to execute a query.
349 */
350 interface ChainableContract {
351 knexQuery: Knex.QueryBuilder;
352 columns: (string | Knex.QueryBuilder | Knex.RawQueryBuilder)[];
353 subQueryAlias?: string;
354 hasAggregates: boolean;
355 hasGroupBy: boolean;
356 hasUnion: boolean;
357 keysResolver?: (columnName: string) => string;
358 from: FromTable<this>;
359 select: DatabaseQueryBuilderSelect<this>;
360 wrapExisting(): this;
361 where: Where<this>;
362 orWhere: Where<this>;
363 andWhere: Where<this>;
364 whereNot: Where<this>;
365 orWhereNot: Where<this>;
366 andWhereNot: Where<this>;
367 whereColumn: WhereColumn<this>;
368 orWhereColumn: WhereColumn<this>;
369 andWhereColumn: WhereColumn<this>;
370 whereNotColumn: WhereColumn<this>;
371 orWhereNotColumn: WhereColumn<this>;
372 andWhereNotColumn: WhereColumn<this>;
373 whereIn: WhereIn<this>;
374 orWhereIn: WhereIn<this>;
375 andWhereIn: WhereIn<this>;
376 whereNotIn: WhereIn<this>;
377 orWhereNotIn: WhereIn<this>;
378 andWhereNotIn: WhereIn<this>;
379 whereNull: WhereNull<this>;
380 orWhereNull: WhereNull<this>;
381 andWhereNull: WhereNull<this>;
382 whereNotNull: WhereNull<this>;
383 orWhereNotNull: WhereNull<this>;
384 andWhereNotNull: WhereNull<this>;
385 whereExists: WhereExists<this>;
386 orWhereExists: WhereExists<this>;
387 andWhereExists: WhereExists<this>;
388 whereNotExists: WhereExists<this>;
389 orWhereNotExists: WhereExists<this>;
390 andWhereNotExists: WhereExists<this>;
391 whereBetween: WhereBetween<this>;
392 orWhereBetween: WhereBetween<this>;
393 andWhereBetween: WhereBetween<this>;
394 whereNotBetween: WhereBetween<this>;
395 orWhereNotBetween: WhereBetween<this>;
396 andWhereNotBetween: WhereBetween<this>;
397 whereRaw: RawQueryFn<this>;
398 orWhereRaw: RawQueryFn<this>;
399 andWhereRaw: RawQueryFn<this>;
400 join: Join<this>;
401 innerJoin: Join<this>;
402 leftJoin: Join<this>;
403 leftOuterJoin: Join<this>;
404 rightJoin: Join<this>;
405 rightOuterJoin: Join<this>;
406 fullOuterJoin: Join<this>;
407 crossJoin: Join<this>;
408 joinRaw: RawQueryFn<this>;
409 having: Having<this>;
410 orHaving: Having<this>;
411 andHaving: Having<this>;
412 havingIn: HavingIn<this>;
413 orHavingIn: HavingIn<this>;
414 andHavingIn: HavingIn<this>;
415 havingNotIn: HavingIn<this>;
416 orHavingNotIn: HavingIn<this>;
417 andHavingNotIn: HavingIn<this>;
418 havingNull: HavingNull<this>;
419 orHavingNull: HavingNull<this>;
420 andHavingNull: HavingNull<this>;
421 havingNotNull: HavingNull<this>;
422 orHavingNotNull: HavingNull<this>;
423 andHavingNotNull: HavingNull<this>;
424 havingExists: HavingExists<this>;
425 orHavingExists: HavingExists<this>;
426 andHavingExists: HavingExists<this>;
427 havingNotExists: HavingExists<this>;
428 orHavingNotExists: HavingExists<this>;
429 andHavingNotExists: HavingExists<this>;
430 havingBetween: HavingBetween<this>;
431 orHavingBetween: HavingBetween<this>;
432 andHavingBetween: HavingBetween<this>;
433 havingNotBetween: HavingBetween<this>;
434 orHavingNotBetween: HavingBetween<this>;
435 andHavingNotBetween: HavingBetween<this>;
436 havingRaw: RawQueryFn<this>;
437 orHavingRaw: RawQueryFn<this>;
438 andHavingRaw: RawQueryFn<this>;
439 distinct: Distinct<this>;
440 distinctOn: Distinct<this>;
441 groupBy: GroupBy<this>;
442 groupByRaw: RawQueryFn<this>;
443 orderBy: OrderBy<this>;
444 orderByRaw: RawQueryFn<this>;
445 union: Union<this>;
446 unionAll: UnionAll<this>;
447 intersect: Intersect<this>;
448 with: With<this>;
449 withRecursive: With<this>;
450 withSchema(schema: string): this;
451 as(name: string): this;
452 offset(offset: number): this;
453 limit(limit: number): this;
454 clearSelect(): this;
455 clearWhere(): this;
456 clearOrder(): this;
457 clearHaving(): this;
458 clearLimit(): this;
459 clearOffset(): this;
460 forUpdate(...tableNames: string[]): this;
461 forShare(...tableNames: string[]): this;
462 skipLocked(): this;
463 noWait(): this;
464 /**
465 * Executes the callback when condition is truthy
466 */
467 if(condition: any, matchCallback: (query: this) => any, noMatchCallback?: (query: this) => any): this;
468 /**
469 * Executes the callback when condition is falsy
470 */
471 unless(condition: any, matchCallback: (query: this) => any, noMatchCallback?: (query: this) => any): this;
472 /**
473 * Write blocks to match from
474 */
475 match(...blocks: ([condition: any, callback: (query: this) => any] | ((query: this) => any))[]): this;
476 }
477 /**
478 * Shape of the raw query that can also be passed as a value to
479 * other queries
480 */
481 interface RawQueryBuilderContract<Result = any> extends ExcutableQueryBuilderContract<Result> {
482 knexQuery: Knex.Raw;
483 client: QueryClientContract;
484 wrap(before: string, after: string): this;
485 }
486 /**
487 * Reference builder
488 */
489 interface ReferenceBuilderContract {
490 withSchema(name: string): this;
491 as(name: string): this;
492 toKnex(client: Knex.Client): Knex.Ref<string, any>;
493 }
494 /**
495 * Static raw builder
496 */
497 interface RawBuilderContract {
498 wrap(before: string, after: string): this;
499 toKnex(client: Knex.Client): Knex.Raw;
500 }
501 /**
502 * The keys for the simple paginator meta
503 * data
504 */
505 type SimplePaginatorMetaKeys = {
506 total: string;
507 perPage: string;
508 currentPage: string;
509 lastPage: string;
510 firstPage: string;
511 firstPageUrl: string;
512 lastPageUrl: string;
513 nextPageUrl: string;
514 previousPageUrl: string;
515 };
516 /**
517 * Shape of the simple paginator that works with offset and limit
518 */
519 interface SimplePaginatorContract<Result> extends Array<Result> {
520 all(): Result[];
521 readonly firstPage: number;
522 readonly perPage: number;
523 readonly currentPage: number;
524 readonly lastPage: number;
525 readonly hasPages: boolean;
526 readonly hasMorePages: boolean;
527 readonly isEmpty: boolean;
528 readonly total: number;
529 readonly hasTotal: boolean;
530 namingStrategy: {
531 paginationMetaKeys(): SimplePaginatorMetaKeys;
532 };
533 baseUrl(url: string): this;
534 queryString(values: {
535 [key: string]: any;
536 }): this;
537 getUrl(page: number): string;
538 getMeta(): any;
539 getNextPageUrl(): string | null;
540 getPreviousPageUrl(): string | null;
541 getUrlsForRange(start: number, end: number): {
542 url: string;
543 page: number;
544 isActive: boolean;
545 }[];
546 toJSON(): {
547 meta: any;
548 data: Result[];
549 };
550 }
551 /**
552 * Database query builder exposes the API to construct SQL query using fluent
553 * chainable API
554 */
555 interface DatabaseQueryBuilderContract<Result = Dictionary<any, string>> extends ChainableContract, ExcutableQueryBuilderContract<Result[]> {
556 client: QueryClientContract;
557 returning: Returning<this>;
558 /**
559 * Clone current query
560 */
561 clone<ClonedResult = Result>(): DatabaseQueryBuilderContract<ClonedResult>;
562 /**
563 * Execute and get first result
564 */
565 first(): Promise<Result | null>;
566 /**
567 * Execute and get first result or fail
568 */
569 firstOrFail(): Promise<Result>;
570 /**
571 * Perform delete operation
572 */
573 del(returning?: OneOrMany<string>): this;
574 delete(returning?: OneOrMany<string>): this;
575 /**
576 * A shorthand to define limit and offset based upon the
577 * current page
578 */
579 forPage(page: number, perPage?: number): this;
580 /**
581 * Execute query with pagination
582 */
583 paginate(page: number, perPage?: number): Promise<SimplePaginatorContract<Result>>;
584 /**
585 * Mutations (update and increment can be one query aswell)
586 */
587 update: Update<this>;
588 increment: Counter<this>;
589 decrement: Counter<this>;
590 /**
591 * Aggregates
592 */
593 count: Aggregate<this>;
594 countDistinct: Aggregate<this>;
595 min: Aggregate<this>;
596 max: Aggregate<this>;
597 sum: Aggregate<this>;
598 sumDistinct: Aggregate<this>;
599 avg: Aggregate<this>;
600 avgDistinct: Aggregate<this>;
601 /**
602 * Executes the callback when dialect matches one of the mentioned
603 * dialects
604 */
605 ifDialect(dialect: DialectContract['name'] | DialectContract['name'][], matchCallback: (query: this) => any, noMatchCallback?: (query: this) => any): this;
606 /**
607 * Executes the callback when dialect matches doesn't all the mentioned
608 * dialects
609 */
610 unlessDialect(dialect: DialectContract['name'] | DialectContract['name'][], matchCallback: (query: this) => any, noMatchCallback?: (query: this) => any): this;
611 }
612 /**
613 * Insert query builder to perform database inserts.
614 */
615 interface InsertQueryBuilderContract<Result = any> extends ExcutableQueryBuilderContract<Result> {
616 knexQuery: Knex.QueryBuilder;
617 client: QueryClientContract;
618 /**
619 * Table for the insert query
620 */
621 table(table: string): this;
622 withSchema(schema: string): this;
623 /**
624 * Define returning columns
625 */
626 returning: Returning<this>;
627 /**
628 * Inserting a single record.
629 */
630 insert: Insert<this>;
631 /**
632 * Inserting multiple columns at once
633 */
634 multiInsert: MultiInsert<this>;
635 }
636 /**
637 * A executable query builder will always have these methods on it.
638 */
639 interface ExcutableQueryBuilderContract<Result> extends Promise<Result> {
640 debug(debug: boolean): this;
641 timeout(time: number, options?: {
642 cancel: boolean;
643 }): this;
644 useTransaction(trx: TransactionClientContract): this;
645 reporterData(data: any): this;
646 toQuery(): string;
647 exec(): Promise<Result>;
648 toSQL(): Knex.Sql;
649 }
650}
651
\No newline at end of file