-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathmanager.ts
333 lines (288 loc) · 9.67 KB
/
manager.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
import {
compareWithOriginal,
getPrimaryKeyInfo,
getRelationValues,
getTableName,
getValues,
isSaved,
mapValueProperties,
setSaved,
} from "./utils/models.ts";
import type { Adapter } from "./adapters/adapter.ts";
import { range } from "./utils/number.ts";
import { RelationType } from "./model.ts";
import { ModelQuery } from "./modelquery.ts";
import { Q } from "./q.ts";
/**
* Same as Partial<T> but goes deeper and makes Partial<T> all its properties and sub-properties.
*/
export type DeepPartial<T> = {
[P in keyof T]?: T[P] extends Array<infer U> ? Array<DeepPartial<U>>
: T[P] extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>
: DeepPartial<T[P]>;
};
/**
* Query options to find a single record.
*/
export interface FindOneOptions<T> {
where?: DeepPartial<T>;
includes?: string[];
}
/**
* Query options to find multiple records.
*/
export type FindOptions<T> = FindOneOptions<T> & {
limit?: number;
offset?: number;
};
/**
* Manager allows you to perform queries to your model.
*/
export class Manager {
/**
* Create a model manager.
*
* @param adapter the database adapter to perform queries
*/
constructor(private adapter: Adapter) {}
/**
* Query a model.
*
* @param modelClass the model you want to query
*/
public query<T extends Object>(modelClass: { new (): T }): ModelQuery<T> {
return new ModelQuery(modelClass, this.adapter);
}
/**
* Save model a instance to the database.
*
* @param model the model you want to save
*/
public async save<T extends Object>(model: T): Promise<T>;
/**
* Save model instances to the database.
*
* @param models the models you want to save
*/
public async save<T extends Object>(models: T[]): Promise<T[]>;
/**
* Save model instance to the database.
*
* @param model the model you want to save
*/
public async save<T extends Object>(model: T | T[]): Promise<T | T[]> {
// If an Array of models is passed, perform INSERT in bulk.
// Otherwise, check if the model is already saved to the
// database or not. If it is, perform update instead of
if (Array.isArray(model)) {
// We wrap everything in transaction, this will undo every
// changes in the database if one of the queries fail.
await this.adapter.transaction(async () => {
// We need to group the models by it's constructor first
// in order to perform bulk insert.
for (const [key, value] of this.groupModels(model)) {
const insert: T[] = [];
// If one of the models is already saved, perform UPDATE.
for (const data of value) {
!data.isSaved
? insert.push(data.model)
: await this.update(data.model);
}
await this.bulkInsert(key, insert);
}
});
} else {
// If the record is saved, we assume that the user want to update the record.
// Otherwise, create a new record to the database.
isSaved(model)
? await this.update(model)
: await this.bulkInsert(model.constructor, [model]);
}
return model;
}
/**
* Remove given model instance from the database.
*
* @param model the model you want to remove.
*/
public async remove<T extends Object>(model: T): Promise<T>;
/**
* Remove given model instaces from the database.
*
* @param model the model you want to remove.
*/
public async remove<T extends Object>(model: T[]): Promise<T[]>;
/**
* Remove given model from the database.
*
* @param model the model you want to remove.
*/
public async remove<T extends Object>(model: T | T[]): Promise<T | T[]> {
if (Array.isArray(model)) {
// Just like save, wrap everything in transaction. This will undo
// every changes in the database if one of the queries fail.
await this.adapter.transaction(async () => {
for (const [key, value] of this.groupModels(model).entries()) {
const tableName = getTableName(key);
const primaryKeyInfo = getPrimaryKeyInfo(key);
// Holds the primary keys of the models to delete.
const ids: number[] = [];
// Holds the model instances to clear it's original values.
const models: T[] = [];
// Only delete saved models.
for (const item of value) {
if (item.isSaved) {
ids.push((item.model as any)[primaryKeyInfo.propertyKey]);
models.push(item.model);
}
}
// Perform bulk delete.
await this.adapter
.table(tableName)
.where(primaryKeyInfo.name, Q.in(ids))
.delete()
.execute();
// Set the `isSaved` value to be false on each models
// and remove their original values.
for (const item of models) {
delete (item as any)[primaryKeyInfo.propertyKey];
setSaved(item, false);
}
}
});
} else {
const tableName = getTableName(model.constructor);
const primaryKeyInfo = getPrimaryKeyInfo(model.constructor);
// Only remove model if it's already saved
if (isSaved(model)) {
const id = (model as any)[primaryKeyInfo.propertyKey];
await this.adapter
.table(tableName)
.where(primaryKeyInfo.name, id)
.delete()
.execute();
// Remove the primary key
delete (model as any)[primaryKeyInfo.propertyKey];
// Set the `isSaved` value to be false and remove the original values
setSaved(model, false);
}
}
return model;
}
/**
* Perform update to a model.
*
* @param model the model you want to update.
*/
private async update<T extends Object>(model: T): Promise<T> {
const tableName = getTableName(model.constructor);
const primaryKeyInfo = getPrimaryKeyInfo(model.constructor);
const { isDirty, diff } = compareWithOriginal(model);
if (isDirty) {
await this.adapter
.table(tableName)
.where(
primaryKeyInfo.name,
(model as any)[primaryKeyInfo.propertyKey],
)
.update(diff)
.execute();
// Save the model's original values
setSaved(model, true);
}
return model;
}
/**
* Group models by its constructor.
*/
private groupModels<T extends Object>(models: T[]) {
return models.reduce((prev, next, index) => {
const previousModels = prev.get(next.constructor);
const data = { model: next, index, isSaved: isSaved(next) };
prev.set(
next.constructor,
previousModels ? previousModels.concat(data) : [data],
);
return prev;
}, new Map<Function, { model: T; index: number; isSaved: boolean }[]>());
}
/**
* Insert multiple records to the database efficiently
*/
private async bulkInsert<T extends Object>(
modelClass: Function,
models: T[],
): Promise<T[]> {
const tableName = getTableName(modelClass);
const primaryKeyInfo = getPrimaryKeyInfo(modelClass);
// Get all model values
const values = models.map((model) => {
const values = getValues(model);
// If there's a belongs to relationship, add it to the INSERT statement
for (const relation of getRelationValues(model)) {
if (relation.description.type === RelationType.BelongsTo) {
values[relation.description.targetColumn] = relation.value as number;
}
}
return values;
});
// Execute query
const query = this.adapter.table(tableName).insert(values);
// The postgres adapter doesn't have any equivalient `lastInsertedId` property.
// So, we need to manually return the primary key.
if (this.adapter.dialect === "postgres") {
query.returning(primaryKeyInfo.name);
}
// Execute the query
const result = await query.execute();
// Get last inserted id
const lastInsertedId = this.adapter.dialect === "postgres"
? result[result.length - 1][primaryKeyInfo.name] as number
: this.adapter.lastInsertedId;
// Set the model primary keys
const ids = range(
lastInsertedId + 1 - models.length,
lastInsertedId,
);
// Assign values to the models
for (const [index, model] of models.entries()) {
// Get the models values that has been sent to the database
// and map column names from `name` to `propertyKey`.
const value = mapValueProperties(
model.constructor,
values[index],
"propertyKey",
);
// Set the primary key
value[primaryKeyInfo.propertyKey] = ids[index];
// Populate empty properties with default value
Object.assign(model, value);
// If there's a has many relationship, update the foreign key
for (const relation of getRelationValues(model)) {
if (relation.description.type === RelationType.HasMany) {
const ids = relation.value as number[];
const tableName = getTableName(relation.description.getModel());
const relationPkInfo = getPrimaryKeyInfo(
relation.description.getModel(),
);
await this.adapter
.table(tableName)
.update({
[relation.description.targetColumn]:
(model as any)[primaryKeyInfo.propertyKey],
})
.where(relationPkInfo.name, Q.in(ids))
.execute();
for (let i = 0; i < ids.length; i++) {
(model as any)[relation.description.propertyKey][i][
relation.description.targetColumn
] = (model as any)[primaryKeyInfo.propertyKey];
}
}
}
// Update the `isSaved` status and save the original values
setSaved(model, true);
}
return models;
}
}