forked from Interactions-as-a-Service/d1-orm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
queryBuilder.ts
229 lines (222 loc) · 7.01 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
/**
* @enum {string} - The type of the query
*/
export enum QueryType {
SELECT = "SELECT",
INSERT = "INSERT",
INSERT_OR_REPLACE = "INSERT or REPLACE",
UPDATE = "UPDATE",
DELETE = "DELETE",
UPSERT = "UPSERT",
}
/**
* @param _
* **where** - The where clause for the query. This is an object with the column names as keys and the values as values.
*
* **limit** - The limit for the query. This is the maximum number of rows to return.
*
* **offset** - The offset for the query. This is the number of rows to skip before returning.
*
* **orderBy** - The order by clause for the query. See {@link OrderBy} for more information.
*
* **data** - The data to insert, or update with. This is an object with the column names as keys and the values as values. In the case of Upsert, `upsertOnlyUpdateData` is also required, and that will be the data to update with, if an `ON CONFLICT` clause is matched.
*
* **upsertOnlyUpdateData** - The data to update with, if an `ON CONFLICT` clause is matched. This is an object with the column names as keys and the values as values.
* @typeParam T - The type of the object to query. This is generally not needed to be specified, but can be useful if you're calling this yourself instead of through a {@link Model}.
*/
export type GenerateQueryOptions<T extends object> = {
where?: Partial<T>;
limit?: number;
offset?: number;
orderBy?: OrderBy<T> | OrderBy<T>[];
data?: Partial<T>;
upsertOnlyUpdateData?: Partial<T>;
};
/**
* @typeParam T - The type of the object to query. This is generally not needed to be specified, but can be useful if you're calling this yourself instead of through a {@link Model}.
* ```ts
* {
* // Any of these are valid
* orderBy: 'id',
* orderBy: ['id', 'name'],
* orderBy: { column: 'id', descending: true, nullLast: true },
* orderBy: [{ column: 'id', descending: true, nullLast: true }, { column: 'name', descending: false, nullLast: false }],
* }
* ```
*/
export type OrderBy<T extends object> =
| keyof T
| { column: keyof T; descending: boolean; nullLast?: boolean };
/**
* @param type - The type of query to generate, see {@link QueryType}
* @param tableName - The table to query
* @param options - The options for the query, see {@link GenerateQueryOptions}
* @typeParam T - The type of the object to query. This is generally not needed to be specified, but can be useful if you're calling this yourself instead of through a {@link Model}.
* @returns The query and bindings to be executed
*/
export function GenerateQuery<T extends object>(
type: QueryType,
tableName: string,
options: GenerateQueryOptions<T> = {},
primaryKeys: string | string[] = "id"
): { bindings: unknown[]; query: string } {
if (typeof tableName !== "string" || !tableName.length) {
throw new Error("Invalid table name");
}
let query = "";
const bindings: unknown[] = [];
switch (type) {
case QueryType.SELECT: {
query = `SELECT * FROM \`${tableName}\``;
if (options.where) {
const whereStmt = [];
for (const [key, value] of Object.entries(options.where)) {
whereStmt.push(`${key} = ?`);
bindings.push(coerceTypedValue(value));
}
if (whereStmt.length) query += ` WHERE ${whereStmt.join(" AND ")}`;
}
if (options.orderBy) {
query += " ORDER BY " + transformOrderBy(options.orderBy);
}
if (options.limit) {
query += ` LIMIT ${options.limit}`;
if (options.offset) {
query += ` OFFSET ${options.offset}`;
}
}
break;
}
case QueryType.DELETE: {
query = `DELETE FROM \`${tableName}\``;
if (options.where) {
const whereStmt = [];
for (const [key, value] of Object.entries(options.where)) {
whereStmt.push(`${key} = ?`);
bindings.push(coerceTypedValue(value));
}
if (whereStmt.length) query += ` WHERE ${whereStmt.join(" AND ")}`;
}
break;
}
case QueryType.INSERT_OR_REPLACE:
case QueryType.INSERT: {
query = `${type} INTO \`${tableName}\``;
if (
typeof options.data !== "object" ||
Object.getOwnPropertyNames(options.data).length === 0
) {
throw new Error("Must provide data to insert");
}
const keys = [];
for (const [key, value] of Object.entries(options.data)) {
keys.push(key);
bindings.push(coerceTypedValue(value));
}
query += ` (${keys.join(", ")}) VALUES (${"?"
.repeat(keys.length)
.split("")
.join(", ")})`;
break;
}
case QueryType.UPDATE: {
query = `UPDATE \`${tableName}\``;
if (
typeof options.data !== "object" ||
Object.getOwnPropertyNames(options.data).length === 0
) {
throw new Error("Must provide data to update");
}
const keys = [];
for (const [key, value] of Object.entries(options.data)) {
keys.push(`${key} = ?`);
bindings.push(coerceTypedValue(value));
}
query += ` SET ${keys.join(", ")}`;
if (options.where) {
const whereStmt = [];
for (const [key, value] of Object.entries(options.where)) {
whereStmt.push(`${key} = ?`);
bindings.push(coerceTypedValue(value));
}
if (whereStmt.length) query += ` WHERE ${whereStmt.join(" AND ")}`;
}
break;
}
case QueryType.UPSERT: {
const insertDataKeys = Object.keys(options.data ?? {});
const updateDataKeys = Object.keys(options.upsertOnlyUpdateData ?? {});
const whereKeys = Object.keys(options.where ?? {});
bindings.push(
...Object.values(options.data ?? {}),
...Object.values(options.upsertOnlyUpdateData ?? {}),
...Object.values(options.where ?? {})
);
coerceTypedValues(bindings);
if (
insertDataKeys.length === 0 ||
updateDataKeys.length === 0 ||
whereKeys.length === 0
) {
throw new Error(
"Must provide data to insert with, data to update with, and where keys in Upsert"
);
}
query = `INSERT INTO \`${tableName}\` (${insertDataKeys.join(", ")})`;
query += ` VALUES (${"?"
.repeat(insertDataKeys.length)
.split("")
.join(", ")})`;
const primaryKeyStr = Array.isArray(primaryKeys)
? primaryKeys.join(", ")
: primaryKeys;
query += ` ON CONFLICT (${primaryKeyStr}) DO UPDATE SET`;
query += ` ${updateDataKeys.map((key) => `${key} = ?`).join(", ")}`;
query += ` WHERE ${whereKeys.map((key) => `${key} = ?`).join(" AND ")}`;
break;
}
default:
throw new Error("Invalid QueryType provided");
}
return {
query,
bindings,
};
}
/** @hidden */
export function coerceTypedValues(list: Array<unknown>) {
for (let i = 0; i < list.length; i++) {
list[i] = coerceTypedValue(list[i]);
}
}
/** @hidden */
export function coerceTypedValue(value: unknown) {
if (typeof value === "boolean") {
return value ? 1 : 0;
} else {
return value;
}
}
/**
* @private
* @hidden
*/
export function transformOrderBy<T extends object>(
orderBy: OrderBy<T> | OrderBy<T>[]
): string {
if (Array.isArray(orderBy)) {
return orderBy.map(transformOrderBy).join(", ");
}
if (
typeof orderBy === "string" ||
typeof orderBy === "symbol" ||
typeof orderBy === "number"
) {
return `"${String(orderBy)}"`;
}
return (
`"${String(orderBy.column)}"` +
(orderBy.descending ? " DESC" : "") +
(orderBy.nullLast ? " NULLS LAST" : "")
);
}