-
Notifications
You must be signed in to change notification settings - Fork 0
/
QueryBuilder.ts
124 lines (101 loc) · 2.26 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
import {MysqlTranslator} from "./translators/MysqlTranslator.ts";
export interface IWhere {
field: string;
operator: string;
value: string | number;
}
export class QueryBuilder<T> {
private _table: string;
private _wheres: Array<IWhere>;
private _isSingle: boolean;
private _isCount: boolean;
private _type: string; // insert | select | update | delete
private _fieldsToUpdateOrInsert: any;
private _selects: Array<string>;
private db: any;
constructor(tableName: string, db: any) {
this._table = tableName;
this.db = db;
this._wheres = [];
this._isSingle = false;
this._type = "select";
this._fieldsToUpdateOrInsert = [];
this._selects = [];
this._isCount = false;
}
single() {
this._isSingle = true;
return this;
}
count() {
this._isCount = true;
return this;
}
select(selects: Array<string>) {
this._selects = selects;
return this;
}
reset() {
this._wheres = [];
this._isSingle = false;
this._type = "select";
this._fieldsToUpdateOrInsert = [];
this._isCount = false;
}
where(fieldOrFields: string, whereOperator: string, whereValue: string) {
this._type = "select";
this._wheres.push({
field: fieldOrFields,
operator: whereOperator,
value: whereValue,
} as IWhere);
return this;
}
delete() {
this._type = "delete";
return this;
}
update(fieldsToUpdate: T) {
this._type = "update";
this._fieldsToUpdateOrInsert = fieldsToUpdate;
return this;
}
insert(fields: any) {
this._type = "insert";
this._fieldsToUpdateOrInsert = fields;
return this;
}
sql(sql = "") {
if (sql != "") {
return sql;
}
return new MysqlTranslator<T>(this).translate();
}
query() {
return this.sql();
}
isSingle(): boolean {
return this._isSingle;
}
isCount(): boolean {
return this._isCount;
}
get wheres(): Array<IWhere> {
return this._wheres;
}
get type(): string {
return this._type;
}
get selects(): Array<string> {
return this._selects;
}
get fieldsToUpdateOrInsert(): any {
return this._fieldsToUpdateOrInsert;
}
get table(): string {
return this._table;
}
set wheres(value: Array<IWhere>) {
this._wheres = value;
}
}