forked from rahmanfadhil/cotton
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquerybuilder.ts
545 lines (458 loc) · 13 KB
/
querybuilder.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
import type {
Adapter,
DatabaseResult,
DatabaseValues,
} from "./adapters/adapter.ts";
import { QueryCompiler } from "./querycompiler.ts";
import { Q } from "./q.ts";
/**
* Combine WHERE operators with OR or NOT
*/
export enum WhereType {
Or = 1,
Not = 2,
Default = 3,
}
/**
* ORDER BY directions
*/
export type OrderDirection = "DESC" | "ASC";
/**
* WHERE clause informations
*/
export interface WhereBinding {
column: string;
expression: Q;
type: WhereType;
}
/**
* ORDER BY clause informations
*/
interface OrderBinding {
column: string;
order: OrderDirection;
}
/**
* Valid query types
*/
export enum QueryType {
Select = 1,
Insert = 2,
Delete = 3,
Update = 4,
Replace = 5,
}
export enum JoinType {
Inner = 1,
Full = 2,
Left = 3,
Right = 4,
}
interface JoinBinding {
table: string;
type: JoinType;
columnA: string;
columnB: string;
}
export interface CountBinding {
columns: string[];
as?: string;
distinct: boolean;
}
/**
* Query values for INSERT and UPDATE
*/
export type QueryValues = {
[key: string]: DatabaseValues;
};
/**
* All information about the query
*/
export interface QueryDescription {
/** The table which the query is targeting */
tableName: string;
/** Query type */
type: QueryType;
/** Table columns that are going to be fetched */
columns: (string | [string, string])[];
/** Query values for INSERT and UPDATE */
values?: QueryValues | QueryValues[];
/** The where constraints of the query */
wheres: WhereBinding[];
/** The orderings for the query */
orders: OrderBinding[];
/** The maximum number of records to return */
limit?: number;
/** The number of records to skip */
offset?: number;
/** Values to be returned by the query */
returning: string[];
/** Tables to be joined */
joins: JoinBinding[];
/** Count records with given conditions */
counts: CountBinding[];
/** Check if the SELECT statement is using DISTINCT keyword */
isDistinct: boolean;
/** The having clauses in the query */
havings: WhereBinding[];
/** Group records by column */
groupBy: string[];
}
/**
* Allows to build complex SQL queries and execute those queries.
*/
export class QueryBuilder {
private description: QueryDescription;
// --------------------------------------------------------------------------------
// CONSTRUCTOR
// --------------------------------------------------------------------------------
constructor(
/** The table which the query is targeting */
tableName: string,
/** The database adapter to perform query */
private adapter: Adapter,
) {
this.description = {
tableName,
type: QueryType.Select,
columns: [],
wheres: [],
orders: [],
returning: [],
joins: [],
counts: [],
havings: [],
groupBy: [],
isDistinct: false,
};
}
// --------------------------------------------------------------------------------
// PUBLIC QUERY METHODS
// --------------------------------------------------------------------------------
/**
* Add basic WHERE clause to query
*
* @param column the table column name
* @param value the expected value
*/
public where(column: string, value: DatabaseValues): QueryBuilder;
/**
* Add basic WHERE clause to query with custom query expression.
*
* @param column the table column name
* @param expresion a custom SQL expression to filter the records
*/
public where(column: string, expression: Q): QueryBuilder;
/** Add basic WHERE clause to query */
public where(column: string, expression: DatabaseValues | Q): QueryBuilder {
this.description.wheres.push({
column,
expression: expression instanceof Q ? expression : Q.eq(expression),
type: WhereType.Default,
});
return this;
}
/**
* Add WHERE NOT clause to query
*
* @param column the table column name
* @param value the expected value
*/
public not(column: string, value: DatabaseValues): QueryBuilder;
/**
* Add WHERE NOT clause to query with custom query expression.
*
* @param column the table column name
* @param expresion a custom SQL expression to filter the records
*/
public not(column: string, expression: Q): QueryBuilder;
/** Add WHERE NOT clause to query */
public not(column: string, expression: DatabaseValues | Q): QueryBuilder {
this.description.wheres.push({
column,
expression: expression instanceof Q ? expression : Q.eq(expression),
type: WhereType.Not,
});
return this;
}
/**
* Add WHERE ... OR clause to query
*
* @param column the table column name
* @param value the expected value
*/
public or(column: string, value: DatabaseValues): QueryBuilder;
/**
* Add WHERE ... OR clause to query with custom query expression.
*
* @param column the table column name
* @param expresion a custom SQL expression to filter the records
*/
public or(column: string, expression: Q): QueryBuilder;
/** Add WHERE ... OR clause to query */
public or(column: string, expression: DatabaseValues | Q): QueryBuilder {
this.description.wheres.push({
column,
expression: expression instanceof Q ? expression : Q.eq(expression),
type: WhereType.Or,
});
return this;
}
/**
* Select table columns
*
* @param columns table columns to select
*/
public select(...columns: (string | [string, string])[]): QueryBuilder {
this.description.columns = this.description.columns.concat(columns);
return this;
}
/**
* Set the "limit" value for the query.
*
* @param limit Maximum number of records
*/
public limit(limit: number): QueryBuilder {
if (limit >= 0) {
this.description.limit = limit;
}
return this;
}
/**
* Set the "offset" value for the query.
*
* @param offset Numbers of records to skip
*/
public offset(offset: number): QueryBuilder {
if (offset > 0) {
this.description.offset = offset;
}
return this;
}
/**
* Get the first record of the query, shortcut for `limit(1)`
*/
public first(): QueryBuilder {
return this.limit(1);
}
/**
* Add an "order by" clause to the query.
*
* @param column Table field
* @param direction "ASC" or "DESC"
*/
public order(
column: string,
direction: OrderDirection = "ASC",
): QueryBuilder {
this.description.orders.push({ column, order: direction });
return this;
}
/**
* Add SQL HAVING clause to query
*
* @param column the table column name
* @param value the expected value
*/
public having(column: string, value: DatabaseValues): QueryBuilder;
/**
* Add SQL HAVING clause to query with custom query expression.
*
* @param column the table column name
* @param expresion a custom SQL expression to filter the records
*/
public having(column: string, expression: Q): QueryBuilder;
/** Add SQL HAVING clause to query */
public having(column: string, expression: DatabaseValues | Q): QueryBuilder {
this.description.havings.push({
column,
expression: expression instanceof Q ? expression : Q.eq(expression),
type: WhereType.Default,
});
return this;
}
/**
* Group records by a column
*
* @param columns the table columns to group
*/
public groupBy(...columns: string[]) {
this.description.groupBy = this.description.groupBy.concat(columns);
return this;
}
/**
* Sets the returning value for the query.
*
* @param columns Table column name
*/
public returning(...columns: string[]): QueryBuilder {
this.description.returning = this.description.returning.concat(columns);
return this;
}
// --------------------------------------------------------------------------------
// CREATE, UPDATE, DELETE
// --------------------------------------------------------------------------------
/**
* Insert a record to the table
*
* @param data A JSON Object representing columnname-value pairs. Example: { firstname: "John", age: 22, ... }
*/
public insert(data: QueryValues | QueryValues[]): QueryBuilder {
// Change the query type from `select` (default) to `insert`
this.description.type = QueryType.Insert;
// Set the query values
this.description.values = data;
return this;
}
/**
* Perform `REPLACE` query to the table.
*
* It will look for `PRIMARY` and `UNIQUE` constraints.
* If something matched, it gets removed from the table
* and creates a new row with the given values.
*
* @param data A JSON Object representing columnname-value pairs. Example: { firstname: "John", age: 22, ... }
*/
public replace(data: QueryValues): QueryBuilder {
// Change the query type from `select` (default) to `replace`
this.description.type = QueryType.Replace;
// Set the query values
this.description.values = data;
return this;
}
/**
* Update record on the database
*
* @param data A JSON Object representing columnname-value pairs. Example: { firstname: "John", age: 22, ... }
*/
public update(data: QueryValues): QueryBuilder {
// Change the query type from `select` (default) to `update`
this.description.type = QueryType.Update;
// Set the query values
this.description.values = data;
return this;
}
/**
* Delete record from the database.
*/
public delete(): QueryBuilder {
this.description.type = QueryType.Delete;
return this;
}
// --------------------------------------------------------------------------------
// AGGREGATE
// --------------------------------------------------------------------------------
/**
* Count records with given conditions
*
* @param column the column(s) you want to count
* @param as the alias for the count result
*/
public count(column: string | string[], as?: string): QueryBuilder {
// Initialize the count information
const info: CountBinding = {
columns: Array.isArray(column) ? column : [column],
distinct: false,
};
// If the alias of this clause is defined, add it to `info`
if (typeof as === "string" && as.length >= 1) info.as = as;
// Add information to the query description
this.description.counts.push(info);
return this;
}
/**
* Count records with unique values
*
* @param columns the unique column(s) you want to count
* @param as the alias for the count result
*/
public countDistinct(column: string | string[], as?: string): QueryBuilder {
// Initialize the count information
const info: CountBinding = {
columns: Array.isArray(column) ? column : [column],
distinct: true,
};
// If the alias of this clause is defined, add it to `data`
if (typeof as === "string" && as.length >= 1) info.as = as;
// Add information to the query description
this.description.counts.push(info);
return this;
}
/**
* Force the query to return distinct (unique) results.
*/
public distinct(): QueryBuilder {
this.description.isDistinct = true;
return this;
}
// --------------------------------------------------------------------------------
// JOINS
// --------------------------------------------------------------------------------
/** SQL INNER JOIN */
public innerJoin(table: string, a: string, b: string): QueryBuilder {
this.description.joins.push({
type: JoinType.Inner,
table,
columnA: a,
columnB: b,
});
return this;
}
/** SQL FULL OUTER JOIN */
public fullJoin(table: string, a: string, b: string): QueryBuilder {
this.description.joins.push({
type: JoinType.Full,
table,
columnA: a,
columnB: b,
});
return this;
}
/** SQL LEFT OUTER JOIN */
public leftJoin(table: string, a: string, b: string): QueryBuilder {
this.description.joins.push({
type: JoinType.Left,
table,
columnA: a,
columnB: b,
});
return this;
}
/** SQL RIGHT OUTER JOIN */
public rightJoin(table: string, a: string, b: string): QueryBuilder {
this.description.joins.push({
type: JoinType.Right,
table,
columnA: a,
columnB: b,
});
return this;
}
// --------------------------------------------------------------------------------
// PERFORM QUERY
// --------------------------------------------------------------------------------
/**
* Execute query and get the result
*
* @param adapter Custom database adapter
*/
public async execute(adapter?: Adapter): Promise<DatabaseResult[]> {
let currentAdapter = adapter || this.adapter;
if (!currentAdapter) {
throw new Error("Cannot run query, adapter is not provided!");
}
const { text, values } = this.toSQL();
return currentAdapter.query(text, values);
}
/**
* Get the actual SQL query string. All the data are replaced by a placeholder.
* So, you need to also bind the values in order to execute the query.
*/
public toSQL() {
const { text, values } = new QueryCompiler(
this.description,
this.adapter.dialect,
).compile();
return { text, values };
}
}