@h3ravel/arquebus 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -5
- package/bin/index.cjs +1 -4948
- package/bin/index.js +1 -4923
- package/dist/browser/index.cjs +1 -1424
- package/dist/browser/index.d.cts +73 -14
- package/dist/browser/index.d.ts +73 -14
- package/dist/browser/index.js +1 -1359
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +1449 -0
- package/dist/index.d.ts +72 -12
- package/dist/index.js +1 -4723
- package/package.json +4 -2
package/dist/index.js
CHANGED
|
@@ -1,4723 +1 @@
|
|
|
1
|
-
// src/casts/attribute.ts
|
|
2
|
-
var Attribute = class _Attribute {
|
|
3
|
-
get;
|
|
4
|
-
set;
|
|
5
|
-
withCaching = false;
|
|
6
|
-
withObjectCaching = true;
|
|
7
|
-
constructor({
|
|
8
|
-
get: get2 = null,
|
|
9
|
-
set: set2 = null
|
|
10
|
-
}) {
|
|
11
|
-
this.get = get2;
|
|
12
|
-
this.set = set2;
|
|
13
|
-
}
|
|
14
|
-
static make({ get: get2 = null, set: set2 = null }) {
|
|
15
|
-
return new _Attribute({ get: get2, set: set2 });
|
|
16
|
-
}
|
|
17
|
-
static get(get2) {
|
|
18
|
-
return new _Attribute({ get: get2 });
|
|
19
|
-
}
|
|
20
|
-
static set(set2) {
|
|
21
|
-
return new _Attribute({ set: set2 });
|
|
22
|
-
}
|
|
23
|
-
withoutObjectCaching() {
|
|
24
|
-
this.withObjectCaching = false;
|
|
25
|
-
return this;
|
|
26
|
-
}
|
|
27
|
-
shouldCache() {
|
|
28
|
-
this.withCaching = true;
|
|
29
|
-
return this;
|
|
30
|
-
}
|
|
31
|
-
};
|
|
32
|
-
var attribute_default = Attribute;
|
|
33
|
-
|
|
34
|
-
// src/errors.ts
|
|
35
|
-
import { isArray } from "radashi";
|
|
36
|
-
var BaseError = class extends Error {
|
|
37
|
-
constructor(message, _entity) {
|
|
38
|
-
super(message);
|
|
39
|
-
Error.captureStackTrace(this, this.constructor);
|
|
40
|
-
this.name = this.constructor.name;
|
|
41
|
-
this.message = message;
|
|
42
|
-
}
|
|
43
|
-
};
|
|
44
|
-
var ModelNotFoundError = class extends BaseError {
|
|
45
|
-
model;
|
|
46
|
-
ids = [];
|
|
47
|
-
constructor() {
|
|
48
|
-
super("");
|
|
49
|
-
}
|
|
50
|
-
setModel(model, ids = []) {
|
|
51
|
-
this.model = model;
|
|
52
|
-
this.ids = isArray(ids) ? ids : [ids];
|
|
53
|
-
this.message = `No query results for model [${model}]`;
|
|
54
|
-
if (this.ids.length > 0) {
|
|
55
|
-
this.message += " " + this.ids.join(", ");
|
|
56
|
-
} else {
|
|
57
|
-
this.message += ".";
|
|
58
|
-
}
|
|
59
|
-
return this;
|
|
60
|
-
}
|
|
61
|
-
getModel() {
|
|
62
|
-
return this.model;
|
|
63
|
-
}
|
|
64
|
-
getIds() {
|
|
65
|
-
return this.ids;
|
|
66
|
-
}
|
|
67
|
-
};
|
|
68
|
-
var RelationNotFoundError = class extends BaseError {
|
|
69
|
-
};
|
|
70
|
-
var InvalidArgumentError = class extends BaseError {
|
|
71
|
-
};
|
|
72
|
-
|
|
73
|
-
// src/builder.ts
|
|
74
|
-
import { diff as difference4, flat as flatten2, isArray as isArray5, isString, assign as merge2, omit as omit5, snake as snake2 } from "radashi";
|
|
75
|
-
|
|
76
|
-
// src/utils.ts
|
|
77
|
-
import { camel, dash, snake, trim } from "radashi";
|
|
78
|
-
import advancedFormat from "dayjs/plugin/advancedFormat.js";
|
|
79
|
-
import dayjs from "dayjs";
|
|
80
|
-
dayjs.extend(advancedFormat);
|
|
81
|
-
var now = (format = "YYYY-MM-DD HH:mm:ss") => dayjs().format(format);
|
|
82
|
-
var getRelationName = (relationMethod) => {
|
|
83
|
-
return snake(relationMethod.substring(8));
|
|
84
|
-
};
|
|
85
|
-
var getScopeName = (scopeMethod) => {
|
|
86
|
-
return snake(scopeMethod.substring(5));
|
|
87
|
-
};
|
|
88
|
-
var getRelationMethod = (relation) => {
|
|
89
|
-
return camel(`relation_${relation}`);
|
|
90
|
-
};
|
|
91
|
-
var getScopeMethod = (scope) => {
|
|
92
|
-
return camel(`scope_${scope}`);
|
|
93
|
-
};
|
|
94
|
-
var getAttrMethod = (attr) => {
|
|
95
|
-
return camel(`attribute_${attr}`);
|
|
96
|
-
};
|
|
97
|
-
var getGetterMethod = (attr) => {
|
|
98
|
-
return camel(`get_${attr}_attribute`);
|
|
99
|
-
};
|
|
100
|
-
var getSetterMethod = (attr) => {
|
|
101
|
-
return camel(`set_${attr}_attribute`);
|
|
102
|
-
};
|
|
103
|
-
var getAttrName = (attrMethod) => {
|
|
104
|
-
return attrMethod.substring(3, attrMethod.length - 9).toLowerCase();
|
|
105
|
-
};
|
|
106
|
-
var tap = (instance, callback) => {
|
|
107
|
-
const result = callback(instance);
|
|
108
|
-
return result instanceof Promise ? result.then(() => instance) : instance;
|
|
109
|
-
};
|
|
110
|
-
function compose(Base, ...mixins) {
|
|
111
|
-
return mixins.reduce((acc, mixin) => mixin(acc), Base);
|
|
112
|
-
}
|
|
113
|
-
var flattenDeep = (arr) => Array.isArray(arr) ? arr.reduce((a, b) => a.concat(flattenDeep(b)), []) : [arr];
|
|
114
|
-
var kebabCase = (str) => trim(dash(str.replace(/[^a-zA-Z0-9_-]/g, "-")), "_-");
|
|
115
|
-
var snakeCase = (str) => trim(snake(str.replace(/[^a-zA-Z0-9_-]/g, "-")), "_-");
|
|
116
|
-
var defineConfig = (config) => {
|
|
117
|
-
return config;
|
|
118
|
-
};
|
|
119
|
-
|
|
120
|
-
// src/builder.ts
|
|
121
|
-
import { Collection as BaseCollection2 } from "collect.js";
|
|
122
|
-
|
|
123
|
-
// src/relations/belongs-to-many.ts
|
|
124
|
-
import { isEqual, omit as omit4 } from "radashi";
|
|
125
|
-
|
|
126
|
-
// src/collection.ts
|
|
127
|
-
import { Collection as BaseCollection, collect as collect5 } from "collect.js";
|
|
128
|
-
import { diff as difference2, isArray as isArray3, isEmpty, omit as omit3, pick } from "radashi";
|
|
129
|
-
|
|
130
|
-
// src/relations/relation.ts
|
|
131
|
-
var Relation = class {
|
|
132
|
-
query;
|
|
133
|
-
parent;
|
|
134
|
-
related;
|
|
135
|
-
eagerKeysWereEmpty = false;
|
|
136
|
-
static constraints = true;
|
|
137
|
-
static selfJoinCount = 0;
|
|
138
|
-
constructor(query, parent) {
|
|
139
|
-
this.query = query;
|
|
140
|
-
this.parent = parent;
|
|
141
|
-
this.related = this.query.model;
|
|
142
|
-
}
|
|
143
|
-
static extend(trait) {
|
|
144
|
-
for (const methodName in trait) {
|
|
145
|
-
this.prototype[methodName] = trait[methodName];
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
static noConstraints(callback) {
|
|
149
|
-
const previous = this.constraints;
|
|
150
|
-
this.constraints = false;
|
|
151
|
-
try {
|
|
152
|
-
return callback();
|
|
153
|
-
} finally {
|
|
154
|
-
this.constraints = previous;
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
asProxy() {
|
|
158
|
-
const handler = {
|
|
159
|
-
get: function(target, prop) {
|
|
160
|
-
if (typeof target[prop] !== "undefined") {
|
|
161
|
-
return target[prop];
|
|
162
|
-
}
|
|
163
|
-
if (typeof prop === "string") {
|
|
164
|
-
if (typeof target.query[prop] === "function") {
|
|
165
|
-
return (...args) => {
|
|
166
|
-
target.query[prop](...args);
|
|
167
|
-
return target.asProxy();
|
|
168
|
-
};
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
};
|
|
173
|
-
return new Proxy(this, handler);
|
|
174
|
-
}
|
|
175
|
-
getRelated() {
|
|
176
|
-
return this.related;
|
|
177
|
-
}
|
|
178
|
-
getKeys(models, key) {
|
|
179
|
-
return models.map((model) => key ? model.attributes[key] : model.getKey()).sort();
|
|
180
|
-
}
|
|
181
|
-
getRelationQuery() {
|
|
182
|
-
return this.query;
|
|
183
|
-
}
|
|
184
|
-
whereInEager(whereIn, key, modelKeys, query = null) {
|
|
185
|
-
(query || this.query)[whereIn](key, modelKeys);
|
|
186
|
-
if (modelKeys.length === 0) {
|
|
187
|
-
this.eagerKeysWereEmpty = true;
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
whereInMethod(model, key) {
|
|
191
|
-
return "whereIn";
|
|
192
|
-
const segments = key.split(".");
|
|
193
|
-
return model.getKeyName() === segments.pop() && ["int", "integer"].includes(model.getKeyType()) ? "whereIntegerInRaw" : "whereIn";
|
|
194
|
-
}
|
|
195
|
-
getEager() {
|
|
196
|
-
return this.eagerKeysWereEmpty ? this.query.getModel().newCollection() : this.get();
|
|
197
|
-
}
|
|
198
|
-
async get(columns = ["*"]) {
|
|
199
|
-
return await this.query.get(columns);
|
|
200
|
-
}
|
|
201
|
-
async first(columns = ["*"]) {
|
|
202
|
-
return await this.query.first(columns);
|
|
203
|
-
}
|
|
204
|
-
async paginate(...args) {
|
|
205
|
-
return await this.query.paginate(...args);
|
|
206
|
-
}
|
|
207
|
-
async count(...args) {
|
|
208
|
-
return await this.query.clearSelect().count(...args);
|
|
209
|
-
}
|
|
210
|
-
toSql() {
|
|
211
|
-
return this.query.toSql();
|
|
212
|
-
}
|
|
213
|
-
addConstraints() {
|
|
214
|
-
}
|
|
215
|
-
getRelationCountHash(incrementJoinCount = true) {
|
|
216
|
-
return "arquebus_reserved_" + (incrementJoinCount ? this.constructor.selfJoinCount++ : this.constructor.selfJoinCount);
|
|
217
|
-
}
|
|
218
|
-
getRelationExistenceQuery(query, parentQuery, columns = ["*"]) {
|
|
219
|
-
return query.select(columns).whereColumn(this.getQualifiedParentKeyName(), "=", this.getExistenceCompareKey());
|
|
220
|
-
}
|
|
221
|
-
getRelationExistenceCountQuery(query, parentQuery) {
|
|
222
|
-
const db = this.related.getConnection();
|
|
223
|
-
return this.getRelationExistenceQuery(query, parentQuery, db.raw("count(*)"));
|
|
224
|
-
}
|
|
225
|
-
getQualifiedParentKeyName() {
|
|
226
|
-
return this.parent.getQualifiedKeyName();
|
|
227
|
-
}
|
|
228
|
-
getExistenceCompareKey() {
|
|
229
|
-
return this.getQualifiedForeignKeyName?.();
|
|
230
|
-
}
|
|
231
|
-
};
|
|
232
|
-
var relation_default = Relation;
|
|
233
|
-
|
|
234
|
-
// src/relations/concerns/supports-default-models.ts
|
|
235
|
-
var SupportsDefaultModels = (Relation2) => {
|
|
236
|
-
return class extends Relation2 {
|
|
237
|
-
_withDefault;
|
|
238
|
-
withDefault(callback = true) {
|
|
239
|
-
this._withDefault = callback;
|
|
240
|
-
return this;
|
|
241
|
-
}
|
|
242
|
-
getDefaultFor(parent) {
|
|
243
|
-
if (!this._withDefault) {
|
|
244
|
-
return null;
|
|
245
|
-
}
|
|
246
|
-
const instance = this.newRelatedInstanceFor(parent);
|
|
247
|
-
if (typeof this._withDefault === "function") {
|
|
248
|
-
return this._withDefault(instance, parent) || instance;
|
|
249
|
-
}
|
|
250
|
-
if (typeof this._withDefault === "object") {
|
|
251
|
-
for (const key in this._withDefault) {
|
|
252
|
-
instance.setAttribute(key, this._withDefault[key]);
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
return instance;
|
|
256
|
-
}
|
|
257
|
-
};
|
|
258
|
-
};
|
|
259
|
-
var supports_default_models_default = SupportsDefaultModels;
|
|
260
|
-
|
|
261
|
-
// src/relations/belongs-to.ts
|
|
262
|
-
var BelongsTo = class extends compose(relation_default, supports_default_models_default) {
|
|
263
|
-
foreignKey;
|
|
264
|
-
ownerKey;
|
|
265
|
-
child;
|
|
266
|
-
relationName;
|
|
267
|
-
constructor(query, child, foreignKey, ownerKey, relationName) {
|
|
268
|
-
super(query, child);
|
|
269
|
-
this.foreignKey = foreignKey;
|
|
270
|
-
this.ownerKey = ownerKey;
|
|
271
|
-
this.child = child;
|
|
272
|
-
this.relationName = relationName;
|
|
273
|
-
this.addConstraints();
|
|
274
|
-
return this.asProxy();
|
|
275
|
-
}
|
|
276
|
-
async getResults() {
|
|
277
|
-
if (this.child[this.foreignKey] === null) {
|
|
278
|
-
return this.getDefaultFor(this.parent);
|
|
279
|
-
}
|
|
280
|
-
const result = await this.query.first();
|
|
281
|
-
return result || this.getDefaultFor(this.parent);
|
|
282
|
-
}
|
|
283
|
-
match(models, results, relation) {
|
|
284
|
-
const foreign = this.foreignKey;
|
|
285
|
-
const owner = this.ownerKey;
|
|
286
|
-
const dictionary = {};
|
|
287
|
-
results.map((result) => {
|
|
288
|
-
const attribute = result.attributes[owner];
|
|
289
|
-
dictionary[attribute] = result;
|
|
290
|
-
});
|
|
291
|
-
models.map((model) => {
|
|
292
|
-
const attribute = model[foreign];
|
|
293
|
-
if (dictionary[attribute] !== void 0) {
|
|
294
|
-
model.setRelation(relation, dictionary[attribute]);
|
|
295
|
-
}
|
|
296
|
-
});
|
|
297
|
-
return models;
|
|
298
|
-
}
|
|
299
|
-
getQualifiedForeignKeyName() {
|
|
300
|
-
return this.child.qualifyColumn(this.foreignKey);
|
|
301
|
-
}
|
|
302
|
-
getRelationExistenceQuery(query, parentQuery, columns = ["*"]) {
|
|
303
|
-
if (parentQuery.getQuery()._single.table === query.getQuery()._single.table) {
|
|
304
|
-
return this.getRelationExistenceQueryForSelfRelation(query, parentQuery, columns);
|
|
305
|
-
}
|
|
306
|
-
return query.select(columns).whereColumn(this.getQualifiedForeignKeyName(), "=", query.qualifyColumn(this.ownerKey));
|
|
307
|
-
}
|
|
308
|
-
getRelationExistenceQueryForSelfRelation(query, parentQuery, columns = ["*"]) {
|
|
309
|
-
const hash = this.getRelationCountHash();
|
|
310
|
-
query.select(columns).from(query.getModel().getTable() + " as " + hash);
|
|
311
|
-
query.getModel().setTable(hash);
|
|
312
|
-
return query.whereColumn(`${hash}.${this.ownerKey}`, "=", this.getQualifiedForeignKeyName());
|
|
313
|
-
}
|
|
314
|
-
initRelation(models, relation) {
|
|
315
|
-
models.forEach((model) => {
|
|
316
|
-
model.setRelation(relation, this.getDefaultFor(model));
|
|
317
|
-
});
|
|
318
|
-
return models;
|
|
319
|
-
}
|
|
320
|
-
addEagerConstraints(models) {
|
|
321
|
-
const key = `${this.related.getTable()}.${this.ownerKey}`;
|
|
322
|
-
this.query.whereIn(key, this.getEagerModelKeys(models));
|
|
323
|
-
}
|
|
324
|
-
getEagerModelKeys(models) {
|
|
325
|
-
const keys = [];
|
|
326
|
-
models.forEach((model) => {
|
|
327
|
-
const value = model[this.foreignKey];
|
|
328
|
-
if (value !== null && value !== void 0) {
|
|
329
|
-
keys.push(value);
|
|
330
|
-
}
|
|
331
|
-
});
|
|
332
|
-
keys.sort();
|
|
333
|
-
return [...new Set(keys)];
|
|
334
|
-
}
|
|
335
|
-
associate(model) {
|
|
336
|
-
const ownerKey = model instanceof Model ? model.attributes[this.ownerKey] : model;
|
|
337
|
-
this.child[this.foreignKey] = ownerKey;
|
|
338
|
-
if (model instanceof Model) {
|
|
339
|
-
this.child.setRelation(this.relationName, model);
|
|
340
|
-
} else {
|
|
341
|
-
this.child.unsetRelation(this.relationName);
|
|
342
|
-
}
|
|
343
|
-
return this.child;
|
|
344
|
-
}
|
|
345
|
-
dissociate() {
|
|
346
|
-
this.child[this.foreignKey] = null;
|
|
347
|
-
return this.child.setRelation(this.relationName, null);
|
|
348
|
-
}
|
|
349
|
-
addConstraints() {
|
|
350
|
-
if (this.constructor.constraints) {
|
|
351
|
-
const table = this.related.getTable();
|
|
352
|
-
this.query.where(`${table}.${this.ownerKey}`, "=", this.child[this.foreignKey]);
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
newRelatedInstanceFor(_parent) {
|
|
356
|
-
return this.related.newInstance();
|
|
357
|
-
}
|
|
358
|
-
};
|
|
359
|
-
var belongs_to_default = BelongsTo;
|
|
360
|
-
|
|
361
|
-
// src/concerns/has-attributes.ts
|
|
362
|
-
import { flat as flatten, omit } from "radashi";
|
|
363
|
-
|
|
364
|
-
// src/casts-attributes.ts
|
|
365
|
-
var CastsAttributes = class _CastsAttributes {
|
|
366
|
-
constructor() {
|
|
367
|
-
if (this.constructor === _CastsAttributes) {
|
|
368
|
-
throw new Error("CastsAttributes cannot be instantiated");
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
|
-
static get(_model, _key, _value, _attributes) {
|
|
372
|
-
throw new Error("get not implemented");
|
|
373
|
-
}
|
|
374
|
-
static set(_model, _key, _value, _attributes) {
|
|
375
|
-
throw new Error("set not implemented");
|
|
376
|
-
}
|
|
377
|
-
};
|
|
378
|
-
var casts_attributes_default = CastsAttributes;
|
|
379
|
-
|
|
380
|
-
// src/concerns/has-attributes.ts
|
|
381
|
-
import collect from "collect.js";
|
|
382
|
-
import dayjs2 from "dayjs";
|
|
383
|
-
var HasAttributes = (Model2) => {
|
|
384
|
-
return class extends Model2 {
|
|
385
|
-
static castTypeCache = {};
|
|
386
|
-
attributes = {};
|
|
387
|
-
original = {};
|
|
388
|
-
casts = {};
|
|
389
|
-
changes = {};
|
|
390
|
-
appends = [];
|
|
391
|
-
setAppends(appends) {
|
|
392
|
-
this.appends = appends;
|
|
393
|
-
return this;
|
|
394
|
-
}
|
|
395
|
-
append(...keys) {
|
|
396
|
-
const appends = flattenDeep(keys);
|
|
397
|
-
this.appends = [...this.appends, ...appends];
|
|
398
|
-
return this;
|
|
399
|
-
}
|
|
400
|
-
normalizeCastClassResponse(key, value) {
|
|
401
|
-
return value?.constructor?.name === "Object" ? value : {
|
|
402
|
-
[key]: value
|
|
403
|
-
};
|
|
404
|
-
}
|
|
405
|
-
syncOriginal() {
|
|
406
|
-
this.original = this.getAttributes();
|
|
407
|
-
return this;
|
|
408
|
-
}
|
|
409
|
-
syncChanges() {
|
|
410
|
-
this.changes = this.getDirty();
|
|
411
|
-
return this;
|
|
412
|
-
}
|
|
413
|
-
syncOriginalAttribute(attribute) {
|
|
414
|
-
this.syncOriginalAttributes(attribute);
|
|
415
|
-
}
|
|
416
|
-
syncOriginalAttributes(...attributes) {
|
|
417
|
-
attributes = flattenDeep(attributes);
|
|
418
|
-
const modelAttributes = this.getAttributes();
|
|
419
|
-
for (const attribute of attributes) {
|
|
420
|
-
this.original[attribute] = modelAttributes[attribute];
|
|
421
|
-
}
|
|
422
|
-
return this;
|
|
423
|
-
}
|
|
424
|
-
isDirty(...attributes) {
|
|
425
|
-
const changes = this.getDirty();
|
|
426
|
-
attributes = flattenDeep(attributes);
|
|
427
|
-
if (attributes.length === 0) {
|
|
428
|
-
return Object.keys(changes).length > 0;
|
|
429
|
-
}
|
|
430
|
-
for (const attribute of attributes) {
|
|
431
|
-
if (attribute in changes) {
|
|
432
|
-
return true;
|
|
433
|
-
}
|
|
434
|
-
}
|
|
435
|
-
return false;
|
|
436
|
-
}
|
|
437
|
-
getDirty() {
|
|
438
|
-
const dirty = {};
|
|
439
|
-
const attributes = this.getAttributes();
|
|
440
|
-
for (const key in attributes) {
|
|
441
|
-
const value = attributes[key];
|
|
442
|
-
if (!this.originalIsEquivalent(key)) {
|
|
443
|
-
dirty[key] = value;
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
return dirty;
|
|
447
|
-
}
|
|
448
|
-
originalIsEquivalent(key) {
|
|
449
|
-
if (this.original[key] === void 0) {
|
|
450
|
-
return false;
|
|
451
|
-
}
|
|
452
|
-
const attribute = this.attributes[key];
|
|
453
|
-
const original = this.original[key];
|
|
454
|
-
if (attribute === original) {
|
|
455
|
-
return true;
|
|
456
|
-
} else {
|
|
457
|
-
return false;
|
|
458
|
-
}
|
|
459
|
-
}
|
|
460
|
-
setAttributes(attributes) {
|
|
461
|
-
this.attributes = { ...attributes };
|
|
462
|
-
}
|
|
463
|
-
setRawAttributes(attributes, sync = false) {
|
|
464
|
-
this.attributes = attributes;
|
|
465
|
-
if (sync) {
|
|
466
|
-
this.syncOriginal();
|
|
467
|
-
}
|
|
468
|
-
return this;
|
|
469
|
-
}
|
|
470
|
-
getAttributes() {
|
|
471
|
-
return { ...this.attributes };
|
|
472
|
-
}
|
|
473
|
-
setAttribute(key, value) {
|
|
474
|
-
const setterMethod = getSetterMethod(key);
|
|
475
|
-
if (typeof this[setterMethod] === "function") {
|
|
476
|
-
this[setterMethod](value);
|
|
477
|
-
return this;
|
|
478
|
-
}
|
|
479
|
-
const attrMethod = getAttrMethod(key);
|
|
480
|
-
if (typeof this[attrMethod] === "function") {
|
|
481
|
-
const attribute = this[attrMethod]();
|
|
482
|
-
const callback = attribute.set || ((value2) => {
|
|
483
|
-
this.attributes[key] = value2;
|
|
484
|
-
});
|
|
485
|
-
this.attributes = {
|
|
486
|
-
...this.attributes,
|
|
487
|
-
...this.normalizeCastClassResponse(key, callback(value, this.attributes))
|
|
488
|
-
};
|
|
489
|
-
return this;
|
|
490
|
-
}
|
|
491
|
-
const casts = this.getCasts();
|
|
492
|
-
const castType = casts[key];
|
|
493
|
-
if (this.isCustomCast(castType) && typeof castType !== "string") {
|
|
494
|
-
value = castType.set(this, key, value, this.attributes) ?? "";
|
|
495
|
-
}
|
|
496
|
-
if (castType === "json") {
|
|
497
|
-
value = JSON.stringify(value);
|
|
498
|
-
}
|
|
499
|
-
if (castType === "collection") {
|
|
500
|
-
value = JSON.stringify(value);
|
|
501
|
-
}
|
|
502
|
-
if (value !== null && this.isDateAttribute(key)) {
|
|
503
|
-
value = this.fromDateTime(value);
|
|
504
|
-
}
|
|
505
|
-
this.attributes[key] = value;
|
|
506
|
-
return this;
|
|
507
|
-
}
|
|
508
|
-
getAttribute(key) {
|
|
509
|
-
if (!key) {
|
|
510
|
-
return;
|
|
511
|
-
}
|
|
512
|
-
const getterMethod = getGetterMethod(key);
|
|
513
|
-
if (typeof this[getterMethod] === "function") {
|
|
514
|
-
return this[getterMethod](this.attributes[key], this.attributes);
|
|
515
|
-
}
|
|
516
|
-
const attrMethod = getAttrMethod(key);
|
|
517
|
-
if (typeof this[attrMethod] === "function") {
|
|
518
|
-
const caster = this[attrMethod]();
|
|
519
|
-
return caster.get(this.attributes[key], this.attributes);
|
|
520
|
-
}
|
|
521
|
-
if (key in this.attributes) {
|
|
522
|
-
if (this.hasCast(key)) {
|
|
523
|
-
return this.castAttribute(key, this.attributes[key]);
|
|
524
|
-
}
|
|
525
|
-
if (this.getDates().includes(key)) {
|
|
526
|
-
return this.asDateTime(this.attributes[key]);
|
|
527
|
-
}
|
|
528
|
-
return this.attributes[key];
|
|
529
|
-
}
|
|
530
|
-
if (key in this.relations) {
|
|
531
|
-
return this.relations[key];
|
|
532
|
-
}
|
|
533
|
-
return;
|
|
534
|
-
}
|
|
535
|
-
castAttribute(key, value) {
|
|
536
|
-
const castType = this.getCastType(key);
|
|
537
|
-
if (!castType) {
|
|
538
|
-
return value;
|
|
539
|
-
}
|
|
540
|
-
if (value === null) {
|
|
541
|
-
return value;
|
|
542
|
-
}
|
|
543
|
-
switch (castType) {
|
|
544
|
-
case "int":
|
|
545
|
-
case "integer":
|
|
546
|
-
return parseInt(value);
|
|
547
|
-
case "real":
|
|
548
|
-
case "float":
|
|
549
|
-
case "double":
|
|
550
|
-
return parseFloat(value);
|
|
551
|
-
case "decimal":
|
|
552
|
-
return this.asDecimal(value, castType.split(":")[1]);
|
|
553
|
-
case "string":
|
|
554
|
-
return String(value);
|
|
555
|
-
case "bool":
|
|
556
|
-
case "boolean":
|
|
557
|
-
return Boolean(value);
|
|
558
|
-
case "object":
|
|
559
|
-
case "json":
|
|
560
|
-
try {
|
|
561
|
-
return JSON.parse(value);
|
|
562
|
-
} catch {
|
|
563
|
-
return null;
|
|
564
|
-
}
|
|
565
|
-
case "collection":
|
|
566
|
-
try {
|
|
567
|
-
return collect(JSON.parse(value));
|
|
568
|
-
} catch {
|
|
569
|
-
return collect([]);
|
|
570
|
-
}
|
|
571
|
-
case "date":
|
|
572
|
-
return this.asDate(value);
|
|
573
|
-
case "datetime":
|
|
574
|
-
case "custom_datetime":
|
|
575
|
-
return this.asDateTime(value);
|
|
576
|
-
case "timestamp":
|
|
577
|
-
return this.asTimestamp(value);
|
|
578
|
-
}
|
|
579
|
-
if (this.isCustomCast(castType)) {
|
|
580
|
-
return castType.get(this, key, value, this.attributes);
|
|
581
|
-
}
|
|
582
|
-
return value;
|
|
583
|
-
}
|
|
584
|
-
attributesToData() {
|
|
585
|
-
let attributes = { ...this.attributes };
|
|
586
|
-
for (const key in attributes) {
|
|
587
|
-
if (this.hidden.includes(key)) {
|
|
588
|
-
attributes = omit(attributes, [key]);
|
|
589
|
-
}
|
|
590
|
-
if (this.visible.length > 0 && this.visible.includes(key) === false) {
|
|
591
|
-
attributes = omit(attributes, [key]);
|
|
592
|
-
}
|
|
593
|
-
}
|
|
594
|
-
for (const key of this.getDates()) {
|
|
595
|
-
if (attributes[key] === void 0) {
|
|
596
|
-
continue;
|
|
597
|
-
}
|
|
598
|
-
attributes[key] = this.serializeDate(this.asDateTime(attributes[key]));
|
|
599
|
-
}
|
|
600
|
-
const casts = this.getCasts();
|
|
601
|
-
for (const key in casts) {
|
|
602
|
-
const value = casts[key];
|
|
603
|
-
if (key in attributes === false) {
|
|
604
|
-
continue;
|
|
605
|
-
}
|
|
606
|
-
attributes[key] = this.castAttribute(key, attributes[key]);
|
|
607
|
-
if (key in attributes && ["date", "datetime"].includes(String(value))) {
|
|
608
|
-
attributes[key] = this.serializeDate(attributes[key]);
|
|
609
|
-
}
|
|
610
|
-
if (key in attributes && this.isCustomDateTimeCast(value)) {
|
|
611
|
-
attributes[key] = dayjs2(attributes[key]).format(String(value).split(":")[1]);
|
|
612
|
-
}
|
|
613
|
-
}
|
|
614
|
-
for (const key of this.appends) {
|
|
615
|
-
attributes[key] = this.mutateAttribute(key, null);
|
|
616
|
-
}
|
|
617
|
-
return attributes;
|
|
618
|
-
}
|
|
619
|
-
mutateAttribute(key, value) {
|
|
620
|
-
if (typeof this[getGetterMethod(key)] === "function") {
|
|
621
|
-
return this[getGetterMethod(key)](value);
|
|
622
|
-
} else if (typeof this[getAttrMethod(key)] === "function") {
|
|
623
|
-
const caster = this[getAttrMethod(key)]();
|
|
624
|
-
return caster.get(key, this.attributes);
|
|
625
|
-
} else if (key in this) {
|
|
626
|
-
return this[key];
|
|
627
|
-
}
|
|
628
|
-
return value;
|
|
629
|
-
}
|
|
630
|
-
mutateAttributeForArray(_key, _value) {
|
|
631
|
-
}
|
|
632
|
-
isDateAttribute(key) {
|
|
633
|
-
return this.getDates().includes(key) || this.isDateCastable(key);
|
|
634
|
-
}
|
|
635
|
-
serializeDate(date) {
|
|
636
|
-
return date ? dayjs2(date).toISOString() : null;
|
|
637
|
-
}
|
|
638
|
-
getDates() {
|
|
639
|
-
return this.usesTimestamps() ? [
|
|
640
|
-
this.getCreatedAtColumn(),
|
|
641
|
-
this.getUpdatedAtColumn()
|
|
642
|
-
] : [];
|
|
643
|
-
}
|
|
644
|
-
getCasts() {
|
|
645
|
-
if (this.getIncrementing()) {
|
|
646
|
-
return {
|
|
647
|
-
[this.getKeyName()]: this.getKeyType(),
|
|
648
|
-
...this.casts
|
|
649
|
-
};
|
|
650
|
-
}
|
|
651
|
-
return this.casts;
|
|
652
|
-
}
|
|
653
|
-
getCastType(key) {
|
|
654
|
-
const castType = this.getCasts()[key];
|
|
655
|
-
let castTypeCacheKey;
|
|
656
|
-
if (typeof castType === "string") {
|
|
657
|
-
castTypeCacheKey = castType;
|
|
658
|
-
} else if (new castType() instanceof casts_attributes_default) {
|
|
659
|
-
castTypeCacheKey = castType.name;
|
|
660
|
-
}
|
|
661
|
-
if (castTypeCacheKey && this.getConstructor().castTypeCache[castTypeCacheKey] !== void 0) {
|
|
662
|
-
return this.getConstructor().castTypeCache[castTypeCacheKey];
|
|
663
|
-
}
|
|
664
|
-
let convertedCastType;
|
|
665
|
-
if (this.isCustomDateTimeCast(castType)) {
|
|
666
|
-
convertedCastType = "custom_datetime";
|
|
667
|
-
} else if (this.isDecimalCast(castType)) {
|
|
668
|
-
convertedCastType = "decimal";
|
|
669
|
-
} else if (this.isCustomCast(castType)) {
|
|
670
|
-
convertedCastType = castType;
|
|
671
|
-
} else {
|
|
672
|
-
convertedCastType = String(castType).toLocaleLowerCase().trim();
|
|
673
|
-
}
|
|
674
|
-
return this.getConstructor()[castTypeCacheKey] = convertedCastType;
|
|
675
|
-
}
|
|
676
|
-
hasCast(key, types = []) {
|
|
677
|
-
if (key in this.casts) {
|
|
678
|
-
types = flatten(types);
|
|
679
|
-
return types.length > 0 ? types.includes(this.getCastType(key)) : true;
|
|
680
|
-
}
|
|
681
|
-
return false;
|
|
682
|
-
}
|
|
683
|
-
withDayjs(date) {
|
|
684
|
-
return dayjs2(date);
|
|
685
|
-
}
|
|
686
|
-
isCustomCast(cast) {
|
|
687
|
-
return typeof cast === "function" && new cast() instanceof casts_attributes_default;
|
|
688
|
-
}
|
|
689
|
-
isCustomDateTimeCast(cast) {
|
|
690
|
-
if (typeof cast !== "string") {
|
|
691
|
-
return false;
|
|
692
|
-
}
|
|
693
|
-
return cast.startsWith("date:") || cast.startsWith("datetime:");
|
|
694
|
-
}
|
|
695
|
-
isDecimalCast(cast) {
|
|
696
|
-
if (typeof cast !== "string") {
|
|
697
|
-
return false;
|
|
698
|
-
}
|
|
699
|
-
return cast.startsWith("decimal:");
|
|
700
|
-
}
|
|
701
|
-
isDateCastable(key) {
|
|
702
|
-
return this.hasCast(key, ["date", "datetime"]);
|
|
703
|
-
}
|
|
704
|
-
fromDateTime(value) {
|
|
705
|
-
return dayjs2(this.asDateTime(value)).format(this.getDateFormat());
|
|
706
|
-
}
|
|
707
|
-
getDateFormat() {
|
|
708
|
-
return this.dateFormat || "YYYY-MM-DD HH:mm:ss";
|
|
709
|
-
}
|
|
710
|
-
asDecimal(value, decimals) {
|
|
711
|
-
return parseFloat(value).toFixed(decimals);
|
|
712
|
-
}
|
|
713
|
-
asDateTime(value) {
|
|
714
|
-
if (value === null) {
|
|
715
|
-
return null;
|
|
716
|
-
}
|
|
717
|
-
if (value instanceof Date) {
|
|
718
|
-
return value;
|
|
719
|
-
}
|
|
720
|
-
if (typeof value === "number") {
|
|
721
|
-
return new Date(value * 1e3);
|
|
722
|
-
}
|
|
723
|
-
return new Date(value);
|
|
724
|
-
}
|
|
725
|
-
asDate(value) {
|
|
726
|
-
const date = this.asDateTime(value);
|
|
727
|
-
return dayjs2(date).startOf("day").toDate();
|
|
728
|
-
}
|
|
729
|
-
};
|
|
730
|
-
};
|
|
731
|
-
var has_attributes_default = HasAttributes;
|
|
732
|
-
|
|
733
|
-
// src/concerns/has-global-scopes.ts
|
|
734
|
-
import { get, set } from "radashi";
|
|
735
|
-
|
|
736
|
-
// src/scope.ts
|
|
737
|
-
var Scope = class _Scope {
|
|
738
|
-
constructor() {
|
|
739
|
-
if (this.constructor === _Scope) {
|
|
740
|
-
throw new Error("Scope cannot be instantiated");
|
|
741
|
-
}
|
|
742
|
-
}
|
|
743
|
-
apply(_builder, _model) {
|
|
744
|
-
throw new Error("apply not implemented");
|
|
745
|
-
}
|
|
746
|
-
};
|
|
747
|
-
var scope_default = Scope;
|
|
748
|
-
|
|
749
|
-
// src/concerns/has-global-scopes.ts
|
|
750
|
-
var HasGlobalScopes = (Model2) => {
|
|
751
|
-
return class extends Model2 {
|
|
752
|
-
static globalScopes;
|
|
753
|
-
static addGlobalScope(scope, implementation = null) {
|
|
754
|
-
if (typeof scope === "string" && implementation instanceof scope_default) {
|
|
755
|
-
this.globalScopes = set(this.globalScopes ?? {}, this.name + "." + scope, implementation);
|
|
756
|
-
return implementation;
|
|
757
|
-
} else if (scope instanceof scope_default) {
|
|
758
|
-
this.globalScopes = set(this.globalScopes ?? {}, this.name + "." + scope.constructor.name, scope);
|
|
759
|
-
return scope;
|
|
760
|
-
}
|
|
761
|
-
throw new InvalidArgumentError("Global scope must be an instance of Scope.");
|
|
762
|
-
}
|
|
763
|
-
static hasGlobalScope(scope) {
|
|
764
|
-
return this.getGlobalScope(scope) !== null;
|
|
765
|
-
}
|
|
766
|
-
static getGlobalScope(scope) {
|
|
767
|
-
if (typeof scope === "string") {
|
|
768
|
-
return get(this.globalScopes, this.name + "." + scope);
|
|
769
|
-
}
|
|
770
|
-
return get(this.globalScopes, this.name + "." + scope.constructor.name);
|
|
771
|
-
}
|
|
772
|
-
static getAllGlobalScopes() {
|
|
773
|
-
return this.globalScopes;
|
|
774
|
-
}
|
|
775
|
-
static setAllGlobalScopes(scopes) {
|
|
776
|
-
this.globalScopes = scopes;
|
|
777
|
-
}
|
|
778
|
-
getGlobalScopes() {
|
|
779
|
-
return get(this.constructor.globalScopes, this.constructor.name, {});
|
|
780
|
-
}
|
|
781
|
-
};
|
|
782
|
-
};
|
|
783
|
-
var has_global_scopes_default = HasGlobalScopes;
|
|
784
|
-
|
|
785
|
-
// src/hooks.ts
|
|
786
|
-
var Hooks = class {
|
|
787
|
-
hooks = {
|
|
788
|
-
creating: [],
|
|
789
|
-
created: [],
|
|
790
|
-
updating: [],
|
|
791
|
-
updated: [],
|
|
792
|
-
saving: [],
|
|
793
|
-
saved: [],
|
|
794
|
-
deleting: [],
|
|
795
|
-
deleted: [],
|
|
796
|
-
restoring: [],
|
|
797
|
-
restored: [],
|
|
798
|
-
trashed: [],
|
|
799
|
-
forceDeleting: [],
|
|
800
|
-
forceDeleted: []
|
|
801
|
-
};
|
|
802
|
-
add(hook, callback) {
|
|
803
|
-
this.hooks[hook].push(callback);
|
|
804
|
-
}
|
|
805
|
-
async exec(hook, data) {
|
|
806
|
-
const callbacks = this.hooks[hook] ?? [];
|
|
807
|
-
for (const callback of callbacks) {
|
|
808
|
-
await callback(...data);
|
|
809
|
-
}
|
|
810
|
-
return true;
|
|
811
|
-
}
|
|
812
|
-
};
|
|
813
|
-
var hooks_default = Hooks;
|
|
814
|
-
|
|
815
|
-
// src/concerns/has-hooks.ts
|
|
816
|
-
var HasHooks = (Model2) => {
|
|
817
|
-
return class extends Model2 {
|
|
818
|
-
static hooks = null;
|
|
819
|
-
static addHook(hook, callback) {
|
|
820
|
-
if (this.hooks instanceof hooks_default === false) {
|
|
821
|
-
this.hooks = new hooks_default();
|
|
822
|
-
}
|
|
823
|
-
this.hooks.add(hook, callback);
|
|
824
|
-
}
|
|
825
|
-
static creating(callback) {
|
|
826
|
-
this.addHook("creating", callback);
|
|
827
|
-
}
|
|
828
|
-
static created(callback) {
|
|
829
|
-
this.addHook("created", callback);
|
|
830
|
-
}
|
|
831
|
-
static updating(callback) {
|
|
832
|
-
this.addHook("updating", callback);
|
|
833
|
-
}
|
|
834
|
-
static updated(callback) {
|
|
835
|
-
this.addHook("updated", callback);
|
|
836
|
-
}
|
|
837
|
-
static saving(callback) {
|
|
838
|
-
this.addHook("saving", callback);
|
|
839
|
-
}
|
|
840
|
-
static saved(callback) {
|
|
841
|
-
this.addHook("saved", callback);
|
|
842
|
-
}
|
|
843
|
-
static deleting(callback) {
|
|
844
|
-
this.addHook("deleting", callback);
|
|
845
|
-
}
|
|
846
|
-
static deleted(callback) {
|
|
847
|
-
this.addHook("deleted", callback);
|
|
848
|
-
}
|
|
849
|
-
static restoring(callback) {
|
|
850
|
-
this.addHook("restoring", callback);
|
|
851
|
-
}
|
|
852
|
-
static restored(callback) {
|
|
853
|
-
this.addHook("restored", callback);
|
|
854
|
-
}
|
|
855
|
-
static trashed(callback) {
|
|
856
|
-
this.addHook("trashed", callback);
|
|
857
|
-
}
|
|
858
|
-
static forceDeleted(callback) {
|
|
859
|
-
this.addHook("forceDeleted", callback);
|
|
860
|
-
}
|
|
861
|
-
async execHooks(hook, options) {
|
|
862
|
-
if (this.constructor.hooks instanceof hooks_default === false) {
|
|
863
|
-
return;
|
|
864
|
-
}
|
|
865
|
-
return await this.constructor.hooks.exec(hook, [this, options]);
|
|
866
|
-
}
|
|
867
|
-
};
|
|
868
|
-
};
|
|
869
|
-
var has_hooks_default = HasHooks;
|
|
870
|
-
|
|
871
|
-
// src/relations/has-one-or-many.ts
|
|
872
|
-
import collect2 from "collect.js";
|
|
873
|
-
var HasOneOrMany = (Relation2) => {
|
|
874
|
-
return class extends Relation2 {
|
|
875
|
-
getRelationValue(dictionary, key, type) {
|
|
876
|
-
const value = dictionary[key];
|
|
877
|
-
return type === "one" ? value[0] : new collection_default(value);
|
|
878
|
-
}
|
|
879
|
-
matchOneOrMany(models, results, relation, type) {
|
|
880
|
-
const dictionary = this.buildDictionary(results);
|
|
881
|
-
models.map((model) => {
|
|
882
|
-
const key = model.attributes[this.localKey];
|
|
883
|
-
if (dictionary[key] !== void 0) {
|
|
884
|
-
model.setRelation(relation, this.getRelationValue(dictionary, key, type));
|
|
885
|
-
}
|
|
886
|
-
});
|
|
887
|
-
return models;
|
|
888
|
-
}
|
|
889
|
-
buildDictionary(results) {
|
|
890
|
-
const foreign = this.getForeignKeyName();
|
|
891
|
-
return collect2(results).mapToDictionary((result) => [
|
|
892
|
-
result[foreign],
|
|
893
|
-
result
|
|
894
|
-
]).all();
|
|
895
|
-
}
|
|
896
|
-
async save(model) {
|
|
897
|
-
this.setForeignAttributesForCreate(model);
|
|
898
|
-
return await model.save() ? model : false;
|
|
899
|
-
}
|
|
900
|
-
async saveMany(models) {
|
|
901
|
-
await Promise.all(models.map(async (model) => {
|
|
902
|
-
await this.save(model);
|
|
903
|
-
}));
|
|
904
|
-
return models instanceof collection_default ? models : new collection_default(models);
|
|
905
|
-
}
|
|
906
|
-
async create(attributes = {}) {
|
|
907
|
-
return await tap(this.related.constructor.init(attributes), async (instance) => {
|
|
908
|
-
this.setForeignAttributesForCreate(instance);
|
|
909
|
-
await instance.save();
|
|
910
|
-
});
|
|
911
|
-
}
|
|
912
|
-
async createMany(records) {
|
|
913
|
-
const instances = await Promise.all(records.map(async (record) => {
|
|
914
|
-
return await this.create(record);
|
|
915
|
-
}));
|
|
916
|
-
return instances instanceof collection_default ? instances : new collection_default(instances);
|
|
917
|
-
}
|
|
918
|
-
setForeignAttributesForCreate(model) {
|
|
919
|
-
model[this.getForeignKeyName()] = this.getParentKey();
|
|
920
|
-
}
|
|
921
|
-
getForeignKeyName() {
|
|
922
|
-
const segments = this.getQualifiedForeignKeyName().split(".");
|
|
923
|
-
return segments[segments.length - 1];
|
|
924
|
-
}
|
|
925
|
-
getParentKey() {
|
|
926
|
-
return this.parent.attributes[this.localKey];
|
|
927
|
-
}
|
|
928
|
-
getQualifiedForeignKeyName() {
|
|
929
|
-
return this.foreignKey;
|
|
930
|
-
}
|
|
931
|
-
getExistenceCompareKey() {
|
|
932
|
-
return this.getQualifiedForeignKeyName();
|
|
933
|
-
}
|
|
934
|
-
addConstraints() {
|
|
935
|
-
if (this.constructor.constraints) {
|
|
936
|
-
const query = this.getRelationQuery();
|
|
937
|
-
query.where(this.foreignKey, "=", this.getParentKey());
|
|
938
|
-
query.whereNotNull(this.foreignKey);
|
|
939
|
-
}
|
|
940
|
-
}
|
|
941
|
-
};
|
|
942
|
-
};
|
|
943
|
-
var has_one_or_many_default = HasOneOrMany;
|
|
944
|
-
|
|
945
|
-
// src/relations/has-many.ts
|
|
946
|
-
import { collect as collect3 } from "collect.js";
|
|
947
|
-
var HasMany = class extends compose(relation_default, has_one_or_many_default) {
|
|
948
|
-
foreignKey;
|
|
949
|
-
localKey;
|
|
950
|
-
constructor(query, parent, foreignKey, localKey) {
|
|
951
|
-
super(query, parent);
|
|
952
|
-
this.foreignKey = foreignKey;
|
|
953
|
-
this.localKey = localKey;
|
|
954
|
-
this.addConstraints();
|
|
955
|
-
return this.asProxy();
|
|
956
|
-
}
|
|
957
|
-
initRelation(models, relation) {
|
|
958
|
-
models.map((model) => {
|
|
959
|
-
model.setRelation(relation, new collection_default([]));
|
|
960
|
-
});
|
|
961
|
-
return models;
|
|
962
|
-
}
|
|
963
|
-
async getResults() {
|
|
964
|
-
return this.getParentKey() !== null ? await this.query.get() : new collection_default([]);
|
|
965
|
-
}
|
|
966
|
-
getForeignKeyName() {
|
|
967
|
-
const segments = this.foreignKey?.split(".");
|
|
968
|
-
return segments?.pop();
|
|
969
|
-
}
|
|
970
|
-
buildDictionary(results) {
|
|
971
|
-
const foreign = this.getForeignKeyName();
|
|
972
|
-
return collect3(results).mapToDictionary((result) => [
|
|
973
|
-
result[foreign],
|
|
974
|
-
result
|
|
975
|
-
]).all();
|
|
976
|
-
}
|
|
977
|
-
match(models, results, relation) {
|
|
978
|
-
return this.matchOneOrMany(models, results, relation, "many");
|
|
979
|
-
}
|
|
980
|
-
addEagerConstraints(models) {
|
|
981
|
-
this.query.whereIn(this.foreignKey, this.getKeys(models, this.localKey));
|
|
982
|
-
}
|
|
983
|
-
};
|
|
984
|
-
var has_many_default = HasMany;
|
|
985
|
-
|
|
986
|
-
// src/relations/has-one.ts
|
|
987
|
-
var HasOne = class extends compose(
|
|
988
|
-
relation_default,
|
|
989
|
-
has_one_or_many_default,
|
|
990
|
-
supports_default_models_default
|
|
991
|
-
) {
|
|
992
|
-
foreignKey;
|
|
993
|
-
localKey;
|
|
994
|
-
constructor(query, parent, foreignKey, localKey) {
|
|
995
|
-
super(query, parent);
|
|
996
|
-
this.foreignKey = foreignKey;
|
|
997
|
-
this.localKey = localKey;
|
|
998
|
-
this.addConstraints();
|
|
999
|
-
return this.asProxy();
|
|
1000
|
-
}
|
|
1001
|
-
initRelation(models, relation) {
|
|
1002
|
-
models.map((model) => {
|
|
1003
|
-
model.setRelation(relation, this.getDefaultFor(model));
|
|
1004
|
-
});
|
|
1005
|
-
return models;
|
|
1006
|
-
}
|
|
1007
|
-
matchOne(models, results, relation) {
|
|
1008
|
-
return this.matchOneOrMany(models, results, relation, "one");
|
|
1009
|
-
}
|
|
1010
|
-
getForeignKeyName() {
|
|
1011
|
-
const segments = this.foreignKey?.split(".");
|
|
1012
|
-
return segments?.pop();
|
|
1013
|
-
}
|
|
1014
|
-
async getResults() {
|
|
1015
|
-
if (this.getParentKey() === null) {
|
|
1016
|
-
return this.getDefaultFor(this.parent);
|
|
1017
|
-
}
|
|
1018
|
-
const results = await this.query.first();
|
|
1019
|
-
return results || this.getDefaultFor(this.parent);
|
|
1020
|
-
}
|
|
1021
|
-
match(models, results, relation) {
|
|
1022
|
-
return this.matchOneOrMany(models, results, relation, "one");
|
|
1023
|
-
}
|
|
1024
|
-
addEagerConstraints(models) {
|
|
1025
|
-
this.query.whereIn(this.foreignKey, this.getKeys(models, this.localKey));
|
|
1026
|
-
}
|
|
1027
|
-
newRelatedInstanceFor(parent) {
|
|
1028
|
-
return this.related.newInstance().setAttribute(this.getForeignKeyName(), parent[this.localKey]);
|
|
1029
|
-
}
|
|
1030
|
-
};
|
|
1031
|
-
var has_one_default = HasOne;
|
|
1032
|
-
|
|
1033
|
-
// src/relations/has-many-through.ts
|
|
1034
|
-
import { isArray as isArray2 } from "radashi";
|
|
1035
|
-
var HasManyThrough = class extends relation_default {
|
|
1036
|
-
throughParent;
|
|
1037
|
-
farParent;
|
|
1038
|
-
firstKey;
|
|
1039
|
-
secondKey;
|
|
1040
|
-
localKey;
|
|
1041
|
-
secondLocalKey;
|
|
1042
|
-
constructor(query, farParent, throughParent, firstKey, secondKey, localKey, secondLocalKey) {
|
|
1043
|
-
super(query, throughParent);
|
|
1044
|
-
this.localKey = localKey;
|
|
1045
|
-
this.firstKey = firstKey;
|
|
1046
|
-
this.secondKey = secondKey;
|
|
1047
|
-
this.farParent = farParent;
|
|
1048
|
-
this.throughParent = throughParent;
|
|
1049
|
-
this.secondLocalKey = secondLocalKey;
|
|
1050
|
-
return this.asProxy();
|
|
1051
|
-
}
|
|
1052
|
-
addConstraints() {
|
|
1053
|
-
const localValue = this.farParent[this.localKey];
|
|
1054
|
-
this.performJoin();
|
|
1055
|
-
if (this.constructor.constraints) {
|
|
1056
|
-
this.query.where(this.getQualifiedFirstKeyName(), "=", localValue);
|
|
1057
|
-
}
|
|
1058
|
-
}
|
|
1059
|
-
performJoin(query = null) {
|
|
1060
|
-
query = query || this.query;
|
|
1061
|
-
const farKey = this.getQualifiedFarKeyName();
|
|
1062
|
-
query.join(this.throughParent.getTable(), this.getQualifiedParentKeyName(), "=", farKey);
|
|
1063
|
-
if (this.throughParentSoftDeletes()) {
|
|
1064
|
-
query.withGlobalScope("SoftDeletableHasManyThrough", (query2) => {
|
|
1065
|
-
query2.whereNull(this.throughParent.getQualifiedDeletedAtColumn());
|
|
1066
|
-
});
|
|
1067
|
-
}
|
|
1068
|
-
}
|
|
1069
|
-
getQualifiedParentKeyName() {
|
|
1070
|
-
return this.parent.qualifyColumn(this.secondLocalKey);
|
|
1071
|
-
}
|
|
1072
|
-
throughParentSoftDeletes() {
|
|
1073
|
-
return this.throughParent.pluginInitializers["SoftDeletes"] !== void 0;
|
|
1074
|
-
}
|
|
1075
|
-
withTrashedParents() {
|
|
1076
|
-
this.query.withoutGlobalScope("SoftDeletableHasManyThrough");
|
|
1077
|
-
return this;
|
|
1078
|
-
}
|
|
1079
|
-
addEagerConstraints(models) {
|
|
1080
|
-
const whereIn = this.whereInMethod(this.farParent, this.localKey);
|
|
1081
|
-
this.whereInEager(whereIn, this.getQualifiedFirstKeyName(), this.getKeys(models, this.localKey));
|
|
1082
|
-
}
|
|
1083
|
-
initRelation(models, relation) {
|
|
1084
|
-
for (const model of models) {
|
|
1085
|
-
model.setRelation(relation, this.related.newCollection());
|
|
1086
|
-
}
|
|
1087
|
-
return models;
|
|
1088
|
-
}
|
|
1089
|
-
match(models, results, relation) {
|
|
1090
|
-
const dictionary = this.buildDictionary(results);
|
|
1091
|
-
for (const model of models) {
|
|
1092
|
-
const key = this.getDictionaryKey(model.getAttribute(this.localKey));
|
|
1093
|
-
if (dictionary[key] !== void 0) {
|
|
1094
|
-
model.setRelation(relation, this.related.newCollection(dictionary[key]));
|
|
1095
|
-
}
|
|
1096
|
-
}
|
|
1097
|
-
return models;
|
|
1098
|
-
}
|
|
1099
|
-
buildDictionary(results) {
|
|
1100
|
-
const dictionary = {};
|
|
1101
|
-
for (const result of results) {
|
|
1102
|
-
if (dictionary[result.laravel_through_key] === void 0) {
|
|
1103
|
-
dictionary[result.laravel_through_key] = [];
|
|
1104
|
-
}
|
|
1105
|
-
dictionary[result.laravel_through_key].push(result);
|
|
1106
|
-
}
|
|
1107
|
-
return dictionary;
|
|
1108
|
-
}
|
|
1109
|
-
async firstOrNew(attributes) {
|
|
1110
|
-
const instance = await this.where(attributes).first();
|
|
1111
|
-
return instance || this.related.newInstance(attributes);
|
|
1112
|
-
}
|
|
1113
|
-
async updateOrCreate(attributes, values = {}) {
|
|
1114
|
-
return tap(await this.firstOrCreate(attributes, values), async (instance) => {
|
|
1115
|
-
if (!instance.wasRecentlyCreated) {
|
|
1116
|
-
await instance.fill(values).save();
|
|
1117
|
-
}
|
|
1118
|
-
});
|
|
1119
|
-
}
|
|
1120
|
-
async firstWhere(column, operator = null, value = null, boolean = "and") {
|
|
1121
|
-
return await this.where(column, operator, value, boolean).first();
|
|
1122
|
-
}
|
|
1123
|
-
async first(columns = ["*"]) {
|
|
1124
|
-
const results = await this.take(1).get(columns);
|
|
1125
|
-
return results.count() > 0 ? results.first() : null;
|
|
1126
|
-
}
|
|
1127
|
-
async firstOrFail(columns = ["*"]) {
|
|
1128
|
-
const model = await this.first(columns);
|
|
1129
|
-
if (model) {
|
|
1130
|
-
return model;
|
|
1131
|
-
}
|
|
1132
|
-
throw new ModelNotFoundError().setModel(this.related.constructor);
|
|
1133
|
-
}
|
|
1134
|
-
async firstOr(columns = ["*"], callback = null) {
|
|
1135
|
-
if (typeof columns === "function") {
|
|
1136
|
-
callback = columns;
|
|
1137
|
-
columns = ["*"];
|
|
1138
|
-
}
|
|
1139
|
-
const model = await this.first(columns);
|
|
1140
|
-
if (model) {
|
|
1141
|
-
return model;
|
|
1142
|
-
}
|
|
1143
|
-
return callback?.();
|
|
1144
|
-
}
|
|
1145
|
-
async find(id, columns = ["*"]) {
|
|
1146
|
-
if (isArray2(id)) {
|
|
1147
|
-
return await this.findMany(id, columns);
|
|
1148
|
-
}
|
|
1149
|
-
return await this.where(this.getRelated().getQualifiedKeyName(), "=", id).first(columns);
|
|
1150
|
-
}
|
|
1151
|
-
async findMany(ids, columns = ["*"]) {
|
|
1152
|
-
if (ids.length === 0) {
|
|
1153
|
-
return this.getRelated().newCollection();
|
|
1154
|
-
}
|
|
1155
|
-
return await this.whereIn(this.getRelated().getQualifiedKeyName(), ids).get(columns);
|
|
1156
|
-
}
|
|
1157
|
-
async findOrFail(id, columns = ["*"]) {
|
|
1158
|
-
const result = await this.find(id, columns);
|
|
1159
|
-
if (Array.isArray(id)) {
|
|
1160
|
-
if (result.count() === id.length) {
|
|
1161
|
-
return result;
|
|
1162
|
-
}
|
|
1163
|
-
} else if (result) {
|
|
1164
|
-
return result;
|
|
1165
|
-
}
|
|
1166
|
-
throw new ModelNotFoundError().setModel(this.related.constructor, id);
|
|
1167
|
-
}
|
|
1168
|
-
async getResults() {
|
|
1169
|
-
return this.farParent[this.localKey] ? await this.get() : this.related.newCollection();
|
|
1170
|
-
}
|
|
1171
|
-
async get(columns = ["*"]) {
|
|
1172
|
-
const builder = this.prepareQueryBuilder(columns);
|
|
1173
|
-
let models = await builder.getModels();
|
|
1174
|
-
if (models.count() > 0) {
|
|
1175
|
-
models = await builder.eagerLoadRelations(models);
|
|
1176
|
-
}
|
|
1177
|
-
return this.related.newCollection(models);
|
|
1178
|
-
}
|
|
1179
|
-
async paginate(perPage = null, columns = ["*"], pageName = "page", page = null) {
|
|
1180
|
-
this.query.addSelect(this.shouldSelect(columns));
|
|
1181
|
-
return await this.query.paginate(perPage, columns, pageName, page);
|
|
1182
|
-
}
|
|
1183
|
-
shouldSelect(columns = ["*"]) {
|
|
1184
|
-
if (columns?.at(0) == "*") {
|
|
1185
|
-
columns = [this.related.getTable() + ".*"];
|
|
1186
|
-
}
|
|
1187
|
-
return [...columns, this.getQualifiedFirstKeyName() + " as laravel_through_key"];
|
|
1188
|
-
}
|
|
1189
|
-
async chunk(count, callback) {
|
|
1190
|
-
return await this.prepareQueryBuilder().chunk(count, callback);
|
|
1191
|
-
}
|
|
1192
|
-
prepareQueryBuilder(columns = ["*"]) {
|
|
1193
|
-
const builder = this.query.applyScopes();
|
|
1194
|
-
return builder.addSelect(this.shouldSelect(builder.getQuery().columns ? [] : columns));
|
|
1195
|
-
}
|
|
1196
|
-
getRelationExistenceQuery(query, parentQuery, columns = ["*"]) {
|
|
1197
|
-
if (parentQuery.getQuery().from === query.getQuery().from) {
|
|
1198
|
-
return this.getRelationExistenceQueryForSelfRelation(query, parentQuery, columns);
|
|
1199
|
-
}
|
|
1200
|
-
if (parentQuery.getQuery().from === this.throughParent.getTable()) {
|
|
1201
|
-
return this.getRelationExistenceQueryForThroughSelfRelation(query, parentQuery, columns);
|
|
1202
|
-
}
|
|
1203
|
-
this.performJoin(query);
|
|
1204
|
-
return query.select(columns).where(this.getQualifiedLocalKeyName(), "=", this.getQualifiedFirstKeyName());
|
|
1205
|
-
}
|
|
1206
|
-
getRelationExistenceQueryForSelfRelation(query, parentQuery, columns = ["*"]) {
|
|
1207
|
-
const hash = this.getRelationCountHash();
|
|
1208
|
-
query.from(query.getModel().getTable() + " as " + hash);
|
|
1209
|
-
query.join(this.throughParent.getTable(), this.getQualifiedParentKeyName(), "=", hash + "." + this.secondKey);
|
|
1210
|
-
if (this.throughParentSoftDeletes()) {
|
|
1211
|
-
query.whereNull(this.throughParent.getQualifiedDeletedAtColumn());
|
|
1212
|
-
}
|
|
1213
|
-
query.getModel().setTable(hash);
|
|
1214
|
-
return query.select(columns).whereColumn(parentQuery.getQuery().from + "." + this.localKey, "=", this.getQualifiedFirstKeyName());
|
|
1215
|
-
}
|
|
1216
|
-
getRelationExistenceQueryForThroughSelfRelation(query, parentQuery, columns = ["*"]) {
|
|
1217
|
-
const hash = this.getRelationCountHash();
|
|
1218
|
-
const table = this.throughParent.getTable() + " as " + hash;
|
|
1219
|
-
query.join(table, hash + "." + this.secondLocalKey, "=", this.getQualifiedFarKeyName());
|
|
1220
|
-
if (this.throughParentSoftDeletes()) {
|
|
1221
|
-
query.whereNull(hash + "." + this.throughParent.getDeletedAtColumn());
|
|
1222
|
-
}
|
|
1223
|
-
return query.select(columns).where(parentQuery.getQuery().from + "." + this.localKey, "=", hash + "." + this.firstKey);
|
|
1224
|
-
}
|
|
1225
|
-
getQualifiedFarKeyName() {
|
|
1226
|
-
return this.getQualifiedForeignKeyName();
|
|
1227
|
-
}
|
|
1228
|
-
getFirstKeyName() {
|
|
1229
|
-
return this.firstKey;
|
|
1230
|
-
}
|
|
1231
|
-
getQualifiedFirstKeyName() {
|
|
1232
|
-
return this.throughParent.qualifyColumn(this.firstKey);
|
|
1233
|
-
}
|
|
1234
|
-
getForeignKeyName() {
|
|
1235
|
-
return this.secondKey;
|
|
1236
|
-
}
|
|
1237
|
-
getQualifiedForeignKeyName() {
|
|
1238
|
-
return this.related.qualifyColumn(this.secondKey);
|
|
1239
|
-
}
|
|
1240
|
-
getLocalKeyName() {
|
|
1241
|
-
return this.localKey;
|
|
1242
|
-
}
|
|
1243
|
-
getQualifiedLocalKeyName() {
|
|
1244
|
-
return this.farParent.qualifyColumn(this.localKey);
|
|
1245
|
-
}
|
|
1246
|
-
getSecondLocalKeyName() {
|
|
1247
|
-
return this.secondLocalKey;
|
|
1248
|
-
}
|
|
1249
|
-
};
|
|
1250
|
-
var has_many_through_default = HasManyThrough;
|
|
1251
|
-
|
|
1252
|
-
// src/relations/has-one-through.ts
|
|
1253
|
-
var HasOneThrough = class extends compose(
|
|
1254
|
-
has_many_through_default,
|
|
1255
|
-
supports_default_models_default
|
|
1256
|
-
) {
|
|
1257
|
-
async getResults() {
|
|
1258
|
-
return await this.first() || this.getDefaultFor(this.farParent);
|
|
1259
|
-
}
|
|
1260
|
-
initRelation(models, relation) {
|
|
1261
|
-
for (const model of models) {
|
|
1262
|
-
model.setRelation(relation, this.getDefaultFor(model));
|
|
1263
|
-
}
|
|
1264
|
-
return models;
|
|
1265
|
-
}
|
|
1266
|
-
match(models, results, relation) {
|
|
1267
|
-
const dictionary = this.buildDictionary(results);
|
|
1268
|
-
for (const model of models) {
|
|
1269
|
-
const key = this.getDictionaryKey(model.getAttribute(this.localKey));
|
|
1270
|
-
if (dictionary[key] !== void 0) {
|
|
1271
|
-
const value = dictionary[key];
|
|
1272
|
-
model.setRelation(relation, value[0]);
|
|
1273
|
-
}
|
|
1274
|
-
}
|
|
1275
|
-
return models;
|
|
1276
|
-
}
|
|
1277
|
-
newRelatedInstanceFor(_parent) {
|
|
1278
|
-
return this.related.newInstance();
|
|
1279
|
-
}
|
|
1280
|
-
};
|
|
1281
|
-
var has_one_through_default = HasOneThrough;
|
|
1282
|
-
|
|
1283
|
-
// src/concerns/has-relations.ts
|
|
1284
|
-
import { omit as omit2 } from "radashi";
|
|
1285
|
-
var HasRelations = (Model2) => {
|
|
1286
|
-
return class extends Model2 {
|
|
1287
|
-
relations = {};
|
|
1288
|
-
getRelation(relation) {
|
|
1289
|
-
return this.relations[relation];
|
|
1290
|
-
}
|
|
1291
|
-
setRelation(relation, value) {
|
|
1292
|
-
this.relations[relation] = value;
|
|
1293
|
-
return this;
|
|
1294
|
-
}
|
|
1295
|
-
unsetRelation(relation) {
|
|
1296
|
-
this.relations = omit2(this.relations, [relation]);
|
|
1297
|
-
return this;
|
|
1298
|
-
}
|
|
1299
|
-
relationLoaded(relation) {
|
|
1300
|
-
return this.relations[relation] !== void 0;
|
|
1301
|
-
}
|
|
1302
|
-
related(relation) {
|
|
1303
|
-
if (typeof this[getRelationMethod(relation)] !== "function") {
|
|
1304
|
-
const message = `Model [${this.constructor.name}]'s relation [${relation}] doesn't exist.`;
|
|
1305
|
-
throw new RelationNotFoundError(message);
|
|
1306
|
-
}
|
|
1307
|
-
return this[getRelationMethod(relation)]();
|
|
1308
|
-
}
|
|
1309
|
-
async getRelated(relation) {
|
|
1310
|
-
return await this.related(relation).getResults();
|
|
1311
|
-
}
|
|
1312
|
-
relationsToData() {
|
|
1313
|
-
const data = {};
|
|
1314
|
-
for (const key in this.relations) {
|
|
1315
|
-
if (this.hidden.includes(key)) {
|
|
1316
|
-
continue;
|
|
1317
|
-
}
|
|
1318
|
-
if (this.visible.length > 0 && this.visible.includes(key) === false) {
|
|
1319
|
-
continue;
|
|
1320
|
-
}
|
|
1321
|
-
data[key] = this.relations[key] instanceof Array ? this.relations[key].map((item) => item.toData()) : this.relations[key] === null ? null : this.relations[key].toData();
|
|
1322
|
-
}
|
|
1323
|
-
return data;
|
|
1324
|
-
}
|
|
1325
|
-
guessBelongsToRelation() {
|
|
1326
|
-
const e = new Error();
|
|
1327
|
-
const frame = e.stack.split("\n")[2];
|
|
1328
|
-
const functionName = frame.split(" ")[5];
|
|
1329
|
-
return getRelationName(functionName);
|
|
1330
|
-
}
|
|
1331
|
-
joiningTable(related, instance = null) {
|
|
1332
|
-
const segments = [
|
|
1333
|
-
instance ? instance.joiningTableSegment() : snakeCase(related.name),
|
|
1334
|
-
this.joiningTableSegment()
|
|
1335
|
-
];
|
|
1336
|
-
return segments.sort().join("_").toLocaleLowerCase();
|
|
1337
|
-
}
|
|
1338
|
-
joiningTableSegment() {
|
|
1339
|
-
return snakeCase(this.constructor.name);
|
|
1340
|
-
}
|
|
1341
|
-
hasOne(related, foreignKey = null, localKey = null) {
|
|
1342
|
-
const query = related.query();
|
|
1343
|
-
const instance = new related();
|
|
1344
|
-
foreignKey = foreignKey || this.getForeignKey();
|
|
1345
|
-
localKey = localKey || this.getKeyName();
|
|
1346
|
-
return new has_one_default(query, this, instance.getTable() + "." + foreignKey, localKey);
|
|
1347
|
-
}
|
|
1348
|
-
hasMany(related, foreignKey = null, localKey = null) {
|
|
1349
|
-
const query = related.query();
|
|
1350
|
-
const instance = new related();
|
|
1351
|
-
foreignKey = foreignKey || this.getForeignKey();
|
|
1352
|
-
localKey = localKey || this.getKeyName();
|
|
1353
|
-
return new has_many_default(query, this, instance.getTable() + "." + foreignKey, localKey);
|
|
1354
|
-
}
|
|
1355
|
-
belongsTo(related, foreignKey = null, ownerKey = null, relation = null) {
|
|
1356
|
-
const query = related.query();
|
|
1357
|
-
const instance = new related();
|
|
1358
|
-
foreignKey = foreignKey || instance.getForeignKey();
|
|
1359
|
-
ownerKey = ownerKey || instance.getKeyName();
|
|
1360
|
-
relation = relation || this.guessBelongsToRelation();
|
|
1361
|
-
return new belongs_to_default(query, this, foreignKey, ownerKey, relation);
|
|
1362
|
-
}
|
|
1363
|
-
belongsToMany(related, table = null, foreignPivotKey = null, relatedPivotKey = null, parentKey = null, relatedKey = null) {
|
|
1364
|
-
const query = related.query();
|
|
1365
|
-
const instance = new related();
|
|
1366
|
-
table = table || this.joiningTable(related, instance);
|
|
1367
|
-
foreignPivotKey = foreignPivotKey || this.getForeignKey();
|
|
1368
|
-
relatedPivotKey = relatedPivotKey || instance.getForeignKey();
|
|
1369
|
-
parentKey = parentKey || this.getKeyName();
|
|
1370
|
-
relatedKey = relatedKey || instance.getKeyName();
|
|
1371
|
-
return new belongs_to_many_default(query, this, table, foreignPivotKey, relatedPivotKey, parentKey, relatedKey);
|
|
1372
|
-
}
|
|
1373
|
-
hasOneThrough(related, through, firstKey = null, secondKey = null, localKey = null, secondLocalKey = null) {
|
|
1374
|
-
through = new through();
|
|
1375
|
-
const query = related.query();
|
|
1376
|
-
firstKey = firstKey || this.getForeignKey();
|
|
1377
|
-
secondKey = secondKey || through.getForeignKey();
|
|
1378
|
-
return new has_one_through_default(query, this, through, firstKey, secondKey, localKey || this.getKeyName(), secondLocalKey || through.getKeyName());
|
|
1379
|
-
}
|
|
1380
|
-
hasManyThrough(related, through, firstKey = null, secondKey = null, localKey = null, secondLocalKey = null) {
|
|
1381
|
-
through = new through();
|
|
1382
|
-
const query = related.query();
|
|
1383
|
-
firstKey = firstKey || this.getForeignKey();
|
|
1384
|
-
secondKey = secondKey || through.getForeignKey();
|
|
1385
|
-
return new has_many_through_default(query, this, through, firstKey, secondKey, localKey || this.getKeyName(), secondLocalKey || through.getKeyName());
|
|
1386
|
-
}
|
|
1387
|
-
};
|
|
1388
|
-
};
|
|
1389
|
-
var has_relations_default = HasRelations;
|
|
1390
|
-
|
|
1391
|
-
// src/concerns/has-timestamps.ts
|
|
1392
|
-
var HasTimestamps = (Model2) => {
|
|
1393
|
-
return class extends Model2 {
|
|
1394
|
-
static CREATED_AT = "created_at";
|
|
1395
|
-
static UPDATED_AT = "updated_at";
|
|
1396
|
-
static DELETED_AT = "deleted_at";
|
|
1397
|
-
timestamps = true;
|
|
1398
|
-
dateFormat = "YYYY-MM-DD HH:mm:ss";
|
|
1399
|
-
usesTimestamps() {
|
|
1400
|
-
return this.timestamps;
|
|
1401
|
-
}
|
|
1402
|
-
updateTimestamps() {
|
|
1403
|
-
const time = this.freshTimestampString();
|
|
1404
|
-
const updatedAtColumn = this.getUpdatedAtColumn();
|
|
1405
|
-
if (updatedAtColumn && !this.isDirty(updatedAtColumn)) {
|
|
1406
|
-
this.setUpdatedAt(time);
|
|
1407
|
-
}
|
|
1408
|
-
const createdAtColumn = this.getCreatedAtColumn();
|
|
1409
|
-
if (!this.exists && createdAtColumn && !this.isDirty(createdAtColumn)) {
|
|
1410
|
-
this.setCreatedAt(time);
|
|
1411
|
-
}
|
|
1412
|
-
return this;
|
|
1413
|
-
}
|
|
1414
|
-
getCreatedAtColumn() {
|
|
1415
|
-
return this.constructor.CREATED_AT;
|
|
1416
|
-
}
|
|
1417
|
-
getUpdatedAtColumn() {
|
|
1418
|
-
return this.constructor.UPDATED_AT;
|
|
1419
|
-
}
|
|
1420
|
-
setCreatedAt(value) {
|
|
1421
|
-
this.attributes[this.getCreatedAtColumn()] = value;
|
|
1422
|
-
return this;
|
|
1423
|
-
}
|
|
1424
|
-
setUpdatedAt(value) {
|
|
1425
|
-
this.attributes[this.getUpdatedAtColumn()] = value;
|
|
1426
|
-
return this;
|
|
1427
|
-
}
|
|
1428
|
-
freshTimestamp() {
|
|
1429
|
-
const time = /* @__PURE__ */ new Date();
|
|
1430
|
-
time.setMilliseconds(0);
|
|
1431
|
-
return time;
|
|
1432
|
-
}
|
|
1433
|
-
freshTimestampString() {
|
|
1434
|
-
return this.fromDateTime(this.freshTimestamp());
|
|
1435
|
-
}
|
|
1436
|
-
};
|
|
1437
|
-
};
|
|
1438
|
-
var has_timestamps_default = HasTimestamps;
|
|
1439
|
-
|
|
1440
|
-
// src/concerns/hides-attributes.ts
|
|
1441
|
-
import { diff as difference } from "radashi";
|
|
1442
|
-
var HidesAttributes = (Model2) => {
|
|
1443
|
-
return class extends Model2 {
|
|
1444
|
-
hidden = [];
|
|
1445
|
-
visible = [];
|
|
1446
|
-
makeVisible(...keys) {
|
|
1447
|
-
const visible = flattenDeep(keys);
|
|
1448
|
-
if (this.visible.length > 0) {
|
|
1449
|
-
this.visible = [...this.visible, ...visible];
|
|
1450
|
-
}
|
|
1451
|
-
this.hidden = difference(this.hidden, visible);
|
|
1452
|
-
return this;
|
|
1453
|
-
}
|
|
1454
|
-
makeHidden(key, ...keys) {
|
|
1455
|
-
const hidden = flattenDeep([...key, ...keys]);
|
|
1456
|
-
if (this.hidden.length > 0) {
|
|
1457
|
-
this.hidden = [...this.hidden, ...hidden];
|
|
1458
|
-
}
|
|
1459
|
-
return this;
|
|
1460
|
-
}
|
|
1461
|
-
getHidden() {
|
|
1462
|
-
return this.hidden;
|
|
1463
|
-
}
|
|
1464
|
-
getVisible() {
|
|
1465
|
-
return this.visible;
|
|
1466
|
-
}
|
|
1467
|
-
setHidden(hidden) {
|
|
1468
|
-
this.hidden = hidden;
|
|
1469
|
-
return this;
|
|
1470
|
-
}
|
|
1471
|
-
setVisible(visible) {
|
|
1472
|
-
this.visible = visible;
|
|
1473
|
-
return this;
|
|
1474
|
-
}
|
|
1475
|
-
};
|
|
1476
|
-
};
|
|
1477
|
-
var hides_attributes_default = HidesAttributes;
|
|
1478
|
-
|
|
1479
|
-
// src/concerns/unique-ids.ts
|
|
1480
|
-
var UniqueIds = (Model2) => {
|
|
1481
|
-
return class extends Model2 {
|
|
1482
|
-
useUniqueIds = false;
|
|
1483
|
-
usesUniqueIds() {
|
|
1484
|
-
return this.useUniqueIds;
|
|
1485
|
-
}
|
|
1486
|
-
uniqueIds() {
|
|
1487
|
-
return [];
|
|
1488
|
-
}
|
|
1489
|
-
newUniqueId() {
|
|
1490
|
-
return null;
|
|
1491
|
-
}
|
|
1492
|
-
setUniqueIds() {
|
|
1493
|
-
const uniqueIds = this.uniqueIds();
|
|
1494
|
-
for (const column of uniqueIds) {
|
|
1495
|
-
if (this[column] === null || this[column] === void 0) {
|
|
1496
|
-
this[column] = this.newUniqueId();
|
|
1497
|
-
}
|
|
1498
|
-
}
|
|
1499
|
-
}
|
|
1500
|
-
};
|
|
1501
|
-
};
|
|
1502
|
-
var unique_ids_default = UniqueIds;
|
|
1503
|
-
|
|
1504
|
-
// src/arquebus.ts
|
|
1505
|
-
import Knex from "knex";
|
|
1506
|
-
|
|
1507
|
-
// src/paginator.ts
|
|
1508
|
-
var Paginator = class {
|
|
1509
|
-
static formatter;
|
|
1510
|
-
_items;
|
|
1511
|
-
_total;
|
|
1512
|
-
_perPage;
|
|
1513
|
-
_lastPage;
|
|
1514
|
-
_currentPage;
|
|
1515
|
-
hasMore = false;
|
|
1516
|
-
options = {};
|
|
1517
|
-
static setFormatter(formatter) {
|
|
1518
|
-
if (typeof formatter !== "function" && formatter !== null && formatter !== void 0) {
|
|
1519
|
-
throw new Error("Paginator formatter must be a function or null");
|
|
1520
|
-
}
|
|
1521
|
-
this.formatter = formatter;
|
|
1522
|
-
}
|
|
1523
|
-
constructor(items, total, perPage, currentPage = 1, options = {}) {
|
|
1524
|
-
this.options = options;
|
|
1525
|
-
for (const key in options) {
|
|
1526
|
-
const value = options[key];
|
|
1527
|
-
this[key] = value;
|
|
1528
|
-
}
|
|
1529
|
-
this._items = new collection_default([]);
|
|
1530
|
-
this._total = total;
|
|
1531
|
-
this._perPage = parseInt(String(perPage));
|
|
1532
|
-
this._lastPage = Math.max(Math.ceil(total / perPage), 1);
|
|
1533
|
-
this._currentPage = currentPage;
|
|
1534
|
-
this.setItems(items);
|
|
1535
|
-
}
|
|
1536
|
-
setItems(items) {
|
|
1537
|
-
this._items = items instanceof collection_default ? items : new collection_default(items);
|
|
1538
|
-
this.hasMore = this._items.count() > this._perPage;
|
|
1539
|
-
this._items = this._items.slice(0, this._perPage);
|
|
1540
|
-
}
|
|
1541
|
-
firstItem() {
|
|
1542
|
-
return this.count() > 0 ? (this._currentPage - 1) * this._perPage + 1 : null;
|
|
1543
|
-
}
|
|
1544
|
-
lastItem() {
|
|
1545
|
-
return this.count() > 0 ? (this.firstItem() ?? 0) + this.count() - 1 : null;
|
|
1546
|
-
}
|
|
1547
|
-
hasMorePages() {
|
|
1548
|
-
return this._currentPage < this._lastPage;
|
|
1549
|
-
}
|
|
1550
|
-
get(index) {
|
|
1551
|
-
return this._items.get(index);
|
|
1552
|
-
}
|
|
1553
|
-
count() {
|
|
1554
|
-
return this._items.count();
|
|
1555
|
-
}
|
|
1556
|
-
items() {
|
|
1557
|
-
return this._items;
|
|
1558
|
-
}
|
|
1559
|
-
map(callback) {
|
|
1560
|
-
return this._items.map(callback);
|
|
1561
|
-
}
|
|
1562
|
-
currentPage() {
|
|
1563
|
-
return this._currentPage;
|
|
1564
|
-
}
|
|
1565
|
-
onFirstPage() {
|
|
1566
|
-
return this._currentPage === 1;
|
|
1567
|
-
}
|
|
1568
|
-
perPage() {
|
|
1569
|
-
return this._perPage;
|
|
1570
|
-
}
|
|
1571
|
-
lastPage() {
|
|
1572
|
-
return this._lastPage;
|
|
1573
|
-
}
|
|
1574
|
-
total() {
|
|
1575
|
-
return this._total;
|
|
1576
|
-
}
|
|
1577
|
-
toData() {
|
|
1578
|
-
if (this.constructor.formatter && typeof this.constructor.formatter === "function") {
|
|
1579
|
-
return this.constructor.formatter(this);
|
|
1580
|
-
}
|
|
1581
|
-
return {
|
|
1582
|
-
current_page: this._currentPage,
|
|
1583
|
-
data: this._items.toData(),
|
|
1584
|
-
per_page: this._perPage,
|
|
1585
|
-
total: this._total,
|
|
1586
|
-
last_page: this._lastPage,
|
|
1587
|
-
count: this.count()
|
|
1588
|
-
};
|
|
1589
|
-
}
|
|
1590
|
-
toJSON() {
|
|
1591
|
-
return this.toData();
|
|
1592
|
-
}
|
|
1593
|
-
toJson(...args) {
|
|
1594
|
-
return JSON.stringify(this.toData(), ...args);
|
|
1595
|
-
}
|
|
1596
|
-
};
|
|
1597
|
-
var paginator_default = Paginator;
|
|
1598
|
-
|
|
1599
|
-
// src/query-builder.ts
|
|
1600
|
-
var Inference = class {
|
|
1601
|
-
};
|
|
1602
|
-
var QueryBuilder = class _QueryBuilder extends Inference {
|
|
1603
|
-
model;
|
|
1604
|
-
schema;
|
|
1605
|
-
connector;
|
|
1606
|
-
constructor(config, connector) {
|
|
1607
|
-
super();
|
|
1608
|
-
this.connector = connector(config);
|
|
1609
|
-
return this.asProxy();
|
|
1610
|
-
}
|
|
1611
|
-
asProxy() {
|
|
1612
|
-
const handler = {
|
|
1613
|
-
get: function(target, prop) {
|
|
1614
|
-
if (typeof target[prop] !== "undefined") {
|
|
1615
|
-
return target[prop];
|
|
1616
|
-
}
|
|
1617
|
-
if (["destroy", "schema"].includes(prop)) {
|
|
1618
|
-
return target.connector.schema;
|
|
1619
|
-
}
|
|
1620
|
-
if ([
|
|
1621
|
-
"select",
|
|
1622
|
-
"from",
|
|
1623
|
-
"where",
|
|
1624
|
-
"orWhere",
|
|
1625
|
-
"whereColumn",
|
|
1626
|
-
"whereRaw",
|
|
1627
|
-
"whereNot",
|
|
1628
|
-
"orWhereNot",
|
|
1629
|
-
"whereIn",
|
|
1630
|
-
"orWhereIn",
|
|
1631
|
-
"whereNotIn",
|
|
1632
|
-
"orWhereNotIn",
|
|
1633
|
-
"whereNull",
|
|
1634
|
-
"orWhereNull",
|
|
1635
|
-
"whereNotNull",
|
|
1636
|
-
"orWhereNotNull",
|
|
1637
|
-
"whereExists",
|
|
1638
|
-
"orWhereExists",
|
|
1639
|
-
"whereNotExists",
|
|
1640
|
-
"orWhereNotExists",
|
|
1641
|
-
"whereBetween",
|
|
1642
|
-
"orWhereBetween",
|
|
1643
|
-
"whereNotBetween",
|
|
1644
|
-
"orWhereNotBetween",
|
|
1645
|
-
"whereLike",
|
|
1646
|
-
"orWhereLike",
|
|
1647
|
-
"whereILike",
|
|
1648
|
-
"orWhereILike",
|
|
1649
|
-
"whereJsonObject",
|
|
1650
|
-
"whereJsonPath",
|
|
1651
|
-
"whereJsonSupersetOf",
|
|
1652
|
-
"whereJsonSubsetOf",
|
|
1653
|
-
"join",
|
|
1654
|
-
"joinRaw",
|
|
1655
|
-
"leftJoin",
|
|
1656
|
-
"leftOuterJoin",
|
|
1657
|
-
"rightJoin",
|
|
1658
|
-
"rightOuterJoin",
|
|
1659
|
-
"crossJoin",
|
|
1660
|
-
"transacting",
|
|
1661
|
-
"groupBy",
|
|
1662
|
-
"groupByRaw",
|
|
1663
|
-
"returning",
|
|
1664
|
-
"having",
|
|
1665
|
-
"havingRaw",
|
|
1666
|
-
"havingBetween",
|
|
1667
|
-
"limit",
|
|
1668
|
-
"offset",
|
|
1669
|
-
"orderBy",
|
|
1670
|
-
"orderByRaw",
|
|
1671
|
-
// 'inRandomOrder',
|
|
1672
|
-
"union",
|
|
1673
|
-
"insert",
|
|
1674
|
-
"forUpdate",
|
|
1675
|
-
"forShare",
|
|
1676
|
-
"distinct",
|
|
1677
|
-
"clearOrder",
|
|
1678
|
-
"clear",
|
|
1679
|
-
"clearSelect",
|
|
1680
|
-
"clearWhere",
|
|
1681
|
-
"clearHaving",
|
|
1682
|
-
"clearGroup"
|
|
1683
|
-
].includes(prop)) {
|
|
1684
|
-
return (...args) => {
|
|
1685
|
-
target.connector[prop](...args);
|
|
1686
|
-
return target.asProxy();
|
|
1687
|
-
};
|
|
1688
|
-
}
|
|
1689
|
-
return target.connector[prop];
|
|
1690
|
-
},
|
|
1691
|
-
set: function(target, prop, value) {
|
|
1692
|
-
if (typeof target[prop] !== "undefined") {
|
|
1693
|
-
target[prop] = value;
|
|
1694
|
-
return target;
|
|
1695
|
-
}
|
|
1696
|
-
target.connector[prop] = value;
|
|
1697
|
-
return target;
|
|
1698
|
-
}
|
|
1699
|
-
};
|
|
1700
|
-
return new Proxy(this, handler);
|
|
1701
|
-
}
|
|
1702
|
-
async beginTransaction() {
|
|
1703
|
-
return await this.connector.transaction();
|
|
1704
|
-
}
|
|
1705
|
-
table(table) {
|
|
1706
|
-
const c = this.connector.table(table);
|
|
1707
|
-
return new _QueryBuilder(null, () => c);
|
|
1708
|
-
}
|
|
1709
|
-
transaction(callback) {
|
|
1710
|
-
if (callback) {
|
|
1711
|
-
return this.connector.transaction((trx) => {
|
|
1712
|
-
return callback(new _QueryBuilder(null, () => trx));
|
|
1713
|
-
});
|
|
1714
|
-
}
|
|
1715
|
-
return callback;
|
|
1716
|
-
}
|
|
1717
|
-
async find(id, columns = ["*"]) {
|
|
1718
|
-
return await this.connector.where("id", id).first(...columns);
|
|
1719
|
-
}
|
|
1720
|
-
async get(_columns = ["*"]) {
|
|
1721
|
-
return await this.connector;
|
|
1722
|
-
}
|
|
1723
|
-
async exists() {
|
|
1724
|
-
return await this.connector.first() !== null;
|
|
1725
|
-
}
|
|
1726
|
-
skip(...args) {
|
|
1727
|
-
return this.offset(...args);
|
|
1728
|
-
}
|
|
1729
|
-
take(...args) {
|
|
1730
|
-
return this.limit(...args);
|
|
1731
|
-
}
|
|
1732
|
-
async chunk(count, callback) {
|
|
1733
|
-
if (this.connector._statements.filter((item) => item.grouping === "order").length === 0) {
|
|
1734
|
-
throw new Error("You must specify an orderBy clause when using this function.");
|
|
1735
|
-
}
|
|
1736
|
-
let page = 1;
|
|
1737
|
-
let countResults;
|
|
1738
|
-
do {
|
|
1739
|
-
const builder = this.clone();
|
|
1740
|
-
const results = await builder.forPage(page, count).get();
|
|
1741
|
-
countResults = results.length;
|
|
1742
|
-
if (countResults == 0) {
|
|
1743
|
-
break;
|
|
1744
|
-
}
|
|
1745
|
-
const bool = await callback(results, page);
|
|
1746
|
-
if (bool === false) {
|
|
1747
|
-
return false;
|
|
1748
|
-
}
|
|
1749
|
-
page++;
|
|
1750
|
-
} while (countResults === count);
|
|
1751
|
-
return true;
|
|
1752
|
-
}
|
|
1753
|
-
async paginate(page = 1, perPage = 15) {
|
|
1754
|
-
const query = this.clone();
|
|
1755
|
-
const total = await query.clearOrder().count("*");
|
|
1756
|
-
let results;
|
|
1757
|
-
if (total > 0) {
|
|
1758
|
-
const skip = (page - 1) * perPage;
|
|
1759
|
-
this.take(perPage).skip(skip);
|
|
1760
|
-
results = await this.get();
|
|
1761
|
-
} else {
|
|
1762
|
-
results = [];
|
|
1763
|
-
}
|
|
1764
|
-
return new paginator_default(results, parseInt(total), perPage, page);
|
|
1765
|
-
}
|
|
1766
|
-
forPage(page = 1, perPage = 15) {
|
|
1767
|
-
return this.offset((page - 1) * perPage).limit(perPage);
|
|
1768
|
-
}
|
|
1769
|
-
toSQL(...args) {
|
|
1770
|
-
return this.connector.toSQL(...args);
|
|
1771
|
-
}
|
|
1772
|
-
async count(column) {
|
|
1773
|
-
const [{ aggregate }] = await this.connector.count(column, { as: "aggregate" });
|
|
1774
|
-
return Number(aggregate);
|
|
1775
|
-
}
|
|
1776
|
-
async min(column) {
|
|
1777
|
-
const [{ aggregate }] = await this.connector.min(column, { as: "aggregate" });
|
|
1778
|
-
return Number(aggregate);
|
|
1779
|
-
}
|
|
1780
|
-
async max(column) {
|
|
1781
|
-
const [{ aggregate }] = await this.connector.max(column, { as: "aggregate" });
|
|
1782
|
-
return Number(aggregate);
|
|
1783
|
-
}
|
|
1784
|
-
async sum(column) {
|
|
1785
|
-
const [{ aggregate }] = await this.connector.sum(column, { as: "aggregate" });
|
|
1786
|
-
return Number(aggregate);
|
|
1787
|
-
}
|
|
1788
|
-
async avg(column) {
|
|
1789
|
-
const [{ aggregate }] = await this.connector.avg(column, { as: "aggregate" });
|
|
1790
|
-
return Number(aggregate);
|
|
1791
|
-
}
|
|
1792
|
-
clone() {
|
|
1793
|
-
const c = this.connector.clone();
|
|
1794
|
-
return new _QueryBuilder(null, () => c);
|
|
1795
|
-
}
|
|
1796
|
-
async delete() {
|
|
1797
|
-
return await this.connector.delete();
|
|
1798
|
-
}
|
|
1799
|
-
async insert(...args) {
|
|
1800
|
-
return await this.connector.insert(...args);
|
|
1801
|
-
}
|
|
1802
|
-
async update(...args) {
|
|
1803
|
-
return await this.connector.update(...args);
|
|
1804
|
-
}
|
|
1805
|
-
destroy(...args) {
|
|
1806
|
-
return this.connector.destroy(...args);
|
|
1807
|
-
}
|
|
1808
|
-
get _statements() {
|
|
1809
|
-
return this.connector._statements;
|
|
1810
|
-
}
|
|
1811
|
-
get _single() {
|
|
1812
|
-
return this.connector._single;
|
|
1813
|
-
}
|
|
1814
|
-
get from() {
|
|
1815
|
-
return this.connector.from;
|
|
1816
|
-
}
|
|
1817
|
-
};
|
|
1818
|
-
var query_builder_default = QueryBuilder;
|
|
1819
|
-
|
|
1820
|
-
// src/arquebus.ts
|
|
1821
|
-
var arquebus = class _arquebus {
|
|
1822
|
-
static connectorFactory = null;
|
|
1823
|
-
static instance = null;
|
|
1824
|
-
manager;
|
|
1825
|
-
connections;
|
|
1826
|
-
models;
|
|
1827
|
-
constructor() {
|
|
1828
|
-
this.manager = {};
|
|
1829
|
-
this.connections = {};
|
|
1830
|
-
this.models = {};
|
|
1831
|
-
}
|
|
1832
|
-
getConstructor() {
|
|
1833
|
-
return this.constructor;
|
|
1834
|
-
}
|
|
1835
|
-
static getInstance() {
|
|
1836
|
-
if (this.instance === null) {
|
|
1837
|
-
this.instance = new _arquebus();
|
|
1838
|
-
}
|
|
1839
|
-
return this.instance;
|
|
1840
|
-
}
|
|
1841
|
-
static connection(connection = null) {
|
|
1842
|
-
return this.getInstance().getConnection(connection);
|
|
1843
|
-
}
|
|
1844
|
-
static setConnectorFactory(connectorFactory) {
|
|
1845
|
-
this.connectorFactory = connectorFactory;
|
|
1846
|
-
}
|
|
1847
|
-
static getConnectorFactory() {
|
|
1848
|
-
return this.connectorFactory ?? Knex;
|
|
1849
|
-
}
|
|
1850
|
-
static addConnection(config, name = "default") {
|
|
1851
|
-
return this.getInstance().addConnection(config, name);
|
|
1852
|
-
}
|
|
1853
|
-
static beginTransaction(connection = null) {
|
|
1854
|
-
return this.getInstance().beginTransaction(connection);
|
|
1855
|
-
}
|
|
1856
|
-
static transaction(callback, connection = null) {
|
|
1857
|
-
return this.getInstance().transaction(callback, connection);
|
|
1858
|
-
}
|
|
1859
|
-
static table(name, connection = null) {
|
|
1860
|
-
return this.getInstance().table(name, connection);
|
|
1861
|
-
}
|
|
1862
|
-
static schema(connection = null) {
|
|
1863
|
-
return this.getInstance().schema(connection);
|
|
1864
|
-
}
|
|
1865
|
-
static async destroyAll() {
|
|
1866
|
-
await this.getInstance().destroyAll();
|
|
1867
|
-
}
|
|
1868
|
-
static createModel(name, options) {
|
|
1869
|
-
return this.getInstance().createModel(name, options);
|
|
1870
|
-
}
|
|
1871
|
-
connection(connection = null) {
|
|
1872
|
-
return this.getConnection(connection);
|
|
1873
|
-
}
|
|
1874
|
-
getConnection(name = null) {
|
|
1875
|
-
name = name || "default";
|
|
1876
|
-
if (this.manager[name] === void 0) {
|
|
1877
|
-
const queryBuilder = new query_builder_default(this.connections[name], _arquebus.getConnectorFactory());
|
|
1878
|
-
this.manager[name] = queryBuilder;
|
|
1879
|
-
}
|
|
1880
|
-
return this.manager[name];
|
|
1881
|
-
}
|
|
1882
|
-
addConnection(config, name = "default") {
|
|
1883
|
-
this.connections[name] = {
|
|
1884
|
-
...config,
|
|
1885
|
-
connection: {
|
|
1886
|
-
...config.connection,
|
|
1887
|
-
dateStrings: true,
|
|
1888
|
-
typeCast: function(field, next) {
|
|
1889
|
-
if (field.type === "JSON") {
|
|
1890
|
-
return field.string("utf8");
|
|
1891
|
-
}
|
|
1892
|
-
return next();
|
|
1893
|
-
}
|
|
1894
|
-
}
|
|
1895
|
-
};
|
|
1896
|
-
}
|
|
1897
|
-
beginTransaction(connection = null) {
|
|
1898
|
-
return this.connection(connection).beginTransaction();
|
|
1899
|
-
}
|
|
1900
|
-
transaction(callback, connection = null) {
|
|
1901
|
-
return this.connection(connection).transaction(callback);
|
|
1902
|
-
}
|
|
1903
|
-
table(name, connection = null) {
|
|
1904
|
-
return this.connection(connection).table(name);
|
|
1905
|
-
}
|
|
1906
|
-
schema(connection = null) {
|
|
1907
|
-
return this.connection(connection).schema;
|
|
1908
|
-
}
|
|
1909
|
-
async destroyAll() {
|
|
1910
|
-
await Promise.all(Object.values(this.manager).map((connection) => {
|
|
1911
|
-
return connection?.destroy();
|
|
1912
|
-
}));
|
|
1913
|
-
}
|
|
1914
|
-
createModel(name, options = {}) {
|
|
1915
|
-
let BaseModel2 = Model;
|
|
1916
|
-
if ("plugins" in options) {
|
|
1917
|
-
BaseModel2 = compose(BaseModel2, ...options.plugins ?? []);
|
|
1918
|
-
}
|
|
1919
|
-
this.models = {
|
|
1920
|
-
...this.models,
|
|
1921
|
-
[name]: class extends BaseModel2 {
|
|
1922
|
-
table = options?.table ?? null;
|
|
1923
|
-
connection = options?.connection ?? null;
|
|
1924
|
-
timestamps = options?.timestamps ?? true;
|
|
1925
|
-
primaryKey = options?.primaryKey ?? "id";
|
|
1926
|
-
keyType = options?.keyType ?? "int";
|
|
1927
|
-
incrementing = options?.incrementing ?? true;
|
|
1928
|
-
with = options?.with ?? [];
|
|
1929
|
-
casts = options?.casts ?? {};
|
|
1930
|
-
static CREATED_AT = options?.CREATED_AT ?? "created_at";
|
|
1931
|
-
static UPDATED_AT = options?.UPDATED_AT ?? "updated_at";
|
|
1932
|
-
static DELETED_AT = options?.DELETED_AT ?? "deleted_at";
|
|
1933
|
-
}
|
|
1934
|
-
};
|
|
1935
|
-
if ("attributes" in options) {
|
|
1936
|
-
for (const attribute in options.attributes) {
|
|
1937
|
-
if (options.attributes[attribute] instanceof attribute_default === false) {
|
|
1938
|
-
throw new Error('Attribute must be an instance of "Attribute"');
|
|
1939
|
-
}
|
|
1940
|
-
this.models[name].prototype[getAttrMethod(attribute)] = () => options.attributes?.[attribute];
|
|
1941
|
-
}
|
|
1942
|
-
}
|
|
1943
|
-
if ("relations" in options) {
|
|
1944
|
-
for (const relation in options.relations) {
|
|
1945
|
-
this.models[name].prototype[getRelationMethod(relation)] = function() {
|
|
1946
|
-
return options.relations?.[relation](this);
|
|
1947
|
-
};
|
|
1948
|
-
}
|
|
1949
|
-
}
|
|
1950
|
-
if ("scopes" in options) {
|
|
1951
|
-
for (const scope in options.scopes) {
|
|
1952
|
-
this.models[name].prototype[getScopeMethod(scope)] = options.scopes[scope];
|
|
1953
|
-
}
|
|
1954
|
-
}
|
|
1955
|
-
this.models[name].setConnectionResolver(this);
|
|
1956
|
-
return this.models[name];
|
|
1957
|
-
}
|
|
1958
|
-
};
|
|
1959
|
-
var arquebus_default = arquebus;
|
|
1960
|
-
|
|
1961
|
-
// src/model.ts
|
|
1962
|
-
import collect4 from "collect.js";
|
|
1963
|
-
import { assign as merge } from "radashi";
|
|
1964
|
-
import pluralize from "pluralize";
|
|
1965
|
-
var BaseModel = compose(
|
|
1966
|
-
class {
|
|
1967
|
-
},
|
|
1968
|
-
has_attributes_default,
|
|
1969
|
-
hides_attributes_default,
|
|
1970
|
-
has_relations_default,
|
|
1971
|
-
has_timestamps_default,
|
|
1972
|
-
has_hooks_default,
|
|
1973
|
-
has_global_scopes_default,
|
|
1974
|
-
unique_ids_default
|
|
1975
|
-
);
|
|
1976
|
-
var Model = class _Model extends BaseModel {
|
|
1977
|
-
primaryKey = "id";
|
|
1978
|
-
builder = null;
|
|
1979
|
-
table = null;
|
|
1980
|
-
keyType = "int";
|
|
1981
|
-
incrementing = true;
|
|
1982
|
-
withCount = [];
|
|
1983
|
-
// protected
|
|
1984
|
-
perPage = 15;
|
|
1985
|
-
static globalScopes = {};
|
|
1986
|
-
static pluginInitializers = {};
|
|
1987
|
-
static _booted = {};
|
|
1988
|
-
static resolver;
|
|
1989
|
-
connection = null;
|
|
1990
|
-
eagerLoad = {};
|
|
1991
|
-
exists = false;
|
|
1992
|
-
with = [];
|
|
1993
|
-
trx = null;
|
|
1994
|
-
constructor(attributes = {}) {
|
|
1995
|
-
super();
|
|
1996
|
-
this.bootIfNotBooted();
|
|
1997
|
-
this.initializePlugins();
|
|
1998
|
-
this.syncOriginal();
|
|
1999
|
-
this.fill(attributes);
|
|
2000
|
-
return this.asProxy();
|
|
2001
|
-
}
|
|
2002
|
-
static query(trx = null) {
|
|
2003
|
-
const instance = new this();
|
|
2004
|
-
return instance.newQuery(trx);
|
|
2005
|
-
}
|
|
2006
|
-
static on(connection = null) {
|
|
2007
|
-
const instance = new this();
|
|
2008
|
-
instance.setConnection(connection);
|
|
2009
|
-
return instance.newQuery();
|
|
2010
|
-
}
|
|
2011
|
-
static init(attributes = {}) {
|
|
2012
|
-
return new this(attributes);
|
|
2013
|
-
}
|
|
2014
|
-
static extend(plugin, options) {
|
|
2015
|
-
plugin(this, options);
|
|
2016
|
-
}
|
|
2017
|
-
static make(attributes = {}) {
|
|
2018
|
-
const instance = new this();
|
|
2019
|
-
for (const attribute in attributes) {
|
|
2020
|
-
if (typeof instance[getRelationMethod(attribute)] !== "function") {
|
|
2021
|
-
instance.setAttribute(attribute, attributes[attribute]);
|
|
2022
|
-
} else {
|
|
2023
|
-
const relation = instance[getRelationMethod(attribute)]();
|
|
2024
|
-
const related = relation.getRelated().constructor;
|
|
2025
|
-
if (relation instanceof has_one_default || relation instanceof belongs_to_default) {
|
|
2026
|
-
instance.setRelation(attribute, related.make(attributes[attribute]));
|
|
2027
|
-
} else if ((relation instanceof has_many_default || relation instanceof belongs_to_many_default) && Array.isArray(attributes[attribute])) {
|
|
2028
|
-
instance.setRelation(attribute, new collection_default(attributes[attribute].map((item) => related.make(item))));
|
|
2029
|
-
}
|
|
2030
|
-
}
|
|
2031
|
-
}
|
|
2032
|
-
return instance;
|
|
2033
|
-
}
|
|
2034
|
-
getConstructor() {
|
|
2035
|
-
return this.constructor;
|
|
2036
|
-
}
|
|
2037
|
-
bootIfNotBooted() {
|
|
2038
|
-
if (this.constructor._booted[this.constructor.name] === void 0) {
|
|
2039
|
-
this.constructor._booted[this.constructor.name] = true;
|
|
2040
|
-
this.constructor.booting();
|
|
2041
|
-
this.initialize();
|
|
2042
|
-
this.constructor.boot();
|
|
2043
|
-
this.constructor.booted();
|
|
2044
|
-
}
|
|
2045
|
-
}
|
|
2046
|
-
static booting() {
|
|
2047
|
-
}
|
|
2048
|
-
static boot() {
|
|
2049
|
-
}
|
|
2050
|
-
static booted() {
|
|
2051
|
-
}
|
|
2052
|
-
static setConnectionResolver(resolver) {
|
|
2053
|
-
this.resolver = resolver;
|
|
2054
|
-
}
|
|
2055
|
-
initialize() {
|
|
2056
|
-
}
|
|
2057
|
-
initializePlugins() {
|
|
2058
|
-
if (typeof this.constructor.pluginInitializers[this.constructor.name] === "undefined") {
|
|
2059
|
-
return;
|
|
2060
|
-
}
|
|
2061
|
-
for (const method of this.constructor.pluginInitializers[this.constructor.name]) {
|
|
2062
|
-
this[method]();
|
|
2063
|
-
}
|
|
2064
|
-
}
|
|
2065
|
-
addPluginInitializer(method) {
|
|
2066
|
-
if (!this.constructor.pluginInitializers[this.constructor.name]) {
|
|
2067
|
-
this.constructor.pluginInitializers[this.constructor.name] = [];
|
|
2068
|
-
}
|
|
2069
|
-
this.constructor.pluginInitializers[this.constructor.name].push(method);
|
|
2070
|
-
}
|
|
2071
|
-
newInstance(attributes = {}, exists = false) {
|
|
2072
|
-
const model = new this.constructor();
|
|
2073
|
-
model.exists = exists;
|
|
2074
|
-
model.setConnection(this.getConnectionName());
|
|
2075
|
-
model.setTable(this.getTable());
|
|
2076
|
-
model.fill(attributes);
|
|
2077
|
-
return model;
|
|
2078
|
-
}
|
|
2079
|
-
newFromBuilder(attributes = {}, connection = null) {
|
|
2080
|
-
const model = this.newInstance({}, true);
|
|
2081
|
-
model.setRawAttributes(attributes, true);
|
|
2082
|
-
model.setConnection(connection || this.getConnectionName());
|
|
2083
|
-
return model;
|
|
2084
|
-
}
|
|
2085
|
-
asProxy() {
|
|
2086
|
-
const handler = {
|
|
2087
|
-
get: function(target, prop) {
|
|
2088
|
-
if (target[prop] !== void 0) {
|
|
2089
|
-
return target[prop];
|
|
2090
|
-
}
|
|
2091
|
-
if (typeof prop === "string") {
|
|
2092
|
-
return target.getAttribute(prop);
|
|
2093
|
-
}
|
|
2094
|
-
},
|
|
2095
|
-
set: function(target, prop, value) {
|
|
2096
|
-
if (target[prop] !== void 0 && typeof target !== "function") {
|
|
2097
|
-
target[prop] = value;
|
|
2098
|
-
return target;
|
|
2099
|
-
}
|
|
2100
|
-
if (typeof prop === "string") {
|
|
2101
|
-
return target.setAttribute(prop, value);
|
|
2102
|
-
}
|
|
2103
|
-
return target;
|
|
2104
|
-
}
|
|
2105
|
-
};
|
|
2106
|
-
return new Proxy(this, handler);
|
|
2107
|
-
}
|
|
2108
|
-
getKey() {
|
|
2109
|
-
return this.getAttribute(this.getKeyName());
|
|
2110
|
-
}
|
|
2111
|
-
getKeyName() {
|
|
2112
|
-
return this.primaryKey;
|
|
2113
|
-
}
|
|
2114
|
-
getForeignKey() {
|
|
2115
|
-
return snakeCase(this.constructor.name) + "_" + this.getKeyName();
|
|
2116
|
-
}
|
|
2117
|
-
getConnectionName() {
|
|
2118
|
-
return this.connection;
|
|
2119
|
-
}
|
|
2120
|
-
getTable() {
|
|
2121
|
-
return this.table || pluralize(snakeCase(this.constructor.name));
|
|
2122
|
-
}
|
|
2123
|
-
getConnection() {
|
|
2124
|
-
if (this.constructor.resolver) {
|
|
2125
|
-
return this.constructor.resolver.getConnection(this.connection);
|
|
2126
|
-
}
|
|
2127
|
-
return arquebus_default.connection(this.connection);
|
|
2128
|
-
}
|
|
2129
|
-
setConnection(connection) {
|
|
2130
|
-
this.connection = connection;
|
|
2131
|
-
return this;
|
|
2132
|
-
}
|
|
2133
|
-
getKeyType() {
|
|
2134
|
-
return this.keyType;
|
|
2135
|
-
}
|
|
2136
|
-
newQuery(trx = null) {
|
|
2137
|
-
return this.addGlobalScopes(this.newQueryWithoutScopes(trx));
|
|
2138
|
-
}
|
|
2139
|
-
newQueryWithoutScopes(trx = null) {
|
|
2140
|
-
return this.newModelQuery(trx).with(this.with).withCount(this.withCount);
|
|
2141
|
-
}
|
|
2142
|
-
newModelQuery(trx = null) {
|
|
2143
|
-
const builder = new builder_default(trx || this.getConnection());
|
|
2144
|
-
return builder.setModel(this);
|
|
2145
|
-
}
|
|
2146
|
-
addGlobalScopes(builder) {
|
|
2147
|
-
const globalScopes = this.getGlobalScopes();
|
|
2148
|
-
for (const identifier in globalScopes) {
|
|
2149
|
-
const scope = globalScopes[identifier];
|
|
2150
|
-
builder.withGlobalScope(identifier, scope);
|
|
2151
|
-
}
|
|
2152
|
-
return builder;
|
|
2153
|
-
}
|
|
2154
|
-
hasNamedScope(name) {
|
|
2155
|
-
const scope = getScopeMethod(name);
|
|
2156
|
-
return typeof this[scope] === "function";
|
|
2157
|
-
}
|
|
2158
|
-
callNamedScope(scope, parameters) {
|
|
2159
|
-
const scopeMethod = getScopeMethod(scope);
|
|
2160
|
-
return this[scopeMethod](...parameters);
|
|
2161
|
-
}
|
|
2162
|
-
setTable(table) {
|
|
2163
|
-
this.table = table;
|
|
2164
|
-
return this;
|
|
2165
|
-
}
|
|
2166
|
-
newCollection(models = []) {
|
|
2167
|
-
return new collection_default(models);
|
|
2168
|
-
}
|
|
2169
|
-
async load(...relations) {
|
|
2170
|
-
const query = this.constructor.query().with(...relations);
|
|
2171
|
-
await query.eagerLoadRelations([this]);
|
|
2172
|
-
return this;
|
|
2173
|
-
}
|
|
2174
|
-
async loadAggregate(relations, column, callback = null) {
|
|
2175
|
-
console.log(relations);
|
|
2176
|
-
await new collection_default([this]).loadAggregate(relations, column, callback);
|
|
2177
|
-
return this;
|
|
2178
|
-
}
|
|
2179
|
-
async loadCount(...relations) {
|
|
2180
|
-
relations = flattenDeep(relations);
|
|
2181
|
-
return await this.loadAggregate(relations, "*", "count");
|
|
2182
|
-
}
|
|
2183
|
-
async loadMax(relations, column) {
|
|
2184
|
-
return await this.loadAggregate(relations, column, "max");
|
|
2185
|
-
}
|
|
2186
|
-
async loadMin(relations, column) {
|
|
2187
|
-
return await this.loadAggregate(relations, column, "min");
|
|
2188
|
-
}
|
|
2189
|
-
async loadSum(relations, column) {
|
|
2190
|
-
return await this.loadAggregate(relations, column, "sum");
|
|
2191
|
-
}
|
|
2192
|
-
async increment(column, amount = 1, extra = {}, options = {}) {
|
|
2193
|
-
return await this.incrementOrDecrement(column, amount, extra, "increment", options);
|
|
2194
|
-
}
|
|
2195
|
-
async decrement(column, amount = 1, extra = {}, options = {}) {
|
|
2196
|
-
return await this.incrementOrDecrement(column, amount, extra, "decrement", options);
|
|
2197
|
-
}
|
|
2198
|
-
async incrementOrDecrement(column, amount, extra, method, options) {
|
|
2199
|
-
const query = this.newModelQuery(options.client);
|
|
2200
|
-
if (!this.exists) {
|
|
2201
|
-
return await query[method](column, amount, extra);
|
|
2202
|
-
}
|
|
2203
|
-
this.attributes[column] = this[column] + (method === "increment" ? amount : amount * -1);
|
|
2204
|
-
for (const key in extra) {
|
|
2205
|
-
this.attributes[key] = extra[key];
|
|
2206
|
-
}
|
|
2207
|
-
await this.execHooks("updating", options);
|
|
2208
|
-
return await tap(await query.where(this.getKeyName(), this.getKey())[method](column, amount, extra), async () => {
|
|
2209
|
-
this.syncChanges();
|
|
2210
|
-
await this.execHooks("updated", options);
|
|
2211
|
-
this.syncOriginalAttribute(column);
|
|
2212
|
-
});
|
|
2213
|
-
}
|
|
2214
|
-
toData() {
|
|
2215
|
-
return merge(this.attributesToData(), this.relationsToData());
|
|
2216
|
-
}
|
|
2217
|
-
toJSON() {
|
|
2218
|
-
return this.toData();
|
|
2219
|
-
}
|
|
2220
|
-
toJson(...args) {
|
|
2221
|
-
return JSON.stringify(this.toData(), ...args);
|
|
2222
|
-
}
|
|
2223
|
-
toString() {
|
|
2224
|
-
return this.toJson();
|
|
2225
|
-
}
|
|
2226
|
-
fill(attributes) {
|
|
2227
|
-
for (const key in attributes) {
|
|
2228
|
-
this.setAttribute(key, attributes[key]);
|
|
2229
|
-
}
|
|
2230
|
-
return this;
|
|
2231
|
-
}
|
|
2232
|
-
transacting(trx) {
|
|
2233
|
-
this.trx = trx;
|
|
2234
|
-
return this;
|
|
2235
|
-
}
|
|
2236
|
-
trashed() {
|
|
2237
|
-
return this[this.getDeletedAtColumn()] !== null;
|
|
2238
|
-
}
|
|
2239
|
-
getIncrementing() {
|
|
2240
|
-
return this.incrementing;
|
|
2241
|
-
}
|
|
2242
|
-
setIncrementing(value) {
|
|
2243
|
-
this.incrementing = value;
|
|
2244
|
-
return this;
|
|
2245
|
-
}
|
|
2246
|
-
async save(options = {}) {
|
|
2247
|
-
const query = this.newModelQuery(options.client);
|
|
2248
|
-
let saved;
|
|
2249
|
-
await this.execHooks("saving", options);
|
|
2250
|
-
if (this.exists) {
|
|
2251
|
-
if (this.isDirty() === false) {
|
|
2252
|
-
saved = true;
|
|
2253
|
-
} else {
|
|
2254
|
-
await this.execHooks("updating", options);
|
|
2255
|
-
if (this.usesTimestamps()) {
|
|
2256
|
-
this.updateTimestamps();
|
|
2257
|
-
}
|
|
2258
|
-
const dirty = this.getDirty();
|
|
2259
|
-
if (Object.keys(dirty).length > 0) {
|
|
2260
|
-
await query.where(this.getKeyName(), this.getKey()).query.update(dirty);
|
|
2261
|
-
this.syncChanges();
|
|
2262
|
-
await this.execHooks("updated", options);
|
|
2263
|
-
}
|
|
2264
|
-
saved = true;
|
|
2265
|
-
}
|
|
2266
|
-
} else {
|
|
2267
|
-
if (this.usesUniqueIds()) {
|
|
2268
|
-
this.setUniqueIds();
|
|
2269
|
-
}
|
|
2270
|
-
await this.execHooks("creating", options);
|
|
2271
|
-
if (this.usesTimestamps()) {
|
|
2272
|
-
this.updateTimestamps();
|
|
2273
|
-
}
|
|
2274
|
-
const attributes = this.getAttributes();
|
|
2275
|
-
if (this.getIncrementing()) {
|
|
2276
|
-
const keyName = this.getKeyName();
|
|
2277
|
-
const data = await query.insert([attributes], [keyName]);
|
|
2278
|
-
this.setAttribute(keyName, data[0]?.[keyName] || data[0]);
|
|
2279
|
-
} else {
|
|
2280
|
-
if (Object.keys(attributes).length > 0) {
|
|
2281
|
-
await query.insert(attributes);
|
|
2282
|
-
}
|
|
2283
|
-
}
|
|
2284
|
-
this.exists = true;
|
|
2285
|
-
await this.execHooks("created", options);
|
|
2286
|
-
saved = true;
|
|
2287
|
-
}
|
|
2288
|
-
if (saved) {
|
|
2289
|
-
await this.execHooks("saved", options);
|
|
2290
|
-
this.syncOriginal();
|
|
2291
|
-
}
|
|
2292
|
-
return saved;
|
|
2293
|
-
}
|
|
2294
|
-
async update(attributes = {}, options = {}) {
|
|
2295
|
-
if (!this.exists) {
|
|
2296
|
-
return false;
|
|
2297
|
-
}
|
|
2298
|
-
for (const key in attributes) {
|
|
2299
|
-
this[key] = attributes[key];
|
|
2300
|
-
}
|
|
2301
|
-
return await this.save(options);
|
|
2302
|
-
}
|
|
2303
|
-
async delete(options = {}) {
|
|
2304
|
-
await this.execHooks("deleting", options);
|
|
2305
|
-
await this.performDeleteOnModel(options);
|
|
2306
|
-
await this.execHooks("deleted", options);
|
|
2307
|
-
return true;
|
|
2308
|
-
}
|
|
2309
|
-
async performDeleteOnModel(options = {}) {
|
|
2310
|
-
await this.setKeysForSaveQuery(this.newModelQuery(options.client)).delete();
|
|
2311
|
-
this.exists = false;
|
|
2312
|
-
}
|
|
2313
|
-
setKeysForSaveQuery(query) {
|
|
2314
|
-
query.where(this.getKeyName(), "=", this.getKey());
|
|
2315
|
-
return query;
|
|
2316
|
-
}
|
|
2317
|
-
async forceDelete(options = {}) {
|
|
2318
|
-
return await this.delete(options);
|
|
2319
|
-
}
|
|
2320
|
-
fresh() {
|
|
2321
|
-
if (!this.exists) {
|
|
2322
|
-
return;
|
|
2323
|
-
}
|
|
2324
|
-
return this.constructor.query().where(this.getKeyName(), this.getKey()).first();
|
|
2325
|
-
}
|
|
2326
|
-
async refresh() {
|
|
2327
|
-
if (!this.exists) {
|
|
2328
|
-
return Promise.resolve(void 0);
|
|
2329
|
-
}
|
|
2330
|
-
const model = await this.constructor.query().where(this.getKeyName(), this.getKey()).first();
|
|
2331
|
-
this.attributes = { ...model.attributes };
|
|
2332
|
-
await this.load(collect4(this.relations).reject((relation) => {
|
|
2333
|
-
return relation instanceof Pivot;
|
|
2334
|
-
}).keys().all());
|
|
2335
|
-
this.syncOriginal();
|
|
2336
|
-
return this;
|
|
2337
|
-
}
|
|
2338
|
-
newPivot(parent, attributes, table, exists, using = null) {
|
|
2339
|
-
return using ? using.fromRawAttributes(parent, attributes, table, exists) : Pivot.fromAttributes(parent, attributes, table, exists);
|
|
2340
|
-
}
|
|
2341
|
-
qualifyColumn(column) {
|
|
2342
|
-
if (column.includes(".")) {
|
|
2343
|
-
return column;
|
|
2344
|
-
}
|
|
2345
|
-
return `${this.getTable()}.${column}`;
|
|
2346
|
-
}
|
|
2347
|
-
getQualifiedKeyName() {
|
|
2348
|
-
return this.qualifyColumn(this.getKeyName());
|
|
2349
|
-
}
|
|
2350
|
-
async push(options = {}) {
|
|
2351
|
-
const saved = await this.save(options);
|
|
2352
|
-
if (!saved) {
|
|
2353
|
-
return false;
|
|
2354
|
-
}
|
|
2355
|
-
for (const relation in this.relations) {
|
|
2356
|
-
let models = this.relations[relation];
|
|
2357
|
-
models = models instanceof collection_default ? models.all() : [models];
|
|
2358
|
-
for (const model of models) {
|
|
2359
|
-
if (!await model.push(options)) {
|
|
2360
|
-
return false;
|
|
2361
|
-
}
|
|
2362
|
-
}
|
|
2363
|
-
;
|
|
2364
|
-
}
|
|
2365
|
-
return true;
|
|
2366
|
-
}
|
|
2367
|
-
is(model) {
|
|
2368
|
-
return model && model instanceof _Model && this.getKey() === model.getKey() && this.getTable() === model.getTable() && this.getConnectionName() === model.getConnectionName();
|
|
2369
|
-
}
|
|
2370
|
-
isNot(model) {
|
|
2371
|
-
return !this.is(model);
|
|
2372
|
-
}
|
|
2373
|
-
};
|
|
2374
|
-
var Pivot = class extends Model {
|
|
2375
|
-
incrementing = false;
|
|
2376
|
-
guarded = [];
|
|
2377
|
-
pivotParent = null;
|
|
2378
|
-
foreignKey = null;
|
|
2379
|
-
relatedKey = null;
|
|
2380
|
-
setPivotKeys(foreignKey, relatedKey) {
|
|
2381
|
-
this.foreignKey = foreignKey;
|
|
2382
|
-
this.relatedKey = relatedKey;
|
|
2383
|
-
return this;
|
|
2384
|
-
}
|
|
2385
|
-
static fromRawAttributes(parent, attributes, table, exists = false) {
|
|
2386
|
-
const instance = this.fromAttributes(parent, {}, table, exists);
|
|
2387
|
-
instance.timestamps = instance.hasTimestampAttributes(attributes);
|
|
2388
|
-
instance.attributes = attributes;
|
|
2389
|
-
instance.exists = exists;
|
|
2390
|
-
return instance;
|
|
2391
|
-
}
|
|
2392
|
-
static fromAttributes(parent, attributes, table, exists = false) {
|
|
2393
|
-
const instance = new this();
|
|
2394
|
-
instance.timestamps = instance.hasTimestampAttributes(attributes);
|
|
2395
|
-
instance.setConnection(parent.connection).setTable(table).fill(attributes).syncOriginal();
|
|
2396
|
-
instance.pivotParent = parent;
|
|
2397
|
-
instance.exists = exists;
|
|
2398
|
-
return instance;
|
|
2399
|
-
}
|
|
2400
|
-
hasTimestampAttributes(attributes = null) {
|
|
2401
|
-
return (attributes || this.attributes)[this.constructor.CREATED_AT] !== void 0;
|
|
2402
|
-
}
|
|
2403
|
-
};
|
|
2404
|
-
var model_default = Model;
|
|
2405
|
-
|
|
2406
|
-
// src/collection.ts
|
|
2407
|
-
var Collection = class _Collection extends BaseCollection {
|
|
2408
|
-
newConstructor(...args) {
|
|
2409
|
-
const constr = this.getConstructor();
|
|
2410
|
-
return new constr(...args);
|
|
2411
|
-
}
|
|
2412
|
-
getConstructor() {
|
|
2413
|
-
return this.constructor;
|
|
2414
|
-
}
|
|
2415
|
-
async load(...relations) {
|
|
2416
|
-
if (this.isNotEmpty()) {
|
|
2417
|
-
const query = this.first().constructor.query().with(...relations);
|
|
2418
|
-
const items = await query.eagerLoadRelations(this.items);
|
|
2419
|
-
return this.newConstructor(items);
|
|
2420
|
-
}
|
|
2421
|
-
return this;
|
|
2422
|
-
}
|
|
2423
|
-
async loadAggregate(relations, column, action = null) {
|
|
2424
|
-
if (this.isEmpty()) {
|
|
2425
|
-
return this;
|
|
2426
|
-
}
|
|
2427
|
-
const models = (await this.first().newModelQuery().whereIn(this.first().getKeyName(), this.modelKeys()).select(this.first().getKeyName()).withAggregate(relations, column, action).get()).keyBy(this.first().getKeyName());
|
|
2428
|
-
const attributes = difference2(Object.keys(models.first().getAttributes()), [models.first().getKeyName()]);
|
|
2429
|
-
this.each((model) => {
|
|
2430
|
-
const extraAttributes = pick(models.get(model.getKey()).getAttributes(), attributes);
|
|
2431
|
-
model.fill(extraAttributes).syncOriginalAttributes(...attributes);
|
|
2432
|
-
});
|
|
2433
|
-
return this;
|
|
2434
|
-
}
|
|
2435
|
-
loadCount(relations) {
|
|
2436
|
-
return this.loadAggregate(relations, "*", "count");
|
|
2437
|
-
}
|
|
2438
|
-
loadMax(relation, column) {
|
|
2439
|
-
return this.loadAggregate(relation, column, "max");
|
|
2440
|
-
}
|
|
2441
|
-
loadMin(relation, column) {
|
|
2442
|
-
return this.loadAggregate(relation, column, "min");
|
|
2443
|
-
}
|
|
2444
|
-
loadSum(relation, column) {
|
|
2445
|
-
return this.loadAggregate(relation, column, "sum");
|
|
2446
|
-
}
|
|
2447
|
-
loadAvg(relation, column) {
|
|
2448
|
-
return this.loadAggregate(relation, column, "avg");
|
|
2449
|
-
}
|
|
2450
|
-
mapThen(callback) {
|
|
2451
|
-
return Promise.all(this.map(callback));
|
|
2452
|
-
}
|
|
2453
|
-
modelKeys() {
|
|
2454
|
-
return this.all().map((item) => item.getKey());
|
|
2455
|
-
}
|
|
2456
|
-
contains(key, operator, value) {
|
|
2457
|
-
if (arguments.length > 1) {
|
|
2458
|
-
return super.contains(key, value ?? operator);
|
|
2459
|
-
}
|
|
2460
|
-
if (key instanceof model_default) {
|
|
2461
|
-
return super.contains((model) => {
|
|
2462
|
-
return model.is(key);
|
|
2463
|
-
});
|
|
2464
|
-
}
|
|
2465
|
-
return super.contains((model) => {
|
|
2466
|
-
return model.getKey() == key;
|
|
2467
|
-
});
|
|
2468
|
-
}
|
|
2469
|
-
diff(items) {
|
|
2470
|
-
const diff = new this.constructor();
|
|
2471
|
-
const dictionary = this.getDictionary(items);
|
|
2472
|
-
this.items.map((item) => {
|
|
2473
|
-
if (dictionary[item.getKey()] === void 0) {
|
|
2474
|
-
diff.add(item);
|
|
2475
|
-
}
|
|
2476
|
-
});
|
|
2477
|
-
return diff;
|
|
2478
|
-
}
|
|
2479
|
-
except(keys) {
|
|
2480
|
-
const dictionary = omit3(this.getDictionary(), keys);
|
|
2481
|
-
return new this.constructor(Object.values(dictionary));
|
|
2482
|
-
}
|
|
2483
|
-
intersect(items) {
|
|
2484
|
-
const intersect = new this.constructor();
|
|
2485
|
-
if (isEmpty(items)) {
|
|
2486
|
-
return intersect;
|
|
2487
|
-
}
|
|
2488
|
-
const dictionary = this.getDictionary(items);
|
|
2489
|
-
for (const item of this.items) {
|
|
2490
|
-
if (dictionary[item.getKey()] !== void 0) {
|
|
2491
|
-
intersect.add(item);
|
|
2492
|
-
}
|
|
2493
|
-
}
|
|
2494
|
-
return intersect;
|
|
2495
|
-
}
|
|
2496
|
-
unique(key, _strict = false) {
|
|
2497
|
-
if (key) {
|
|
2498
|
-
return super.unique(key);
|
|
2499
|
-
}
|
|
2500
|
-
return new this.constructor(Object.values(this.getDictionary()));
|
|
2501
|
-
}
|
|
2502
|
-
find(key, defaultValue = null) {
|
|
2503
|
-
if (key instanceof model_default) {
|
|
2504
|
-
key = key.getKey();
|
|
2505
|
-
}
|
|
2506
|
-
if (isArray3(key)) {
|
|
2507
|
-
if (this.isEmpty()) {
|
|
2508
|
-
return new this.constructor();
|
|
2509
|
-
}
|
|
2510
|
-
return this.whereIn(this.first().getKeyName(), key);
|
|
2511
|
-
}
|
|
2512
|
-
collect5(this.items).first((model) => {
|
|
2513
|
-
return model.getKey() == key;
|
|
2514
|
-
});
|
|
2515
|
-
return this.items.filter((model) => {
|
|
2516
|
-
return model.getKey() == key;
|
|
2517
|
-
})[0] || defaultValue;
|
|
2518
|
-
}
|
|
2519
|
-
async fresh(...args) {
|
|
2520
|
-
if (this.isEmpty()) {
|
|
2521
|
-
return new this.constructor();
|
|
2522
|
-
}
|
|
2523
|
-
const model = this.first();
|
|
2524
|
-
const freshModels = (await model.newQuery().with(...args).whereIn(model.getKeyName(), this.modelKeys()).get()).getDictionary();
|
|
2525
|
-
return this.filter((model2) => {
|
|
2526
|
-
return model2.exists && freshModels[model2.getKey()] !== void 0;
|
|
2527
|
-
}).map((model2) => {
|
|
2528
|
-
return freshModels[model2.getKey()];
|
|
2529
|
-
});
|
|
2530
|
-
}
|
|
2531
|
-
makeVisible(attributes) {
|
|
2532
|
-
return this.each((item) => {
|
|
2533
|
-
item.makeVisible(attributes);
|
|
2534
|
-
});
|
|
2535
|
-
}
|
|
2536
|
-
makeHidden(attributes) {
|
|
2537
|
-
return this.each((item) => {
|
|
2538
|
-
item.makeHidden(attributes);
|
|
2539
|
-
});
|
|
2540
|
-
}
|
|
2541
|
-
append(attributes) {
|
|
2542
|
-
return this.each((item) => {
|
|
2543
|
-
item.append(attributes);
|
|
2544
|
-
});
|
|
2545
|
-
}
|
|
2546
|
-
only(keys) {
|
|
2547
|
-
if (keys === null) {
|
|
2548
|
-
return new _Collection(this.items);
|
|
2549
|
-
}
|
|
2550
|
-
const dictionary = pick(this.getDictionary(), keys);
|
|
2551
|
-
return new this.constructor(Object.values(dictionary));
|
|
2552
|
-
}
|
|
2553
|
-
getDictionary(items) {
|
|
2554
|
-
items = !items ? this.items : items;
|
|
2555
|
-
const dictionary = {};
|
|
2556
|
-
items.map((value) => {
|
|
2557
|
-
dictionary[value.getKey()] = value;
|
|
2558
|
-
});
|
|
2559
|
-
return dictionary;
|
|
2560
|
-
}
|
|
2561
|
-
toQuery() {
|
|
2562
|
-
const model = this.first();
|
|
2563
|
-
if (!model) {
|
|
2564
|
-
throw new Error("Unable to create query for empty collection.");
|
|
2565
|
-
}
|
|
2566
|
-
const modelName = model.constructor.name;
|
|
2567
|
-
if (this.filter((model2) => {
|
|
2568
|
-
return !(model2 instanceof modelName);
|
|
2569
|
-
}).isNotEmpty()) {
|
|
2570
|
-
throw new Error("Unable to create query for collection with mixed types.");
|
|
2571
|
-
}
|
|
2572
|
-
return model.newModelQuery().whereKey(this.modelKeys());
|
|
2573
|
-
}
|
|
2574
|
-
toData() {
|
|
2575
|
-
return this.all().map((item) => typeof item.toData == "function" ? item.toData() : item);
|
|
2576
|
-
}
|
|
2577
|
-
toJSON() {
|
|
2578
|
-
return this.toData();
|
|
2579
|
-
}
|
|
2580
|
-
toJson(...args) {
|
|
2581
|
-
return JSON.stringify(this.toData(), ...args);
|
|
2582
|
-
}
|
|
2583
|
-
[Symbol.iterator] = () => {
|
|
2584
|
-
const items = this.items;
|
|
2585
|
-
const length = this.items.length;
|
|
2586
|
-
let n = 0;
|
|
2587
|
-
return {
|
|
2588
|
-
next() {
|
|
2589
|
-
return n < length ? {
|
|
2590
|
-
value: items[n++],
|
|
2591
|
-
done: false
|
|
2592
|
-
} : {
|
|
2593
|
-
done: true
|
|
2594
|
-
};
|
|
2595
|
-
}
|
|
2596
|
-
};
|
|
2597
|
-
};
|
|
2598
|
-
};
|
|
2599
|
-
var collection_default = Collection;
|
|
2600
|
-
|
|
2601
|
-
// src/relations/concerns/interacts-with-pivot-table.ts
|
|
2602
|
-
import { assign, diff as difference3, isArray as isArray4 } from "radashi";
|
|
2603
|
-
import { collect as collect6 } from "collect.js";
|
|
2604
|
-
var InteractsWithPivotTable = (Relation2) => {
|
|
2605
|
-
return class extends Relation2 {
|
|
2606
|
-
newExistingPivot(attributes = []) {
|
|
2607
|
-
return this.newPivot(attributes, true);
|
|
2608
|
-
}
|
|
2609
|
-
newPivot(attributes = [], exists = false) {
|
|
2610
|
-
const pivot = this.related.newPivot(this.parent, attributes, this.getTable(), exists, this.using);
|
|
2611
|
-
return pivot.setPivotKeys(this.foreignPivotKey, this.relatedPivotKey);
|
|
2612
|
-
}
|
|
2613
|
-
async attach(id, attributes = {}, _touch = true) {
|
|
2614
|
-
if (this.using) {
|
|
2615
|
-
await this.attachUsingCustomClass(id, attributes);
|
|
2616
|
-
} else {
|
|
2617
|
-
await this.newPivotStatement().insert(this.formatAttachRecords(this.parseIds(id), attributes));
|
|
2618
|
-
}
|
|
2619
|
-
}
|
|
2620
|
-
async detach(ids, _touch = true) {
|
|
2621
|
-
let results;
|
|
2622
|
-
if (this.using && ids !== null && this.pivotWheres.length == 0 && this.pivotWhereIns.length == 0 && this.pivotWhereNulls.length == 0) {
|
|
2623
|
-
results = await this.detachUsingCustomClass(ids);
|
|
2624
|
-
} else {
|
|
2625
|
-
const query = this.newPivotQuery();
|
|
2626
|
-
if (ids !== null) {
|
|
2627
|
-
ids = this.parseIds(ids);
|
|
2628
|
-
if (ids.length == 0) {
|
|
2629
|
-
return 0;
|
|
2630
|
-
}
|
|
2631
|
-
query.whereIn(this.getQualifiedRelatedPivotKeyName(), ids);
|
|
2632
|
-
}
|
|
2633
|
-
results = await query.delete();
|
|
2634
|
-
}
|
|
2635
|
-
return results;
|
|
2636
|
-
}
|
|
2637
|
-
async sync(ids, detaching = true) {
|
|
2638
|
-
let changes = {
|
|
2639
|
-
attached: [],
|
|
2640
|
-
detached: [],
|
|
2641
|
-
updated: []
|
|
2642
|
-
};
|
|
2643
|
-
let records;
|
|
2644
|
-
const results = await this.getCurrentlyAttachedPivots();
|
|
2645
|
-
const current = results.length === 0 ? [] : results.map((result) => result.toData()).pluck(this.relatedPivotKey).all().map((i) => String(i));
|
|
2646
|
-
const detach = difference3(current, Object.keys(records = this.formatRecordsList(this.parseIds(ids))));
|
|
2647
|
-
if (detaching && detach.length > 0) {
|
|
2648
|
-
await this.detach(detach);
|
|
2649
|
-
changes.detached = this.castKeys(detach);
|
|
2650
|
-
}
|
|
2651
|
-
changes = assign(changes, await this.attachNew(records, current, false));
|
|
2652
|
-
return changes;
|
|
2653
|
-
}
|
|
2654
|
-
syncWithoutDetaching(ids) {
|
|
2655
|
-
return this.sync(ids, false);
|
|
2656
|
-
}
|
|
2657
|
-
syncWithPivotValues(ids, values, detaching = true) {
|
|
2658
|
-
return this.sync(collect6(this.parseIds(ids)).mapWithKeys((id) => {
|
|
2659
|
-
return [id, values];
|
|
2660
|
-
}), detaching);
|
|
2661
|
-
}
|
|
2662
|
-
withPivot(columns) {
|
|
2663
|
-
this.pivotColumns = this.pivotColumns.concat(isArray4(columns) ? columns : Array.prototype.slice.call(columns));
|
|
2664
|
-
return this;
|
|
2665
|
-
}
|
|
2666
|
-
async attachNew(records, current, touch = true) {
|
|
2667
|
-
const changes = {
|
|
2668
|
-
attached: [],
|
|
2669
|
-
updated: []
|
|
2670
|
-
};
|
|
2671
|
-
for (const id in records) {
|
|
2672
|
-
const attributes = records[id];
|
|
2673
|
-
if (!current.includes(id)) {
|
|
2674
|
-
await this.attach(id, attributes, touch);
|
|
2675
|
-
changes.attached.push(this.castKey(id));
|
|
2676
|
-
} else if (Object.keys(attributes).length > 0 && await this.updateExistingPivot(id, attributes, touch)) {
|
|
2677
|
-
changes.updated.push(this.castKey(id));
|
|
2678
|
-
}
|
|
2679
|
-
}
|
|
2680
|
-
return changes;
|
|
2681
|
-
}
|
|
2682
|
-
async updateExistingPivot(id, attributes, touch = true) {
|
|
2683
|
-
if (this.using && this.pivotWheres.length > 0 && this.pivotWhereInspivotWheres.length > 0 && this.pivotWhereNullspivotWheres.length > 0) {
|
|
2684
|
-
return await this.updateExistingPivotUsingCustomClass(id, attributes, touch);
|
|
2685
|
-
}
|
|
2686
|
-
if (this.hasPivotColumn(this.updatedAt())) {
|
|
2687
|
-
attributes = this.addTimestampsToAttachment(attributes, true);
|
|
2688
|
-
}
|
|
2689
|
-
const updated = this.newPivotStatementForId(this.parseId(id)).update(this.castAttributes(attributes));
|
|
2690
|
-
return updated;
|
|
2691
|
-
}
|
|
2692
|
-
addTimestampsToAttachment(record, exists = false) {
|
|
2693
|
-
let fresh = this.parent.freshTimestamp();
|
|
2694
|
-
if (this.using) {
|
|
2695
|
-
const pivotModel = new this.using();
|
|
2696
|
-
fresh = pivotModel.fromDateTime(fresh);
|
|
2697
|
-
}
|
|
2698
|
-
if (!exists && this.hasPivotColumn(this.createdAt())) {
|
|
2699
|
-
record[this.createdAt()] = fresh;
|
|
2700
|
-
}
|
|
2701
|
-
if (this.hasPivotColumn(this.updatedAt())) {
|
|
2702
|
-
record[this.updatedAt()] = fresh;
|
|
2703
|
-
}
|
|
2704
|
-
return record;
|
|
2705
|
-
}
|
|
2706
|
-
async updateExistingPivotUsingCustomClass(id, attributes, _touch) {
|
|
2707
|
-
const pivot = await this.getCurrentlyAttachedPivots().where(this.foreignPivotKey, this.parent[this.parentKey]).where(this.relatedPivotKey, this.parseId(id)).first();
|
|
2708
|
-
const updated = pivot ? pivot.fill(attributes).isDirty() : false;
|
|
2709
|
-
if (updated) {
|
|
2710
|
-
await pivot.save();
|
|
2711
|
-
}
|
|
2712
|
-
return parseInt(updated);
|
|
2713
|
-
}
|
|
2714
|
-
formatRecordsList(records) {
|
|
2715
|
-
return collect6(records).mapWithKeys((attributes, id) => {
|
|
2716
|
-
if (!isArray4(attributes)) {
|
|
2717
|
-
[id, attributes] = [attributes, {}];
|
|
2718
|
-
}
|
|
2719
|
-
return [id, attributes];
|
|
2720
|
-
}).all();
|
|
2721
|
-
}
|
|
2722
|
-
async getCurrentlyAttachedPivots() {
|
|
2723
|
-
const query = this.newPivotQuery();
|
|
2724
|
-
const results = await query.get();
|
|
2725
|
-
return results.map((record) => {
|
|
2726
|
-
const modelClass = this.using || Pivot;
|
|
2727
|
-
const pivot = modelClass.fromRawAttributes(this.parent, record, this.getTable(), true);
|
|
2728
|
-
return pivot.setPivotKeys(this.foreignPivotKey, this.relatedPivotKey);
|
|
2729
|
-
});
|
|
2730
|
-
}
|
|
2731
|
-
castKeys(keys) {
|
|
2732
|
-
return keys.map((v) => {
|
|
2733
|
-
return this.castKey(v);
|
|
2734
|
-
});
|
|
2735
|
-
}
|
|
2736
|
-
castKey(key) {
|
|
2737
|
-
return this.getTypeSwapValue(this.related.getKeyType(), key);
|
|
2738
|
-
}
|
|
2739
|
-
getTypeSwapValue(type, value) {
|
|
2740
|
-
switch (type.toLowerCase()) {
|
|
2741
|
-
case "int":
|
|
2742
|
-
case "integer":
|
|
2743
|
-
return parseInt(value);
|
|
2744
|
-
case "real":
|
|
2745
|
-
case "float":
|
|
2746
|
-
case "double":
|
|
2747
|
-
return parseFloat(value);
|
|
2748
|
-
case "string":
|
|
2749
|
-
return String(value);
|
|
2750
|
-
default:
|
|
2751
|
-
return value;
|
|
2752
|
-
}
|
|
2753
|
-
}
|
|
2754
|
-
newPivotQuery() {
|
|
2755
|
-
const query = this.newPivotStatement();
|
|
2756
|
-
this.pivotWheres.map((args) => {
|
|
2757
|
-
query.where(...args);
|
|
2758
|
-
});
|
|
2759
|
-
this.pivotWhereIns.map((args) => {
|
|
2760
|
-
query.whereIn(...args);
|
|
2761
|
-
});
|
|
2762
|
-
this.pivotWhereNulls.map((args) => {
|
|
2763
|
-
query.whereNull(...args);
|
|
2764
|
-
});
|
|
2765
|
-
return query.where(this.getQualifiedForeignPivotKeyName(), this.parent[this.parentKey]);
|
|
2766
|
-
}
|
|
2767
|
-
async detachUsingCustomClass(ids) {
|
|
2768
|
-
let results = 0;
|
|
2769
|
-
for (const id in this.parseIds(ids)) {
|
|
2770
|
-
results += await this.newPivot({
|
|
2771
|
-
[this.foreignPivotKey]: this.parent[this.parentKey],
|
|
2772
|
-
[this.relatedPivotKey]: id
|
|
2773
|
-
}, true).delete();
|
|
2774
|
-
}
|
|
2775
|
-
;
|
|
2776
|
-
return results;
|
|
2777
|
-
}
|
|
2778
|
-
newPivotStatement() {
|
|
2779
|
-
const builder = this.parent.newQuery();
|
|
2780
|
-
builder.setTable(this.table);
|
|
2781
|
-
return builder;
|
|
2782
|
-
}
|
|
2783
|
-
async attachUsingCustomClass(id, attributes) {
|
|
2784
|
-
const records = this.formatAttachRecords(this.parseIds(id), attributes);
|
|
2785
|
-
await Promise.all(records.map(async (record) => {
|
|
2786
|
-
await this.newPivot(record, false).save();
|
|
2787
|
-
}));
|
|
2788
|
-
}
|
|
2789
|
-
formatAttachRecords(ids, attributes) {
|
|
2790
|
-
const records = [];
|
|
2791
|
-
const hasTimestamps = this.hasPivotColumn(this.createdAt()) || this.hasPivotColumn(this.updatedAt());
|
|
2792
|
-
for (const key in ids) {
|
|
2793
|
-
const value = ids[key];
|
|
2794
|
-
records.push(this.formatAttachRecord(key, value, attributes, hasTimestamps));
|
|
2795
|
-
}
|
|
2796
|
-
return records;
|
|
2797
|
-
}
|
|
2798
|
-
formatAttachRecord(key, value, attributes, hasTimestamps) {
|
|
2799
|
-
const [id, newAttributes] = this.extractAttachIdAndAttributes(key, value, attributes);
|
|
2800
|
-
return assign(this.baseAttachRecord(id, hasTimestamps), newAttributes);
|
|
2801
|
-
}
|
|
2802
|
-
baseAttachRecord(id, timed) {
|
|
2803
|
-
let record = {};
|
|
2804
|
-
record[this.relatedPivotKey] = id;
|
|
2805
|
-
record[this.foreignPivotKey] = this.parent[this.parentKey];
|
|
2806
|
-
if (timed) {
|
|
2807
|
-
record = this.addTimestampsToAttachment(record);
|
|
2808
|
-
}
|
|
2809
|
-
this.pivotValues.map((value) => {
|
|
2810
|
-
record[value.column] = value.value;
|
|
2811
|
-
});
|
|
2812
|
-
return record;
|
|
2813
|
-
}
|
|
2814
|
-
extractAttachIdAndAttributes(key, value, newAttributes) {
|
|
2815
|
-
return isArray4(value) ? [key, { ...value, ...newAttributes }] : [value, newAttributes];
|
|
2816
|
-
}
|
|
2817
|
-
hasPivotColumn(column) {
|
|
2818
|
-
return this.pivotColumns.includes(column);
|
|
2819
|
-
}
|
|
2820
|
-
parseIds(value) {
|
|
2821
|
-
if (value instanceof Model) {
|
|
2822
|
-
return [value[this.relatedKey]];
|
|
2823
|
-
}
|
|
2824
|
-
if (value instanceof collection_default) {
|
|
2825
|
-
return value.pluck(this.relatedKey).all();
|
|
2826
|
-
}
|
|
2827
|
-
return isArray4(value) ? value : [value];
|
|
2828
|
-
}
|
|
2829
|
-
};
|
|
2830
|
-
};
|
|
2831
|
-
var interacts_with_pivot_table_default = InteractsWithPivotTable;
|
|
2832
|
-
|
|
2833
|
-
// src/relations/belongs-to-many.ts
|
|
2834
|
-
import { collect as collect7 } from "collect.js";
|
|
2835
|
-
var BelongsToMany = class extends compose(relation_default, interacts_with_pivot_table_default) {
|
|
2836
|
-
table;
|
|
2837
|
-
foreignPivotKey;
|
|
2838
|
-
relatedPivotKey;
|
|
2839
|
-
parentKey;
|
|
2840
|
-
relatedKey;
|
|
2841
|
-
pivotColumns = [];
|
|
2842
|
-
pivotValues = [];
|
|
2843
|
-
pivotWheres = [];
|
|
2844
|
-
pivotWhereIns = [];
|
|
2845
|
-
pivotWhereNulls = [];
|
|
2846
|
-
accessor = "pivot";
|
|
2847
|
-
using;
|
|
2848
|
-
pivotCreatedAt;
|
|
2849
|
-
pivotUpdatedAt;
|
|
2850
|
-
constructor(query, parent, table, foreignPivotKey, relatedPivotKey, parentKey, relatedKey) {
|
|
2851
|
-
super(query, parent);
|
|
2852
|
-
this.table = table;
|
|
2853
|
-
this.foreignPivotKey = foreignPivotKey;
|
|
2854
|
-
this.relatedPivotKey = relatedPivotKey;
|
|
2855
|
-
this.parentKey = parentKey;
|
|
2856
|
-
this.relatedKey = relatedKey;
|
|
2857
|
-
this.addConstraints();
|
|
2858
|
-
return this.asProxy();
|
|
2859
|
-
}
|
|
2860
|
-
initRelation(models, relation) {
|
|
2861
|
-
models.map((model) => {
|
|
2862
|
-
model.setRelation(relation, new collection_default([]));
|
|
2863
|
-
});
|
|
2864
|
-
return models;
|
|
2865
|
-
}
|
|
2866
|
-
addConstraints() {
|
|
2867
|
-
this.performJoin();
|
|
2868
|
-
if (this.constructor.constraints) {
|
|
2869
|
-
this.addWhereConstraints();
|
|
2870
|
-
}
|
|
2871
|
-
}
|
|
2872
|
-
performJoin(query = null) {
|
|
2873
|
-
query = query || this.query;
|
|
2874
|
-
query.join(
|
|
2875
|
-
this.getTable(),
|
|
2876
|
-
this.getQualifiedRelatedKeyName(),
|
|
2877
|
-
"=",
|
|
2878
|
-
this.qualifyPivotColumn(this.relatedPivotKey)
|
|
2879
|
-
);
|
|
2880
|
-
return this;
|
|
2881
|
-
}
|
|
2882
|
-
getTable() {
|
|
2883
|
-
return this.table;
|
|
2884
|
-
}
|
|
2885
|
-
getQualifiedRelatedKeyName() {
|
|
2886
|
-
return this.related.qualifyColumn(this.relatedKey);
|
|
2887
|
-
}
|
|
2888
|
-
async getResults() {
|
|
2889
|
-
return this.parent[this.parentKey] !== null ? await this.get() : new collection_default([]);
|
|
2890
|
-
}
|
|
2891
|
-
addWhereConstraints() {
|
|
2892
|
-
this.query.where(
|
|
2893
|
-
this.getQualifiedForeignPivotKeyName(),
|
|
2894
|
-
"=",
|
|
2895
|
-
this.parent[this.parentKey]
|
|
2896
|
-
);
|
|
2897
|
-
return this;
|
|
2898
|
-
}
|
|
2899
|
-
async get(columns) {
|
|
2900
|
-
const builder = this.query.applyScopes();
|
|
2901
|
-
columns = builder.query?._statements?.find((item) => item.grouping == "columns") ? [] : columns;
|
|
2902
|
-
let models = await builder.select(this.shouldSelect(columns)).getModels();
|
|
2903
|
-
this.hydratePivotRelation(models);
|
|
2904
|
-
if (models.length > 0) {
|
|
2905
|
-
models = await builder.eagerLoadRelations(models);
|
|
2906
|
-
}
|
|
2907
|
-
return new collection_default(models);
|
|
2908
|
-
}
|
|
2909
|
-
async first(columns = ["*"]) {
|
|
2910
|
-
const results = await this.take(1).get(columns);
|
|
2911
|
-
return results.count() > 0 ? results.first() : null;
|
|
2912
|
-
}
|
|
2913
|
-
async firstOrFail(columns = ["*"]) {
|
|
2914
|
-
const model = await this.first(columns);
|
|
2915
|
-
if (model !== null) {
|
|
2916
|
-
return model;
|
|
2917
|
-
}
|
|
2918
|
-
throw new ModelNotFoundError().setModel(this.related.constructor);
|
|
2919
|
-
}
|
|
2920
|
-
async paginate(page = 1, perPage = 15, columns = ["*"]) {
|
|
2921
|
-
this.query.select(this.shouldSelect(columns));
|
|
2922
|
-
return tap(await this.query.paginate(page, perPage), (paginator) => {
|
|
2923
|
-
this.hydratePivotRelation(paginator.items());
|
|
2924
|
-
});
|
|
2925
|
-
}
|
|
2926
|
-
async chunk(count, callback) {
|
|
2927
|
-
return await this.prepareQueryBuilder().chunk(count, async (results, page) => {
|
|
2928
|
-
this.hydratePivotRelation(results.all());
|
|
2929
|
-
return await callback(results, page);
|
|
2930
|
-
});
|
|
2931
|
-
}
|
|
2932
|
-
setUsing(model) {
|
|
2933
|
-
this.using = model;
|
|
2934
|
-
return this;
|
|
2935
|
-
}
|
|
2936
|
-
as(accessor) {
|
|
2937
|
-
this.accessor = accessor;
|
|
2938
|
-
return this;
|
|
2939
|
-
}
|
|
2940
|
-
prepareQueryBuilder() {
|
|
2941
|
-
return this.query.select(this.shouldSelect());
|
|
2942
|
-
}
|
|
2943
|
-
hydratePivotRelation(models) {
|
|
2944
|
-
models.map((model) => {
|
|
2945
|
-
model.setRelation(
|
|
2946
|
-
this.accessor,
|
|
2947
|
-
this.newExistingPivot(this.migratePivotAttributes(model))
|
|
2948
|
-
);
|
|
2949
|
-
});
|
|
2950
|
-
}
|
|
2951
|
-
migratePivotAttributes(model) {
|
|
2952
|
-
const values = {};
|
|
2953
|
-
for (const key in model.attributes) {
|
|
2954
|
-
const value = model.attributes[key];
|
|
2955
|
-
if (key.startsWith("pivot_")) {
|
|
2956
|
-
values[key.substring(6)] = value;
|
|
2957
|
-
model.attributes = omit4(model.attributes, [key]);
|
|
2958
|
-
}
|
|
2959
|
-
}
|
|
2960
|
-
return values;
|
|
2961
|
-
}
|
|
2962
|
-
withTimestamps(createdAt = null, updatedAt = null) {
|
|
2963
|
-
this.pivotCreatedAt = createdAt;
|
|
2964
|
-
this.pivotUpdatedAt = updatedAt;
|
|
2965
|
-
return this.withPivot(this.createdAt(), this.updatedAt());
|
|
2966
|
-
}
|
|
2967
|
-
shouldSelect(columns = ["*"]) {
|
|
2968
|
-
if (isEqual(columns, ["*"])) {
|
|
2969
|
-
columns = [this.related.getTable() + ".*"];
|
|
2970
|
-
}
|
|
2971
|
-
return columns.concat(this.aliasedPivotColumns());
|
|
2972
|
-
}
|
|
2973
|
-
aliasedPivotColumns() {
|
|
2974
|
-
const defaults = [this.foreignPivotKey, this.relatedPivotKey];
|
|
2975
|
-
return collect7(defaults.concat(this.pivotColumns)).map((column) => {
|
|
2976
|
-
return this.qualifyPivotColumn(column) + " as pivot_" + column;
|
|
2977
|
-
}).unique().all();
|
|
2978
|
-
}
|
|
2979
|
-
qualifyPivotColumn(column) {
|
|
2980
|
-
return column.includes(".") ? column : this.getTable() + "." + column;
|
|
2981
|
-
}
|
|
2982
|
-
match(models, results, relation) {
|
|
2983
|
-
const dictionary = this.buildDictionary(results);
|
|
2984
|
-
models.map((model) => {
|
|
2985
|
-
const key = model.getKey();
|
|
2986
|
-
if (dictionary[key] !== void 0) {
|
|
2987
|
-
model.setRelation(relation, dictionary[key]);
|
|
2988
|
-
}
|
|
2989
|
-
});
|
|
2990
|
-
return models;
|
|
2991
|
-
}
|
|
2992
|
-
buildDictionary(results) {
|
|
2993
|
-
const dictionary = {};
|
|
2994
|
-
results.map((result) => {
|
|
2995
|
-
const value = result[this.accessor][this.foreignPivotKey];
|
|
2996
|
-
if (dictionary[value] === void 0) {
|
|
2997
|
-
dictionary[value] = new collection_default([]);
|
|
2998
|
-
}
|
|
2999
|
-
dictionary[value].push(result);
|
|
3000
|
-
});
|
|
3001
|
-
return dictionary;
|
|
3002
|
-
}
|
|
3003
|
-
addEagerConstraints(models) {
|
|
3004
|
-
this.query.whereIn(
|
|
3005
|
-
this.getQualifiedForeignPivotKeyName(),
|
|
3006
|
-
this.getKeys(models, this.parentKey)
|
|
3007
|
-
);
|
|
3008
|
-
}
|
|
3009
|
-
getQualifiedForeignPivotKeyName() {
|
|
3010
|
-
return this.qualifyPivotColumn(this.foreignPivotKey);
|
|
3011
|
-
}
|
|
3012
|
-
getQualifiedRelatedPivotKeyName() {
|
|
3013
|
-
return this.qualifyPivotColumn(this.relatedPivotKey);
|
|
3014
|
-
}
|
|
3015
|
-
wherePivot(column, operator = null, value = null, boolean = "and") {
|
|
3016
|
-
this.pivotWheres.push(Array.prototype.slice.call(arguments));
|
|
3017
|
-
return this.where(this.qualifyPivotColumn(column), operator, value, boolean);
|
|
3018
|
-
}
|
|
3019
|
-
wherePivotBetween(column, values, boolean = "and", not = false) {
|
|
3020
|
-
return this.whereBetween(this.qualifyPivotColumn(column), values, boolean, not);
|
|
3021
|
-
}
|
|
3022
|
-
orWherePivotBetween(column, values) {
|
|
3023
|
-
return this.wherePivotBetween(column, values, "or");
|
|
3024
|
-
}
|
|
3025
|
-
wherePivotNotBetween(column, values, boolean = "and") {
|
|
3026
|
-
return this.wherePivotBetween(column, values, boolean, true);
|
|
3027
|
-
}
|
|
3028
|
-
orWherePivotNotBetween(column, values) {
|
|
3029
|
-
return this.wherePivotBetween(column, values, "or", true);
|
|
3030
|
-
}
|
|
3031
|
-
wherePivotIn(column, values, boolean = "and", not = false) {
|
|
3032
|
-
return this.whereIn(this.qualifyPivotColumn(column), values, boolean, not);
|
|
3033
|
-
}
|
|
3034
|
-
orWherePivot(column, operator = null, value = null) {
|
|
3035
|
-
return this.wherePivot(column, operator, value, "or");
|
|
3036
|
-
}
|
|
3037
|
-
orWherePivotIn(column, values) {
|
|
3038
|
-
return this.wherePivotIn(column, values, "or");
|
|
3039
|
-
}
|
|
3040
|
-
wherePivotNotIn(column, values, boolean = "and") {
|
|
3041
|
-
return this.wherePivotIn(column, values, boolean, true);
|
|
3042
|
-
}
|
|
3043
|
-
orWherePivotNotIn(column, values) {
|
|
3044
|
-
return this.wherePivotNotIn(column, values, "or");
|
|
3045
|
-
}
|
|
3046
|
-
wherePivotNull(column, boolean = "and", not = false) {
|
|
3047
|
-
return this.whereNull(this.qualifyPivotColumn(column), boolean, not);
|
|
3048
|
-
}
|
|
3049
|
-
wherePivotNotNull(column, boolean = "and") {
|
|
3050
|
-
return this.wherePivotNull(column, boolean, true);
|
|
3051
|
-
}
|
|
3052
|
-
orWherePivotNull(column, not = false) {
|
|
3053
|
-
return this.wherePivotNull(column, "or", not);
|
|
3054
|
-
}
|
|
3055
|
-
orWherePivotNotNull(column) {
|
|
3056
|
-
return this.orWherePivotNull(column, true);
|
|
3057
|
-
}
|
|
3058
|
-
orderByPivot(column, direction = "asc") {
|
|
3059
|
-
return this.orderBy(this.qualifyPivotColumn(column), direction);
|
|
3060
|
-
}
|
|
3061
|
-
createdAt() {
|
|
3062
|
-
return this.pivotCreatedAt || this.parent.getCreatedAtColumn();
|
|
3063
|
-
}
|
|
3064
|
-
updatedAt() {
|
|
3065
|
-
return this.pivotUpdatedAt || this.parent.getUpdatedAtColumn();
|
|
3066
|
-
}
|
|
3067
|
-
getExistenceCompareKey() {
|
|
3068
|
-
return this.getQualifiedForeignPivotKeyName();
|
|
3069
|
-
}
|
|
3070
|
-
getRelationExistenceQuery(query, parentQuery, columns = ["*"]) {
|
|
3071
|
-
if (parentQuery.getQuery()._single.table == query.getQuery()._single.table) {
|
|
3072
|
-
return this.getRelationExistenceQueryForSelfJoin(query, parentQuery, columns);
|
|
3073
|
-
}
|
|
3074
|
-
this.performJoin(query);
|
|
3075
|
-
return super.getRelationExistenceQuery(query, parentQuery, columns);
|
|
3076
|
-
}
|
|
3077
|
-
getRelationExistenceQueryForSelfJoin(query, parentQuery, columns = ["*"]) {
|
|
3078
|
-
const hash = this.getRelationCountHash();
|
|
3079
|
-
query.select(columns).from(this.related.getTable() + " as " + hash);
|
|
3080
|
-
this.related.setTable(hash);
|
|
3081
|
-
this.performJoin(query);
|
|
3082
|
-
return super.getRelationExistenceQuery(query, parentQuery, columns);
|
|
3083
|
-
}
|
|
3084
|
-
};
|
|
3085
|
-
var belongs_to_many_default = BelongsToMany;
|
|
3086
|
-
|
|
3087
|
-
// src/builder.ts
|
|
3088
|
-
var Inference2 = class {
|
|
3089
|
-
};
|
|
3090
|
-
var Builder = class _Builder extends Inference2 {
|
|
3091
|
-
query;
|
|
3092
|
-
connection;
|
|
3093
|
-
model;
|
|
3094
|
-
actions;
|
|
3095
|
-
localMacros = {};
|
|
3096
|
-
eagerLoad = {};
|
|
3097
|
-
globalScopes = {};
|
|
3098
|
-
onDeleteCallback;
|
|
3099
|
-
constructor(query) {
|
|
3100
|
-
super();
|
|
3101
|
-
this.query = query;
|
|
3102
|
-
return this.asProxy();
|
|
3103
|
-
}
|
|
3104
|
-
asProxy() {
|
|
3105
|
-
const handler = {
|
|
3106
|
-
get(target, prop) {
|
|
3107
|
-
if (typeof target[prop] !== "undefined") {
|
|
3108
|
-
return target[prop];
|
|
3109
|
-
}
|
|
3110
|
-
if ([
|
|
3111
|
-
"select",
|
|
3112
|
-
"from",
|
|
3113
|
-
"where",
|
|
3114
|
-
"orWhere",
|
|
3115
|
-
"whereColumn",
|
|
3116
|
-
"whereRaw",
|
|
3117
|
-
"whereNot",
|
|
3118
|
-
"orWhereNot",
|
|
3119
|
-
"whereIn",
|
|
3120
|
-
"orWhereIn",
|
|
3121
|
-
"whereNotIn",
|
|
3122
|
-
"orWhereNotIn",
|
|
3123
|
-
"whereNull",
|
|
3124
|
-
"orWhereNull",
|
|
3125
|
-
"whereNotNull",
|
|
3126
|
-
"orWhereNotNull",
|
|
3127
|
-
"whereExists",
|
|
3128
|
-
"orWhereExists",
|
|
3129
|
-
"whereNotExists",
|
|
3130
|
-
"orWhereNotExists",
|
|
3131
|
-
"whereBetween",
|
|
3132
|
-
"orWhereBetween",
|
|
3133
|
-
"whereNotBetween",
|
|
3134
|
-
"orWhereNotBetween",
|
|
3135
|
-
"whereLike",
|
|
3136
|
-
"orWhereLike",
|
|
3137
|
-
"whereILike",
|
|
3138
|
-
"orWhereILike",
|
|
3139
|
-
"whereJsonObject",
|
|
3140
|
-
"whereJsonPath",
|
|
3141
|
-
"whereJsonSupersetOf",
|
|
3142
|
-
"whereJsonSubsetOf",
|
|
3143
|
-
"join",
|
|
3144
|
-
"joinRaw",
|
|
3145
|
-
"leftJoin",
|
|
3146
|
-
"leftOuterJoin",
|
|
3147
|
-
"rightJoin",
|
|
3148
|
-
"rightOuterJoin",
|
|
3149
|
-
"crossJoin",
|
|
3150
|
-
"transacting",
|
|
3151
|
-
"groupBy",
|
|
3152
|
-
"groupByRaw",
|
|
3153
|
-
"returning",
|
|
3154
|
-
"having",
|
|
3155
|
-
"havingRaw",
|
|
3156
|
-
"havingBetween",
|
|
3157
|
-
"limit",
|
|
3158
|
-
"offset",
|
|
3159
|
-
"orderBy",
|
|
3160
|
-
"orderByRaw",
|
|
3161
|
-
// 'inRandomOrder',
|
|
3162
|
-
"union",
|
|
3163
|
-
"insert",
|
|
3164
|
-
"forUpdate",
|
|
3165
|
-
"forShare",
|
|
3166
|
-
"distinct",
|
|
3167
|
-
"clearOrder",
|
|
3168
|
-
"clear",
|
|
3169
|
-
"clearSelect",
|
|
3170
|
-
"clearWhere",
|
|
3171
|
-
"clearHaving",
|
|
3172
|
-
"clearGroup"
|
|
3173
|
-
].includes(prop)) {
|
|
3174
|
-
return (...args) => {
|
|
3175
|
-
target.query[prop](...args);
|
|
3176
|
-
return target.asProxy();
|
|
3177
|
-
};
|
|
3178
|
-
}
|
|
3179
|
-
if ([
|
|
3180
|
-
"avg",
|
|
3181
|
-
"max",
|
|
3182
|
-
"min",
|
|
3183
|
-
"sum",
|
|
3184
|
-
"count"
|
|
3185
|
-
].includes(prop)) {
|
|
3186
|
-
return (column) => {
|
|
3187
|
-
const instance = target.asProxy();
|
|
3188
|
-
instance.applyScopes();
|
|
3189
|
-
column = !column && prop === "count" ? "*" : column;
|
|
3190
|
-
return instance.query[prop](column);
|
|
3191
|
-
};
|
|
3192
|
-
}
|
|
3193
|
-
if (typeof prop === "string") {
|
|
3194
|
-
if (target.hasMacro(prop)) {
|
|
3195
|
-
const instance = target.asProxy();
|
|
3196
|
-
return (...args) => {
|
|
3197
|
-
return instance.localMacros[prop](instance, ...args);
|
|
3198
|
-
};
|
|
3199
|
-
}
|
|
3200
|
-
if (target.hasNamedScope(prop)) {
|
|
3201
|
-
const instance = target.asProxy();
|
|
3202
|
-
return (...args) => {
|
|
3203
|
-
instance.callNamedScope(prop, args);
|
|
3204
|
-
return instance;
|
|
3205
|
-
};
|
|
3206
|
-
}
|
|
3207
|
-
if (prop.startsWith("where")) {
|
|
3208
|
-
const column = snake2(prop.substring(5));
|
|
3209
|
-
return (...args) => {
|
|
3210
|
-
target.query.where(column, ...args);
|
|
3211
|
-
return target.asProxy();
|
|
3212
|
-
};
|
|
3213
|
-
}
|
|
3214
|
-
}
|
|
3215
|
-
}
|
|
3216
|
-
};
|
|
3217
|
-
return new Proxy(this, handler);
|
|
3218
|
-
}
|
|
3219
|
-
orWhere(...args) {
|
|
3220
|
-
if (typeof args[0] === "function") {
|
|
3221
|
-
const callback = args[0];
|
|
3222
|
-
this.query.orWhere((query) => {
|
|
3223
|
-
this.query = query;
|
|
3224
|
-
callback(this);
|
|
3225
|
-
});
|
|
3226
|
-
return this;
|
|
3227
|
-
}
|
|
3228
|
-
this.query.orWhere(...args);
|
|
3229
|
-
return this;
|
|
3230
|
-
}
|
|
3231
|
-
async chunk(count, callback) {
|
|
3232
|
-
let page = 1;
|
|
3233
|
-
let countResults;
|
|
3234
|
-
do {
|
|
3235
|
-
this.enforceOrderBy();
|
|
3236
|
-
const builder = this.clone();
|
|
3237
|
-
const results = await builder.forPage(page, count).get();
|
|
3238
|
-
countResults = results.count();
|
|
3239
|
-
if (countResults == 0) {
|
|
3240
|
-
break;
|
|
3241
|
-
}
|
|
3242
|
-
const bool = await callback(results, page);
|
|
3243
|
-
if (bool === false) {
|
|
3244
|
-
return false;
|
|
3245
|
-
}
|
|
3246
|
-
page++;
|
|
3247
|
-
} while (countResults === count);
|
|
3248
|
-
return true;
|
|
3249
|
-
}
|
|
3250
|
-
enforceOrderBy() {
|
|
3251
|
-
if (this.query._statements.filter((item) => item.grouping === "order").length === 0) {
|
|
3252
|
-
this.orderBy(this.model.getQualifiedKeyName(), "asc");
|
|
3253
|
-
}
|
|
3254
|
-
}
|
|
3255
|
-
clone() {
|
|
3256
|
-
const query = this.query.clone();
|
|
3257
|
-
const builder = new this.constructor(query);
|
|
3258
|
-
builder.connection = this.connection;
|
|
3259
|
-
builder.setModel(this.model);
|
|
3260
|
-
builder.globalScopes = { ...this.globalScopes };
|
|
3261
|
-
builder.localMacros = { ...this.localMacros };
|
|
3262
|
-
builder.eagerLoad = { ...this.eagerLoad };
|
|
3263
|
-
return builder;
|
|
3264
|
-
}
|
|
3265
|
-
forPage(page, perPage = 15) {
|
|
3266
|
-
return this.offset((page - 1) * perPage).limit(perPage);
|
|
3267
|
-
}
|
|
3268
|
-
insert(...args) {
|
|
3269
|
-
return this.query.insert(...args);
|
|
3270
|
-
}
|
|
3271
|
-
update(values) {
|
|
3272
|
-
this.applyScopes();
|
|
3273
|
-
return this.query.update(this.addUpdatedAtColumn(values));
|
|
3274
|
-
}
|
|
3275
|
-
increment(column, amount = 1, extra = {}) {
|
|
3276
|
-
this.applyScopes();
|
|
3277
|
-
const db = this.model.getConnection();
|
|
3278
|
-
return this.query.update(this.addUpdatedAtColumn({
|
|
3279
|
-
...extra,
|
|
3280
|
-
[column]: db.raw(`${column} + ${amount}`)
|
|
3281
|
-
}));
|
|
3282
|
-
}
|
|
3283
|
-
decrement(column, amount = 1, extra = {}) {
|
|
3284
|
-
this.applyScopes();
|
|
3285
|
-
const db = this.model.getConnection();
|
|
3286
|
-
return this.query.update(this.addUpdatedAtColumn({
|
|
3287
|
-
...extra,
|
|
3288
|
-
[column]: db.raw(`${column} - ${amount}`)
|
|
3289
|
-
}));
|
|
3290
|
-
}
|
|
3291
|
-
addUpdatedAtColumn(values) {
|
|
3292
|
-
if (!this.model.usesTimestamps() || this.model.getUpdatedAtColumn() === null) {
|
|
3293
|
-
return values;
|
|
3294
|
-
}
|
|
3295
|
-
const column = this.model.getUpdatedAtColumn();
|
|
3296
|
-
values = merge2({ [column]: this.model.freshTimestampString() }, values);
|
|
3297
|
-
return values;
|
|
3298
|
-
}
|
|
3299
|
-
delete() {
|
|
3300
|
-
if (this.onDeleteCallback) {
|
|
3301
|
-
return this.onDeleteCallback(this);
|
|
3302
|
-
}
|
|
3303
|
-
return this.query.delete();
|
|
3304
|
-
}
|
|
3305
|
-
onDelete(callback) {
|
|
3306
|
-
this.onDeleteCallback = callback;
|
|
3307
|
-
}
|
|
3308
|
-
forceDelete() {
|
|
3309
|
-
return this.query.delete();
|
|
3310
|
-
}
|
|
3311
|
-
async create(attributes = {}) {
|
|
3312
|
-
return await tap(this.newModelInstance(attributes), async (instance) => {
|
|
3313
|
-
await instance.save({
|
|
3314
|
-
client: this.query
|
|
3315
|
-
});
|
|
3316
|
-
});
|
|
3317
|
-
}
|
|
3318
|
-
newModelInstance(attributes = {}) {
|
|
3319
|
-
return this.model.newInstance(attributes).setConnection(this.model.getConnectionName());
|
|
3320
|
-
}
|
|
3321
|
-
getQuery() {
|
|
3322
|
-
return this.query;
|
|
3323
|
-
}
|
|
3324
|
-
getModel() {
|
|
3325
|
-
return this.model;
|
|
3326
|
-
}
|
|
3327
|
-
setModel(model) {
|
|
3328
|
-
this.model = model;
|
|
3329
|
-
if (typeof this.query?.client?.table == "function") {
|
|
3330
|
-
this.query = this.query.client.table(this.model.getTable());
|
|
3331
|
-
} else {
|
|
3332
|
-
this.query = this.query.table(this.model.getTable());
|
|
3333
|
-
}
|
|
3334
|
-
return this;
|
|
3335
|
-
}
|
|
3336
|
-
qualifyColumn(column) {
|
|
3337
|
-
return this.model.qualifyColumn(column);
|
|
3338
|
-
}
|
|
3339
|
-
setTable(table) {
|
|
3340
|
-
this.query = this.query.table(table);
|
|
3341
|
-
return this;
|
|
3342
|
-
}
|
|
3343
|
-
applyScopes() {
|
|
3344
|
-
if (!this.globalScopes) {
|
|
3345
|
-
return this;
|
|
3346
|
-
}
|
|
3347
|
-
for (const identifier in this.globalScopes) {
|
|
3348
|
-
const scope = this.globalScopes[identifier];
|
|
3349
|
-
if (scope instanceof scope_default) {
|
|
3350
|
-
scope.apply(this, this.getModel());
|
|
3351
|
-
} else {
|
|
3352
|
-
scope(this);
|
|
3353
|
-
}
|
|
3354
|
-
}
|
|
3355
|
-
return this;
|
|
3356
|
-
}
|
|
3357
|
-
hasNamedScope(name) {
|
|
3358
|
-
return this.model && this.model.hasNamedScope(name);
|
|
3359
|
-
}
|
|
3360
|
-
callNamedScope(scope, parameters) {
|
|
3361
|
-
return this.model.callNamedScope(scope, [this, ...parameters]);
|
|
3362
|
-
}
|
|
3363
|
-
callScope(scope, parameters = []) {
|
|
3364
|
-
const result = scope(this, ...parameters) || this;
|
|
3365
|
-
return result;
|
|
3366
|
-
}
|
|
3367
|
-
scopes(scopes) {
|
|
3368
|
-
scopes.map((scopeName) => {
|
|
3369
|
-
const scopeMethod = getScopeMethod(scopeName);
|
|
3370
|
-
if (typeof this.model[scopeMethod] === "function") {
|
|
3371
|
-
this.globalScopes[scopeName] = this.model[scopeMethod];
|
|
3372
|
-
}
|
|
3373
|
-
});
|
|
3374
|
-
return this;
|
|
3375
|
-
}
|
|
3376
|
-
withGlobalScope(identifier, scope) {
|
|
3377
|
-
this.globalScopes[identifier] = scope;
|
|
3378
|
-
if (typeof scope.extend === "function") {
|
|
3379
|
-
scope.extend(this);
|
|
3380
|
-
}
|
|
3381
|
-
return this;
|
|
3382
|
-
}
|
|
3383
|
-
withoutGlobalScope(scope) {
|
|
3384
|
-
if (typeof scope !== "string") {
|
|
3385
|
-
scope = scope.constructor.name;
|
|
3386
|
-
}
|
|
3387
|
-
this.globalScopes = omit5(this.globalScopes, [scope]);
|
|
3388
|
-
return this;
|
|
3389
|
-
}
|
|
3390
|
-
macro(name, callback) {
|
|
3391
|
-
this.localMacros[name] = callback;
|
|
3392
|
-
return this;
|
|
3393
|
-
}
|
|
3394
|
-
hasMacro(name) {
|
|
3395
|
-
return name in this.localMacros;
|
|
3396
|
-
}
|
|
3397
|
-
getMacro(name) {
|
|
3398
|
-
return this.localMacros[name];
|
|
3399
|
-
}
|
|
3400
|
-
with(...args) {
|
|
3401
|
-
let eagerLoads = {};
|
|
3402
|
-
if (typeof args[1] === "function") {
|
|
3403
|
-
const eagerLoad = this.parseWithRelations({
|
|
3404
|
-
[args[0]]: args[1]
|
|
3405
|
-
});
|
|
3406
|
-
this.eagerLoad = merge2(this.eagerLoad, eagerLoad);
|
|
3407
|
-
return this;
|
|
3408
|
-
}
|
|
3409
|
-
const relations = flattenDeep(args);
|
|
3410
|
-
if (relations.length === 0) {
|
|
3411
|
-
return this;
|
|
3412
|
-
}
|
|
3413
|
-
for (const relation of relations) {
|
|
3414
|
-
let eagerLoad;
|
|
3415
|
-
if (typeof relation === "string") {
|
|
3416
|
-
eagerLoad = {
|
|
3417
|
-
[relation]: (q) => q
|
|
3418
|
-
};
|
|
3419
|
-
} else if (typeof relation === "object") {
|
|
3420
|
-
eagerLoad = relation;
|
|
3421
|
-
}
|
|
3422
|
-
eagerLoads = merge2(eagerLoads, eagerLoad);
|
|
3423
|
-
}
|
|
3424
|
-
this.eagerLoad = merge2(this.eagerLoad, this.parseWithRelations(eagerLoads));
|
|
3425
|
-
return this;
|
|
3426
|
-
}
|
|
3427
|
-
has(relation, operator = ">=", count = 1, boolean = "and", callback = null) {
|
|
3428
|
-
if (isString(relation)) {
|
|
3429
|
-
if (relation.includes(".")) {
|
|
3430
|
-
return this.hasNested(relation, operator, count, boolean, callback);
|
|
3431
|
-
}
|
|
3432
|
-
relation = this.getRelationWithoutConstraints(getRelationMethod(relation));
|
|
3433
|
-
}
|
|
3434
|
-
const method = this.canUseExistsForExistenceCheck(operator, count) ? "getRelationExistenceQuery" : "getRelationExistenceCountQuery";
|
|
3435
|
-
const hasQuery = relation[method](relation.getRelated().newModelQuery(), this);
|
|
3436
|
-
if (callback) {
|
|
3437
|
-
callback(hasQuery);
|
|
3438
|
-
}
|
|
3439
|
-
return this.addHasWhere(hasQuery, relation, operator, count, boolean);
|
|
3440
|
-
}
|
|
3441
|
-
orHas(relation, operator = ">=", count = 1) {
|
|
3442
|
-
return this.has(relation, operator, count, "or");
|
|
3443
|
-
}
|
|
3444
|
-
doesntHave(relation, boolean = "and", callback = null) {
|
|
3445
|
-
return this.has(relation, "<", 1, boolean, callback);
|
|
3446
|
-
}
|
|
3447
|
-
orDoesntHave(relation) {
|
|
3448
|
-
return this.doesntHave(relation, "or");
|
|
3449
|
-
}
|
|
3450
|
-
whereHas(relation, callback = null, operator = ">=", count = 1) {
|
|
3451
|
-
return this.has(relation, operator, count, "and", callback);
|
|
3452
|
-
}
|
|
3453
|
-
orWhereHas(relation, callback = null, operator = ">=", count = 1) {
|
|
3454
|
-
return this.has(relation, operator, count, "or", callback);
|
|
3455
|
-
}
|
|
3456
|
-
whereRelation(relation, ...args) {
|
|
3457
|
-
const column = args.shift();
|
|
3458
|
-
return this.whereHas(relation, (query) => {
|
|
3459
|
-
if (typeof column === "function") {
|
|
3460
|
-
column(query);
|
|
3461
|
-
} else {
|
|
3462
|
-
query.where(column, ...args);
|
|
3463
|
-
}
|
|
3464
|
-
});
|
|
3465
|
-
}
|
|
3466
|
-
orWhereRelation(relation, ...args) {
|
|
3467
|
-
const column = args.shift();
|
|
3468
|
-
return this.orWhereHas(relation, function(query) {
|
|
3469
|
-
if (typeof column === "function") {
|
|
3470
|
-
column(query);
|
|
3471
|
-
} else {
|
|
3472
|
-
query.where(column, ...args);
|
|
3473
|
-
}
|
|
3474
|
-
});
|
|
3475
|
-
}
|
|
3476
|
-
hasNested(relations, operator = ">=", count = 1, boolean = "and", callback = null) {
|
|
3477
|
-
relations = relations.split(".");
|
|
3478
|
-
const doesntHave = operator === "<" && count === 1;
|
|
3479
|
-
if (doesntHave) {
|
|
3480
|
-
operator = ">=";
|
|
3481
|
-
count = 1;
|
|
3482
|
-
}
|
|
3483
|
-
const closure = (q) => {
|
|
3484
|
-
if (relations.length > 1) {
|
|
3485
|
-
q.whereHas(relations.shift(), closure);
|
|
3486
|
-
} else {
|
|
3487
|
-
q.has(relations.shift(), operator, count, "and", callback);
|
|
3488
|
-
}
|
|
3489
|
-
return null;
|
|
3490
|
-
};
|
|
3491
|
-
return this.has(relations.shift(), doesntHave ? "<" : ">=", 1, boolean, closure);
|
|
3492
|
-
}
|
|
3493
|
-
canUseExistsForExistenceCheck(operator, count) {
|
|
3494
|
-
return (operator === ">=" || operator === "<") && count === 1;
|
|
3495
|
-
}
|
|
3496
|
-
addHasWhere(hasQuery, relation, operator, count, boolean) {
|
|
3497
|
-
hasQuery.mergeConstraintsFrom(relation.getQuery());
|
|
3498
|
-
return this.canUseExistsForExistenceCheck(operator, count) ? this.addWhereExistsQuery(hasQuery.getQuery(), boolean, operator === "<" && count === 1) : this.addWhereCountQuery(hasQuery.getQuery(), operator, count, boolean);
|
|
3499
|
-
}
|
|
3500
|
-
addWhereExistsQuery(query, boolean = "and", not = false) {
|
|
3501
|
-
const type = not ? "NotExists" : "Exists";
|
|
3502
|
-
const method = boolean === "and" ? "where" + type : "orWhere" + type;
|
|
3503
|
-
this[method](query.connector);
|
|
3504
|
-
return this;
|
|
3505
|
-
}
|
|
3506
|
-
addWhereCountQuery(query, operator = ">=", count = 1, boolean = "and") {
|
|
3507
|
-
const db = this.model.getConnection();
|
|
3508
|
-
return this.where(db.raw("(" + query.toSQL().sql + ")"), operator, typeof count === "number" ? db.raw(count) : count, boolean);
|
|
3509
|
-
}
|
|
3510
|
-
withAggregate(relations, column, action = null) {
|
|
3511
|
-
if (relations.length === 0) {
|
|
3512
|
-
return this;
|
|
3513
|
-
}
|
|
3514
|
-
relations = flattenDeep([relations]);
|
|
3515
|
-
let eagerLoads = {};
|
|
3516
|
-
for (const relation of relations) {
|
|
3517
|
-
let eagerLoad;
|
|
3518
|
-
if (typeof relation === "string") {
|
|
3519
|
-
eagerLoad = {
|
|
3520
|
-
[relation]: (q) => q
|
|
3521
|
-
};
|
|
3522
|
-
} else if (typeof relation === "object") {
|
|
3523
|
-
eagerLoad = relation;
|
|
3524
|
-
}
|
|
3525
|
-
eagerLoads = merge2(eagerLoads, eagerLoad);
|
|
3526
|
-
}
|
|
3527
|
-
relations = eagerLoads;
|
|
3528
|
-
const db = this.model.getConnection();
|
|
3529
|
-
const columns = this.query._statements.filter((item) => item.grouping == "columns").map((item) => item.value).flat();
|
|
3530
|
-
if (columns.length === 0) {
|
|
3531
|
-
this.query.select([this.query._single.table + ".*"]);
|
|
3532
|
-
}
|
|
3533
|
-
const parses = this.parseWithRelations(relations);
|
|
3534
|
-
for (let name in parses) {
|
|
3535
|
-
const constraints = parses[name];
|
|
3536
|
-
const segments = name.split(" ");
|
|
3537
|
-
let alias, expression;
|
|
3538
|
-
if (segments.length === 3 && segments[1].toLocaleLowerCase() === "as") {
|
|
3539
|
-
[name, alias] = [segments[0], segments[2]];
|
|
3540
|
-
}
|
|
3541
|
-
const relation = this.getRelationWithoutConstraints(getRelationMethod(name));
|
|
3542
|
-
if (action) {
|
|
3543
|
-
const hashedColumn = this.query._single.table === relation.query.query._single.table ? `${relation.getRelationCountHash(false)}.${column}` : column;
|
|
3544
|
-
const wrappedColumn = column === "*" ? column : relation.getRelated().qualifyColumn(hashedColumn);
|
|
3545
|
-
expression = action === "exists" ? wrappedColumn : `${action}(${wrappedColumn})`;
|
|
3546
|
-
} else {
|
|
3547
|
-
expression = column;
|
|
3548
|
-
}
|
|
3549
|
-
const query = relation.getRelationExistenceQuery(relation.getRelated().newModelQuery(), this, db.raw(expression));
|
|
3550
|
-
constraints(query);
|
|
3551
|
-
alias = alias || snake2(`${name} ${action} ${column}`.replace("/[^[:alnum:][:space:]_]/u", ""));
|
|
3552
|
-
if (action === "exists") {
|
|
3553
|
-
this.select(db.raw(`exists(${query.toSql().sql}) as ${alias}`));
|
|
3554
|
-
} else {
|
|
3555
|
-
this.selectSub(action ? query : query.limit(1), alias);
|
|
3556
|
-
}
|
|
3557
|
-
}
|
|
3558
|
-
return this;
|
|
3559
|
-
}
|
|
3560
|
-
toSql() {
|
|
3561
|
-
const query = this.clone();
|
|
3562
|
-
query.applyScopes();
|
|
3563
|
-
return query.query.toSQL();
|
|
3564
|
-
}
|
|
3565
|
-
mergeConstraintsFrom(_from) {
|
|
3566
|
-
return this;
|
|
3567
|
-
}
|
|
3568
|
-
selectSub(query, as) {
|
|
3569
|
-
const [querySub, bindings] = this.createSub(query);
|
|
3570
|
-
const db = this.model.getConnection();
|
|
3571
|
-
return this.select(db.raw("(" + querySub + ") as " + as, bindings));
|
|
3572
|
-
}
|
|
3573
|
-
createSub(query) {
|
|
3574
|
-
return this.parseSub(query);
|
|
3575
|
-
}
|
|
3576
|
-
parseSub(query) {
|
|
3577
|
-
if (query instanceof _Builder || query instanceof relation_default) {
|
|
3578
|
-
return [query.toSql().sql, query.toSql().bindings];
|
|
3579
|
-
} else if (isString(query)) {
|
|
3580
|
-
return [query, []];
|
|
3581
|
-
} else {
|
|
3582
|
-
throw new Error("A subquery must be a query builder instance, a Closure, or a string.");
|
|
3583
|
-
}
|
|
3584
|
-
}
|
|
3585
|
-
prependDatabaseNameIfCrossDatabaseQuery(query) {
|
|
3586
|
-
if (query.query._single.table !== this.query._single.table) {
|
|
3587
|
-
const databaseName = query.query._single.table;
|
|
3588
|
-
if (!query.query._single.table.startsWith(databaseName) && !query.query._single.table.contains(".")) {
|
|
3589
|
-
query.from(databaseName + "." + query.from);
|
|
3590
|
-
}
|
|
3591
|
-
}
|
|
3592
|
-
return query;
|
|
3593
|
-
}
|
|
3594
|
-
getRelationWithoutConstraints(relation) {
|
|
3595
|
-
return relation_default.noConstraints(() => {
|
|
3596
|
-
return this.getModel()[relation]();
|
|
3597
|
-
});
|
|
3598
|
-
}
|
|
3599
|
-
withCount(...args) {
|
|
3600
|
-
return this.withAggregate(flattenDeep(args), "*", "count");
|
|
3601
|
-
}
|
|
3602
|
-
withMax(relation, column) {
|
|
3603
|
-
return this.withAggregate(relation, column, "max");
|
|
3604
|
-
}
|
|
3605
|
-
withMin(relation, column) {
|
|
3606
|
-
return this.withAggregate(relation, column, "min");
|
|
3607
|
-
}
|
|
3608
|
-
withAvg(relation, column) {
|
|
3609
|
-
return this.withAggregate(relation, column, "avg");
|
|
3610
|
-
}
|
|
3611
|
-
withSum(relation, column) {
|
|
3612
|
-
return this.withAggregate(relation, column, "sum");
|
|
3613
|
-
}
|
|
3614
|
-
withExists(relation) {
|
|
3615
|
-
return this.withAggregate(relation, "*", "exists");
|
|
3616
|
-
}
|
|
3617
|
-
parseWithRelations(relations) {
|
|
3618
|
-
if (relations.length === 0) {
|
|
3619
|
-
return [];
|
|
3620
|
-
}
|
|
3621
|
-
let results = {};
|
|
3622
|
-
const constraintsMap = this.prepareNestedWithRelationships(relations);
|
|
3623
|
-
for (const name in constraintsMap) {
|
|
3624
|
-
results = this.addNestedWiths(name, results);
|
|
3625
|
-
results[name] = constraintsMap[name];
|
|
3626
|
-
}
|
|
3627
|
-
return results;
|
|
3628
|
-
}
|
|
3629
|
-
addNestedWiths(name, results) {
|
|
3630
|
-
const progress = [];
|
|
3631
|
-
name.split(".").map((segment) => {
|
|
3632
|
-
progress.push(segment);
|
|
3633
|
-
const last = progress.join(".");
|
|
3634
|
-
if (results[last] === void 0) {
|
|
3635
|
-
results[last] = () => {
|
|
3636
|
-
};
|
|
3637
|
-
}
|
|
3638
|
-
});
|
|
3639
|
-
return results;
|
|
3640
|
-
}
|
|
3641
|
-
prepareNestedWithRelationships(relations, prefix = "") {
|
|
3642
|
-
let preparedRelationships = {};
|
|
3643
|
-
if (prefix !== "") {
|
|
3644
|
-
prefix += ".";
|
|
3645
|
-
}
|
|
3646
|
-
for (const key in relations) {
|
|
3647
|
-
const value = relations[key];
|
|
3648
|
-
if (isString(value) || Number.isFinite(parseInt(value))) {
|
|
3649
|
-
continue;
|
|
3650
|
-
}
|
|
3651
|
-
const [attribute, attributeSelectConstraint] = this.parseNameAndAttributeSelectionConstraint(key, value);
|
|
3652
|
-
preparedRelationships = Object.assign({}, preparedRelationships, {
|
|
3653
|
-
[`${prefix}${attribute}`]: attributeSelectConstraint
|
|
3654
|
-
}, this.prepareNestedWithRelationships(value, `${prefix}${attribute}`));
|
|
3655
|
-
relations = omit5(relations, [key]);
|
|
3656
|
-
}
|
|
3657
|
-
for (const key in relations) {
|
|
3658
|
-
const value = relations[key];
|
|
3659
|
-
let attribute = key, attributeSelectConstraint = value;
|
|
3660
|
-
if (isString(value)) {
|
|
3661
|
-
[attribute, attributeSelectConstraint] = this.parseNameAndAttributeSelectionConstraint(value);
|
|
3662
|
-
}
|
|
3663
|
-
preparedRelationships[`${prefix}${attribute}`] = this.combineConstraints([
|
|
3664
|
-
attributeSelectConstraint,
|
|
3665
|
-
preparedRelationships[`${prefix}${attribute}`] || (() => {
|
|
3666
|
-
})
|
|
3667
|
-
]);
|
|
3668
|
-
}
|
|
3669
|
-
return preparedRelationships;
|
|
3670
|
-
}
|
|
3671
|
-
combineConstraints(constraints) {
|
|
3672
|
-
return (builder) => {
|
|
3673
|
-
constraints.map((constraint) => {
|
|
3674
|
-
builder = constraint(builder) || builder;
|
|
3675
|
-
});
|
|
3676
|
-
return builder;
|
|
3677
|
-
};
|
|
3678
|
-
}
|
|
3679
|
-
parseNameAndAttributeSelectionConstraint(name, value) {
|
|
3680
|
-
return name.includes(":") ? this.createSelectWithConstraint(name) : [name, value];
|
|
3681
|
-
}
|
|
3682
|
-
createSelectWithConstraint(name) {
|
|
3683
|
-
return [name.split(":")[0], (query) => {
|
|
3684
|
-
query.select(name.split(":")[1].split(",").map((column) => {
|
|
3685
|
-
if (column.includes(".")) {
|
|
3686
|
-
return column;
|
|
3687
|
-
}
|
|
3688
|
-
return query instanceof belongs_to_many_default ? query.related.getTable() + "." + column : column;
|
|
3689
|
-
}));
|
|
3690
|
-
}];
|
|
3691
|
-
}
|
|
3692
|
-
related(relation) {
|
|
3693
|
-
if (typeof this.model[getRelationMethod(relation)] !== "function") {
|
|
3694
|
-
const message = `Model [${this.model.constructor.name}]'s relation [${relation}] doesn't exist.`;
|
|
3695
|
-
throw new RelationNotFoundError(message);
|
|
3696
|
-
}
|
|
3697
|
-
return this.model[getRelationMethod(relation)]();
|
|
3698
|
-
}
|
|
3699
|
-
take(...args) {
|
|
3700
|
-
return this.limit(...args);
|
|
3701
|
-
}
|
|
3702
|
-
skip(...args) {
|
|
3703
|
-
return this.offset(...args);
|
|
3704
|
-
}
|
|
3705
|
-
async first(...columns) {
|
|
3706
|
-
this.applyScopes();
|
|
3707
|
-
this.limit(1);
|
|
3708
|
-
let models = await this.getModels(columns);
|
|
3709
|
-
if (models.length > 0) {
|
|
3710
|
-
models = await this.eagerLoadRelations(models);
|
|
3711
|
-
}
|
|
3712
|
-
return models[0] || null;
|
|
3713
|
-
}
|
|
3714
|
-
async firstOrFail(...columns) {
|
|
3715
|
-
const data = await this.first(...columns);
|
|
3716
|
-
if (data === null) {
|
|
3717
|
-
throw new ModelNotFoundError().setModel(this.model.constructor.name);
|
|
3718
|
-
}
|
|
3719
|
-
return data;
|
|
3720
|
-
}
|
|
3721
|
-
async findOrFail(...args) {
|
|
3722
|
-
const data = await this.find(...args);
|
|
3723
|
-
if (isArray5(args[0])) {
|
|
3724
|
-
if (data.count() !== args[0].length) {
|
|
3725
|
-
throw new ModelNotFoundError().setModel(this.model.constructor.name, difference4(args[0], data.modelKeys()));
|
|
3726
|
-
}
|
|
3727
|
-
return data;
|
|
3728
|
-
}
|
|
3729
|
-
if (data === null) {
|
|
3730
|
-
throw new ModelNotFoundError().setModel(this.model.constructor.name, args[0]);
|
|
3731
|
-
}
|
|
3732
|
-
return data;
|
|
3733
|
-
}
|
|
3734
|
-
async findOrNew(id, columns = ["*"]) {
|
|
3735
|
-
const model = await this.find(id, columns);
|
|
3736
|
-
if (model !== null) {
|
|
3737
|
-
return model;
|
|
3738
|
-
}
|
|
3739
|
-
return this.newModelInstance();
|
|
3740
|
-
}
|
|
3741
|
-
async firstOrNew(attributes = {}, values = {}) {
|
|
3742
|
-
const instance = await this.where(attributes).first();
|
|
3743
|
-
if (instance !== null) {
|
|
3744
|
-
return instance;
|
|
3745
|
-
}
|
|
3746
|
-
return this.newModelInstance(merge2(attributes, values));
|
|
3747
|
-
}
|
|
3748
|
-
async firstOrCreate(attributes = {}, values = {}) {
|
|
3749
|
-
const instance = await this.where(attributes).first();
|
|
3750
|
-
if (instance !== null) {
|
|
3751
|
-
return instance;
|
|
3752
|
-
}
|
|
3753
|
-
return tap(this.newModelInstance(merge2(attributes, values)), async (instance2) => {
|
|
3754
|
-
await instance2.save({
|
|
3755
|
-
client: this.query
|
|
3756
|
-
});
|
|
3757
|
-
});
|
|
3758
|
-
}
|
|
3759
|
-
async updateOrCreate(attributes, values = {}) {
|
|
3760
|
-
return await tap(await this.firstOrNew(attributes), async (instance) => {
|
|
3761
|
-
await instance.fill(values).save({
|
|
3762
|
-
client: this.query
|
|
3763
|
-
});
|
|
3764
|
-
});
|
|
3765
|
-
}
|
|
3766
|
-
latest(column = "id") {
|
|
3767
|
-
if (column === null) {
|
|
3768
|
-
column = this.model.getCreatedAtColumn() || "created_at";
|
|
3769
|
-
}
|
|
3770
|
-
this.query.orderBy(column, "desc");
|
|
3771
|
-
return this;
|
|
3772
|
-
}
|
|
3773
|
-
oldest(column = "id") {
|
|
3774
|
-
if (column === null) {
|
|
3775
|
-
column = this.model.getCreatedAtColumn() || "created_at";
|
|
3776
|
-
}
|
|
3777
|
-
this.query.orderBy(column, "asc");
|
|
3778
|
-
return this;
|
|
3779
|
-
}
|
|
3780
|
-
async find(id, columns) {
|
|
3781
|
-
if (isArray5(id) || id instanceof collection_default) {
|
|
3782
|
-
return await this.findMany(id, columns);
|
|
3783
|
-
}
|
|
3784
|
-
return await this.where(this.model.getKeyName(), id).first(columns);
|
|
3785
|
-
}
|
|
3786
|
-
async findMany(ids, columns = ["*"]) {
|
|
3787
|
-
if (ids instanceof collection_default) {
|
|
3788
|
-
ids = ids.modelKeys();
|
|
3789
|
-
}
|
|
3790
|
-
ids = isArray5(ids) ? ids : [ids];
|
|
3791
|
-
if (ids.length === 0) {
|
|
3792
|
-
return new collection_default([]);
|
|
3793
|
-
}
|
|
3794
|
-
return await this.whereIn(this.model.getKeyName(), ids).get(columns);
|
|
3795
|
-
}
|
|
3796
|
-
async pluck(column) {
|
|
3797
|
-
const data = await this.query.pluck(column);
|
|
3798
|
-
return new collection_default(data);
|
|
3799
|
-
}
|
|
3800
|
-
async destroy(ids) {
|
|
3801
|
-
if (ids instanceof collection_default) {
|
|
3802
|
-
ids = ids.modelKeys();
|
|
3803
|
-
}
|
|
3804
|
-
if (ids instanceof BaseCollection2) {
|
|
3805
|
-
ids = ids.all();
|
|
3806
|
-
}
|
|
3807
|
-
ids = isArray5(ids) ? ids : Array.prototype.slice.call(ids);
|
|
3808
|
-
if (ids.length === 0) {
|
|
3809
|
-
return 0;
|
|
3810
|
-
}
|
|
3811
|
-
const instance = this.model.newInstance();
|
|
3812
|
-
const key = instance.getKeyName();
|
|
3813
|
-
let count = 0;
|
|
3814
|
-
const models = await this.model.newModelQuery().whereIn(key, ids).get();
|
|
3815
|
-
for (const model of models) {
|
|
3816
|
-
if (await model.delete()) {
|
|
3817
|
-
count++;
|
|
3818
|
-
}
|
|
3819
|
-
}
|
|
3820
|
-
return count;
|
|
3821
|
-
}
|
|
3822
|
-
async get(columns = ["*"]) {
|
|
3823
|
-
this.applyScopes();
|
|
3824
|
-
let models = await this.getModels(columns);
|
|
3825
|
-
if (models.length > 0) {
|
|
3826
|
-
models = await this.eagerLoadRelations(models);
|
|
3827
|
-
}
|
|
3828
|
-
return new collection_default(models);
|
|
3829
|
-
}
|
|
3830
|
-
async all(columns = ["*"]) {
|
|
3831
|
-
return await this.model.newModelQuery().get(columns);
|
|
3832
|
-
}
|
|
3833
|
-
async paginate(page = 1, perPage = 10) {
|
|
3834
|
-
page = page || 1;
|
|
3835
|
-
perPage = perPage || this?.model?.perPage || 15;
|
|
3836
|
-
this.applyScopes();
|
|
3837
|
-
const query = this.query.clone();
|
|
3838
|
-
const total = await query.clearOrder().clearSelect().count(this.primaryKey);
|
|
3839
|
-
let results = [];
|
|
3840
|
-
if (total > 0) {
|
|
3841
|
-
const skip = (page - 1) * (perPage ?? 10);
|
|
3842
|
-
this.take(perPage).skip(skip);
|
|
3843
|
-
results = await this.getModels();
|
|
3844
|
-
if (results.length > 0) {
|
|
3845
|
-
results = await this.eagerLoadRelations(results);
|
|
3846
|
-
}
|
|
3847
|
-
} else {
|
|
3848
|
-
results = [];
|
|
3849
|
-
}
|
|
3850
|
-
return new paginator_default(results, parseInt(total), perPage, page);
|
|
3851
|
-
}
|
|
3852
|
-
async getModels(...columns) {
|
|
3853
|
-
columns = flatten2(columns);
|
|
3854
|
-
if (columns.length > 0) {
|
|
3855
|
-
if (this.query._statements.filter((item) => item.grouping == "columns").length == 0 && columns[0] !== "*") {
|
|
3856
|
-
this.query.select(...columns);
|
|
3857
|
-
}
|
|
3858
|
-
}
|
|
3859
|
-
return this.hydrate(await this.query.get()).all();
|
|
3860
|
-
}
|
|
3861
|
-
getRelation(name) {
|
|
3862
|
-
if (typeof this.model[getRelationMethod(name)] !== "function") {
|
|
3863
|
-
const message = `Model [${this.model.constructor.name}]'s relation [${name}] doesn't exist.`;
|
|
3864
|
-
throw new RelationNotFoundError(message);
|
|
3865
|
-
}
|
|
3866
|
-
const relation = relation_default.noConstraints(() => this.model.newInstance(this.model.attributes)[getRelationMethod(name)]());
|
|
3867
|
-
const nested = this.relationsNestedUnder(name);
|
|
3868
|
-
if (Object.keys(nested).length > 0) {
|
|
3869
|
-
relation.query.with(nested);
|
|
3870
|
-
}
|
|
3871
|
-
return relation.asProxy();
|
|
3872
|
-
}
|
|
3873
|
-
relationsNestedUnder(relation) {
|
|
3874
|
-
const nested = {};
|
|
3875
|
-
for (const name in this.eagerLoad) {
|
|
3876
|
-
const constraints = this.eagerLoad[name];
|
|
3877
|
-
if (this.isNestedUnder(relation, name)) {
|
|
3878
|
-
nested[name.substring((relation + ".").length)] = constraints;
|
|
3879
|
-
}
|
|
3880
|
-
}
|
|
3881
|
-
return nested;
|
|
3882
|
-
}
|
|
3883
|
-
isNestedUnder(relation, name) {
|
|
3884
|
-
return name.includes(".") && name.startsWith(relation + ".");
|
|
3885
|
-
}
|
|
3886
|
-
async eagerLoadRelation(models, name, constraints) {
|
|
3887
|
-
const relation = this.getRelation(name);
|
|
3888
|
-
relation.addEagerConstraints(models);
|
|
3889
|
-
constraints(relation);
|
|
3890
|
-
return relation.match(relation.initRelation(models, name), await relation.get(), name);
|
|
3891
|
-
}
|
|
3892
|
-
async eagerLoadRelations(models) {
|
|
3893
|
-
for (const name in this.eagerLoad) {
|
|
3894
|
-
const constraints = this.eagerLoad[name];
|
|
3895
|
-
if (!name.includes(".")) {
|
|
3896
|
-
models = await this.eagerLoadRelation(models, name, constraints);
|
|
3897
|
-
}
|
|
3898
|
-
}
|
|
3899
|
-
return models;
|
|
3900
|
-
}
|
|
3901
|
-
hydrate(items) {
|
|
3902
|
-
return new collection_default(items.map((item) => {
|
|
3903
|
-
if (!this.model) {
|
|
3904
|
-
return item;
|
|
3905
|
-
}
|
|
3906
|
-
const model = this.model.newFromBuilder(item);
|
|
3907
|
-
return model;
|
|
3908
|
-
}));
|
|
3909
|
-
}
|
|
3910
|
-
};
|
|
3911
|
-
var builder_default = Builder;
|
|
3912
|
-
|
|
3913
|
-
// src/concerns/has-unique-ids.ts
|
|
3914
|
-
var HasUniqueIds = (Model2) => {
|
|
3915
|
-
return class extends Model2 {
|
|
3916
|
-
useUniqueIds = true;
|
|
3917
|
-
uniqueIds() {
|
|
3918
|
-
return [this.getKeyName()];
|
|
3919
|
-
}
|
|
3920
|
-
getKeyType() {
|
|
3921
|
-
if (this.uniqueIds().includes(this.getKeyName())) {
|
|
3922
|
-
return "string";
|
|
3923
|
-
}
|
|
3924
|
-
return this.keyType;
|
|
3925
|
-
}
|
|
3926
|
-
getIncrementing() {
|
|
3927
|
-
if (this.uniqueIds().includes(this.getKeyName())) {
|
|
3928
|
-
return false;
|
|
3929
|
-
}
|
|
3930
|
-
return this.incrementing;
|
|
3931
|
-
}
|
|
3932
|
-
};
|
|
3933
|
-
};
|
|
3934
|
-
var has_unique_ids_default = HasUniqueIds;
|
|
3935
|
-
|
|
3936
|
-
// src/migrations/migration-repository.ts
|
|
3937
|
-
var MigrationRepository = class {
|
|
3938
|
-
resolver;
|
|
3939
|
-
table;
|
|
3940
|
-
connection = null;
|
|
3941
|
-
constructor(resolver, table) {
|
|
3942
|
-
this.resolver = resolver;
|
|
3943
|
-
this.table = table;
|
|
3944
|
-
}
|
|
3945
|
-
async getRan() {
|
|
3946
|
-
return await this.getTable().orderBy("batch", "asc").orderBy("migration", "asc").pluck("migration");
|
|
3947
|
-
}
|
|
3948
|
-
async getMigrations(steps) {
|
|
3949
|
-
const query = this.getTable().where("batch", ">=", "1");
|
|
3950
|
-
return await query.orderBy("batch", "desc").orderBy("migration", "desc").take(steps).get();
|
|
3951
|
-
}
|
|
3952
|
-
async getMigrationsByBatch(batch) {
|
|
3953
|
-
return await this.getTable().where("batch", batch).orderBy("migration", "desc").get();
|
|
3954
|
-
}
|
|
3955
|
-
async getLast() {
|
|
3956
|
-
const query = this.getTable().where("batch", await this.getLastBatchNumber());
|
|
3957
|
-
return await query.orderBy("migration", "desc").get();
|
|
3958
|
-
}
|
|
3959
|
-
async getMigrationBatches() {
|
|
3960
|
-
const migrations = await this.getTable().select("batch", "migration").orderBy("batch", "asc").orderBy("migration", "asc").get();
|
|
3961
|
-
const migrationBatches = {};
|
|
3962
|
-
migrations.map((migration) => {
|
|
3963
|
-
migrationBatches[migration.migration] = migration.batch;
|
|
3964
|
-
});
|
|
3965
|
-
return migrationBatches;
|
|
3966
|
-
}
|
|
3967
|
-
async log(file, batch) {
|
|
3968
|
-
await this.getTable().insert({
|
|
3969
|
-
migration: file,
|
|
3970
|
-
batch
|
|
3971
|
-
});
|
|
3972
|
-
}
|
|
3973
|
-
async delete(migration) {
|
|
3974
|
-
await this.getTable().where("migration", migration.migration).delete();
|
|
3975
|
-
}
|
|
3976
|
-
async getNextBatchNumber() {
|
|
3977
|
-
return await this.getLastBatchNumber() + 1;
|
|
3978
|
-
}
|
|
3979
|
-
async getLastBatchNumber() {
|
|
3980
|
-
return await this.getTable().max("batch");
|
|
3981
|
-
}
|
|
3982
|
-
async createRepository() {
|
|
3983
|
-
const schema = this.getConnection().schema;
|
|
3984
|
-
await schema.createTable(this.table, function(table) {
|
|
3985
|
-
table.increments("id");
|
|
3986
|
-
table.string("migration");
|
|
3987
|
-
table.integer("batch");
|
|
3988
|
-
});
|
|
3989
|
-
}
|
|
3990
|
-
repositoryExists() {
|
|
3991
|
-
const schema = this.getConnection().schema;
|
|
3992
|
-
return schema.hasTable(this.table);
|
|
3993
|
-
}
|
|
3994
|
-
async deleteRepository() {
|
|
3995
|
-
const schema = this.getConnection().schema;
|
|
3996
|
-
await schema.drop(this.table);
|
|
3997
|
-
}
|
|
3998
|
-
getTable() {
|
|
3999
|
-
return this.getConnection().table(this.table);
|
|
4000
|
-
}
|
|
4001
|
-
getConnection() {
|
|
4002
|
-
return this.resolver.connection(this.connection);
|
|
4003
|
-
}
|
|
4004
|
-
setSource(name) {
|
|
4005
|
-
this.connection = name;
|
|
4006
|
-
}
|
|
4007
|
-
};
|
|
4008
|
-
var migration_repository_default = MigrationRepository;
|
|
4009
|
-
|
|
4010
|
-
// src/migrations/migrator.ts
|
|
4011
|
-
import color from "chalk";
|
|
4012
|
-
import fs from "fs/promises";
|
|
4013
|
-
import path from "path";
|
|
4014
|
-
async function glob(folderPath) {
|
|
4015
|
-
const files = await fs.readdir(folderPath);
|
|
4016
|
-
const allFiles = [];
|
|
4017
|
-
for (const file of files) {
|
|
4018
|
-
const filePath = `${folderPath}/${file}`;
|
|
4019
|
-
const stats = await fs.stat(filePath);
|
|
4020
|
-
if (stats.isFile()) {
|
|
4021
|
-
allFiles.push(filePath);
|
|
4022
|
-
} else if (stats.isDirectory()) {
|
|
4023
|
-
const subFiles = await glob(filePath);
|
|
4024
|
-
allFiles.push(...subFiles);
|
|
4025
|
-
}
|
|
4026
|
-
}
|
|
4027
|
-
return allFiles;
|
|
4028
|
-
}
|
|
4029
|
-
var Migrator = class {
|
|
4030
|
-
events = null;
|
|
4031
|
-
repository;
|
|
4032
|
-
files;
|
|
4033
|
-
resolver;
|
|
4034
|
-
connection;
|
|
4035
|
-
paths = [];
|
|
4036
|
-
output = null;
|
|
4037
|
-
constructor(repository, resolver = null, files = null, dispatcher = null) {
|
|
4038
|
-
this.repository = repository;
|
|
4039
|
-
this.files = files;
|
|
4040
|
-
this.resolver = resolver;
|
|
4041
|
-
this.events = dispatcher;
|
|
4042
|
-
}
|
|
4043
|
-
async run(paths = [], options = {}) {
|
|
4044
|
-
const files = await this.getMigrationFiles(paths);
|
|
4045
|
-
const ran = await this.repository.getRan();
|
|
4046
|
-
const migrations = this.pendingMigrations(files, ran);
|
|
4047
|
-
await this.runPending(migrations, options);
|
|
4048
|
-
return migrations;
|
|
4049
|
-
}
|
|
4050
|
-
pendingMigrations(files, ran) {
|
|
4051
|
-
return Object.values(files).filter((file) => !ran.includes(this.getMigrationName(file)));
|
|
4052
|
-
}
|
|
4053
|
-
async runPending(migrations, options = {}) {
|
|
4054
|
-
if (migrations.length === 0) {
|
|
4055
|
-
this.write("Nothing to migrate");
|
|
4056
|
-
return;
|
|
4057
|
-
}
|
|
4058
|
-
let batch = await this.repository.getNextBatchNumber();
|
|
4059
|
-
const pretend = options.pretend || false;
|
|
4060
|
-
const step = options.step || false;
|
|
4061
|
-
this.write("Running migrations.");
|
|
4062
|
-
for (const file of migrations) {
|
|
4063
|
-
await this.runUp(file, batch, pretend);
|
|
4064
|
-
if (step) {
|
|
4065
|
-
batch++;
|
|
4066
|
-
}
|
|
4067
|
-
}
|
|
4068
|
-
}
|
|
4069
|
-
async runUp(file, batch, _pretend) {
|
|
4070
|
-
const migration = await this.resolvePath(file);
|
|
4071
|
-
const name = this.getMigrationName(file);
|
|
4072
|
-
await this.writeTask(name, () => this.runMigration(migration, "up"));
|
|
4073
|
-
await this.repository.log(name, batch);
|
|
4074
|
-
}
|
|
4075
|
-
async runDown(file, migration, _pretend) {
|
|
4076
|
-
const instance = await this.resolvePath(file);
|
|
4077
|
-
const name = this.getMigrationName(file);
|
|
4078
|
-
await this.writeTask(name, () => this.runMigration(instance, "down"));
|
|
4079
|
-
await this.repository.delete(migration);
|
|
4080
|
-
}
|
|
4081
|
-
async rollback(paths = [], options = {}) {
|
|
4082
|
-
const migrations = await this.getMigrationsForRollback(options);
|
|
4083
|
-
if (migrations.length === 0) {
|
|
4084
|
-
this.write("Nothing to rollback.");
|
|
4085
|
-
return [];
|
|
4086
|
-
}
|
|
4087
|
-
return await this.rollbackMigrations(migrations, paths, options);
|
|
4088
|
-
}
|
|
4089
|
-
async getMigrationsForRollback(options) {
|
|
4090
|
-
if (options.step && options.step > 0) {
|
|
4091
|
-
return await this.repository.getMigrations(options.step);
|
|
4092
|
-
}
|
|
4093
|
-
if (options.batch && options.batch > 0) {
|
|
4094
|
-
return await this.repository.getMigrationsByBatch(options.batch);
|
|
4095
|
-
}
|
|
4096
|
-
return await this.repository.getLast();
|
|
4097
|
-
}
|
|
4098
|
-
async rollbackMigrations(migrations, paths, options) {
|
|
4099
|
-
const rolledBack = [];
|
|
4100
|
-
const files = await this.getMigrationFiles(paths);
|
|
4101
|
-
this.write("Rolling back migrations.");
|
|
4102
|
-
for (const migration of migrations) {
|
|
4103
|
-
const file = files[migration.migration];
|
|
4104
|
-
if (!file) {
|
|
4105
|
-
this.writeTwoColumns(migration.migration, color.yellow("Migration not found"));
|
|
4106
|
-
continue;
|
|
4107
|
-
}
|
|
4108
|
-
rolledBack.push(file);
|
|
4109
|
-
await this.runDown(file, migration, options.pretend || false);
|
|
4110
|
-
}
|
|
4111
|
-
return rolledBack;
|
|
4112
|
-
}
|
|
4113
|
-
reset(_paths = [], _pretend = false) {
|
|
4114
|
-
const _migrations = this.repository.getRan().then((r) => r.reverse());
|
|
4115
|
-
return [];
|
|
4116
|
-
}
|
|
4117
|
-
resetMigrations(migrations, paths, pretend = false) {
|
|
4118
|
-
return this.rollbackMigrations(migrations, paths, { pretend });
|
|
4119
|
-
}
|
|
4120
|
-
async runMigration(migration, method) {
|
|
4121
|
-
const connection = this.resolveConnection(migration.getConnection());
|
|
4122
|
-
const callback = async (trx) => {
|
|
4123
|
-
if (typeof migration[method] === "function") {
|
|
4124
|
-
await this.runMethod(trx, migration, method);
|
|
4125
|
-
}
|
|
4126
|
-
};
|
|
4127
|
-
if (migration.withinTransaction) {
|
|
4128
|
-
await connection.transaction(callback);
|
|
4129
|
-
} else {
|
|
4130
|
-
await callback(connection);
|
|
4131
|
-
}
|
|
4132
|
-
}
|
|
4133
|
-
async runMethod(connection, migration, method) {
|
|
4134
|
-
await migration[method]?.(connection.schema, connection);
|
|
4135
|
-
}
|
|
4136
|
-
async resolvePath(filePath) {
|
|
4137
|
-
try {
|
|
4138
|
-
return new (await import(filePath)).default();
|
|
4139
|
-
} catch {
|
|
4140
|
-
}
|
|
4141
|
-
return new class {
|
|
4142
|
-
}();
|
|
4143
|
-
}
|
|
4144
|
-
getMigrationClass(migrationName) {
|
|
4145
|
-
return migrationName.split("_").slice(4).map((str) => str.charAt(0).toUpperCase() + str.slice(1)).join("");
|
|
4146
|
-
}
|
|
4147
|
-
async getMigrationFiles(paths) {
|
|
4148
|
-
const files = [];
|
|
4149
|
-
for (const p of paths) {
|
|
4150
|
-
if (p.endsWith(".js") || p.endsWith(".ts")) {
|
|
4151
|
-
files.push(p);
|
|
4152
|
-
continue;
|
|
4153
|
-
}
|
|
4154
|
-
files.push(...await glob(p));
|
|
4155
|
-
}
|
|
4156
|
-
return files.filter(Boolean).reduce((result, file) => {
|
|
4157
|
-
result[this.getMigrationName(file)] = file;
|
|
4158
|
-
return result;
|
|
4159
|
-
}, {});
|
|
4160
|
-
}
|
|
4161
|
-
getMigrationName(filePath) {
|
|
4162
|
-
return path.basename(filePath).replace(".js", "");
|
|
4163
|
-
}
|
|
4164
|
-
path(p) {
|
|
4165
|
-
this.paths = Array.from(/* @__PURE__ */ new Set([...this.paths, p]));
|
|
4166
|
-
}
|
|
4167
|
-
getPaths() {
|
|
4168
|
-
return this.paths;
|
|
4169
|
-
}
|
|
4170
|
-
getConnection() {
|
|
4171
|
-
return this.connection;
|
|
4172
|
-
}
|
|
4173
|
-
resolveConnection(connection) {
|
|
4174
|
-
return this.resolver.connection(connection || this.connection);
|
|
4175
|
-
}
|
|
4176
|
-
getRepository() {
|
|
4177
|
-
return this.repository;
|
|
4178
|
-
}
|
|
4179
|
-
repositoryExists() {
|
|
4180
|
-
return this.repository.repositoryExists();
|
|
4181
|
-
}
|
|
4182
|
-
async hasRunAnyMigrations() {
|
|
4183
|
-
const ran = await this.repository.getRan();
|
|
4184
|
-
const exists = await this.repositoryExists();
|
|
4185
|
-
return exists && ran.length > 0;
|
|
4186
|
-
}
|
|
4187
|
-
deleteRepository() {
|
|
4188
|
-
this.repository.deleteRepository();
|
|
4189
|
-
}
|
|
4190
|
-
setOutput(output) {
|
|
4191
|
-
this.output = output;
|
|
4192
|
-
return this;
|
|
4193
|
-
}
|
|
4194
|
-
write(...args) {
|
|
4195
|
-
if (this.output) {
|
|
4196
|
-
console.log(...args);
|
|
4197
|
-
}
|
|
4198
|
-
}
|
|
4199
|
-
writeTwoColumns(name, ...args) {
|
|
4200
|
-
const value = args.join(" ");
|
|
4201
|
-
const regex = /\x1b\[\d+m/g;
|
|
4202
|
-
const width = Math.min(process.stdout.columns, 100);
|
|
4203
|
-
const dots = Math.max(width - name.replace(regex, "").length - value.replace(regex, "").length - 10, 0);
|
|
4204
|
-
this.write(name, color.gray(".".repeat(dots)), value);
|
|
4205
|
-
}
|
|
4206
|
-
async writeTask(description, task) {
|
|
4207
|
-
const startTime = process.hrtime();
|
|
4208
|
-
let result = false;
|
|
4209
|
-
try {
|
|
4210
|
-
result = await (task || (() => true))();
|
|
4211
|
-
} finally {
|
|
4212
|
-
const endTime = process.hrtime(startTime);
|
|
4213
|
-
const duration = (endTime[0] * 1e9 + endTime[1]) / 1e6;
|
|
4214
|
-
this.writeTwoColumns(
|
|
4215
|
-
color.green(description),
|
|
4216
|
-
color.gray(`${Math.floor(duration)}ms`),
|
|
4217
|
-
result !== false ? color.green("\u2714") : color.red("\u2718")
|
|
4218
|
-
);
|
|
4219
|
-
}
|
|
4220
|
-
}
|
|
4221
|
-
};
|
|
4222
|
-
var migrator_default = Migrator;
|
|
4223
|
-
|
|
4224
|
-
// src/cli/utils.ts
|
|
4225
|
-
import { access } from "fs/promises";
|
|
4226
|
-
import chalk from "chalk";
|
|
4227
|
-
import escalade from "escalade/sync";
|
|
4228
|
-
import path2 from "path";
|
|
4229
|
-
import resolveFrom from "resolve-from";
|
|
4230
|
-
var join = path2.join;
|
|
4231
|
-
var Utils = class {
|
|
4232
|
-
/**
|
|
4233
|
-
* Wraps text with chalk
|
|
4234
|
-
*
|
|
4235
|
-
* @param txt
|
|
4236
|
-
* @param color
|
|
4237
|
-
* @returns
|
|
4238
|
-
*/
|
|
4239
|
-
static textFormat(txt, color2) {
|
|
4240
|
-
return String(txt).split(":").map((e, i, a) => i == 0 && a.length > 1 ? color2(" " + e + ": ") : e).join("");
|
|
4241
|
-
}
|
|
4242
|
-
/**
|
|
4243
|
-
* Ouput formater object
|
|
4244
|
-
*
|
|
4245
|
-
* @returns
|
|
4246
|
-
*/
|
|
4247
|
-
static output() {
|
|
4248
|
-
return {
|
|
4249
|
-
success: (msg, exit = false) => {
|
|
4250
|
-
console.log(chalk.green("\u2713"), this.textFormat(msg, chalk.bgGreen), "\n");
|
|
4251
|
-
if (exit) process.exit(0);
|
|
4252
|
-
},
|
|
4253
|
-
info: (msg, exit = false) => {
|
|
4254
|
-
console.log(chalk.blue("\u2139"), this.textFormat(msg, chalk.bgBlue), "\n");
|
|
4255
|
-
if (exit) process.exit(0);
|
|
4256
|
-
},
|
|
4257
|
-
error: (msg, exit = true) => {
|
|
4258
|
-
if (msg instanceof Error) {
|
|
4259
|
-
if (msg.message) {
|
|
4260
|
-
console.error(chalk.red("\u2716"), this.textFormat(msg.message, chalk.bgRed));
|
|
4261
|
-
}
|
|
4262
|
-
console.error(chalk.red(`${msg.detail ? `${msg.detail}
|
|
4263
|
-
` : ""}${msg.stack}`), "\n");
|
|
4264
|
-
} else {
|
|
4265
|
-
console.error(chalk.red("\u2716"), this.textFormat(msg, chalk.bgRed), "\n");
|
|
4266
|
-
}
|
|
4267
|
-
if (exit) process.exit(1);
|
|
4268
|
-
},
|
|
4269
|
-
quiet: () => {
|
|
4270
|
-
process.exit(0);
|
|
4271
|
-
}
|
|
4272
|
-
};
|
|
4273
|
-
}
|
|
4274
|
-
static findModulePkg(moduleId, cwd) {
|
|
4275
|
-
const parts = moduleId.replace(/\\/g, "/").split("/");
|
|
4276
|
-
let packageName = "";
|
|
4277
|
-
if (parts.length > 0 && parts[0][0] === "@") {
|
|
4278
|
-
packageName += parts.shift() + "/";
|
|
4279
|
-
}
|
|
4280
|
-
packageName += parts.shift();
|
|
4281
|
-
const packageJson = path2.join(packageName, "package.json");
|
|
4282
|
-
const resolved = resolveFrom.silent(cwd ?? process.cwd(), packageJson);
|
|
4283
|
-
if (!resolved) {
|
|
4284
|
-
return;
|
|
4285
|
-
}
|
|
4286
|
-
return path2.join(path2.dirname(resolved), parts.join("/"));
|
|
4287
|
-
}
|
|
4288
|
-
static async getMigrationPaths(cwd, migrator, defaultPath, path3) {
|
|
4289
|
-
if (path3) {
|
|
4290
|
-
return [join(cwd, path3)];
|
|
4291
|
-
}
|
|
4292
|
-
return [
|
|
4293
|
-
...migrator.getPaths(),
|
|
4294
|
-
join(cwd, defaultPath)
|
|
4295
|
-
];
|
|
4296
|
-
}
|
|
4297
|
-
static twoColumnDetail(name, value) {
|
|
4298
|
-
const regex = /\x1b\[\d+m/g;
|
|
4299
|
-
const width = Math.min(process.stdout.columns, 100);
|
|
4300
|
-
const dots = Math.max(width - name.replace(regex, "").length - value.replace(regex, "").length - 10, 0);
|
|
4301
|
-
return console.log(name, chalk.gray(".".repeat(dots)), value);
|
|
4302
|
-
}
|
|
4303
|
-
/**
|
|
4304
|
-
* Check if file exists
|
|
4305
|
-
*
|
|
4306
|
-
* @param path
|
|
4307
|
-
* @returns
|
|
4308
|
-
*/
|
|
4309
|
-
static async fileExists(path3) {
|
|
4310
|
-
try {
|
|
4311
|
-
await access(path3);
|
|
4312
|
-
return true;
|
|
4313
|
-
} catch {
|
|
4314
|
-
return false;
|
|
4315
|
-
}
|
|
4316
|
-
}
|
|
4317
|
-
static findUpConfig(cwd, name, extensions) {
|
|
4318
|
-
return escalade(cwd, (_dir, names) => {
|
|
4319
|
-
for (const ext of extensions) {
|
|
4320
|
-
const filename = `${name}.${ext}`;
|
|
4321
|
-
if (names.includes(filename)) {
|
|
4322
|
-
return filename;
|
|
4323
|
-
}
|
|
4324
|
-
}
|
|
4325
|
-
return false;
|
|
4326
|
-
});
|
|
4327
|
-
}
|
|
4328
|
-
};
|
|
4329
|
-
|
|
4330
|
-
// src/migrate.ts
|
|
4331
|
-
var Migrate = class {
|
|
4332
|
-
constructor(basePath, customStubPath, callback) {
|
|
4333
|
-
this.basePath = basePath;
|
|
4334
|
-
this.customStubPath = customStubPath;
|
|
4335
|
-
this.callback = callback ?? ((_ = "") => {
|
|
4336
|
-
});
|
|
4337
|
-
}
|
|
4338
|
-
callback;
|
|
4339
|
-
/**
|
|
4340
|
-
* Runs all pending migrations
|
|
4341
|
-
*
|
|
4342
|
-
* @param config
|
|
4343
|
-
* @param options
|
|
4344
|
-
* @param destroyAll
|
|
4345
|
-
*/
|
|
4346
|
-
async run(config, options = {}, destroyAll = false) {
|
|
4347
|
-
const { arquebus: arquebus2, migrator } = await this.setupConnection(config);
|
|
4348
|
-
await this.prepareDatabase(migrator);
|
|
4349
|
-
const paths = await Utils.getMigrationPaths(
|
|
4350
|
-
this.basePath ?? process.cwd(),
|
|
4351
|
-
migrator,
|
|
4352
|
-
config.migrations.path,
|
|
4353
|
-
options.path
|
|
4354
|
-
);
|
|
4355
|
-
await migrator.setOutput(true).run(paths, {
|
|
4356
|
-
step: options.step,
|
|
4357
|
-
pretend: options.pretend
|
|
4358
|
-
});
|
|
4359
|
-
if (destroyAll) {
|
|
4360
|
-
await arquebus2.destroyAll();
|
|
4361
|
-
}
|
|
4362
|
-
}
|
|
4363
|
-
/**
|
|
4364
|
-
* Rollback the last migration
|
|
4365
|
-
*
|
|
4366
|
-
* @param config
|
|
4367
|
-
* @param options
|
|
4368
|
-
* @param destroyAll
|
|
4369
|
-
*/
|
|
4370
|
-
async rollback(config, options = {}, destroyAll = false) {
|
|
4371
|
-
const { arquebus: arquebus2, migrator } = await this.setupConnection(config);
|
|
4372
|
-
const paths = await Utils.getMigrationPaths(
|
|
4373
|
-
this.basePath ?? process.cwd(),
|
|
4374
|
-
migrator,
|
|
4375
|
-
config.migrations.path,
|
|
4376
|
-
options.path
|
|
4377
|
-
);
|
|
4378
|
-
await migrator.setOutput(true).rollback(paths, {
|
|
4379
|
-
step: options.step || 0,
|
|
4380
|
-
pretend: options.pretend,
|
|
4381
|
-
batch: options.batch || 0
|
|
4382
|
-
});
|
|
4383
|
-
if (destroyAll) {
|
|
4384
|
-
await arquebus2.destroyAll();
|
|
4385
|
-
}
|
|
4386
|
-
}
|
|
4387
|
-
/**
|
|
4388
|
-
* Prepares the database for migration
|
|
4389
|
-
*
|
|
4390
|
-
* @param migrator
|
|
4391
|
-
*/
|
|
4392
|
-
async prepareDatabase(migrator) {
|
|
4393
|
-
const exists = await migrator.repositoryExists();
|
|
4394
|
-
if (!exists) {
|
|
4395
|
-
this.callback("INFO: Preparing database.", "info");
|
|
4396
|
-
this.callback("INFO: Creating migration table...", "info");
|
|
4397
|
-
await migrator.repository.createRepository();
|
|
4398
|
-
this.callback("SUCCESS: Migration table created successfully.", "success");
|
|
4399
|
-
}
|
|
4400
|
-
}
|
|
4401
|
-
/**
|
|
4402
|
-
* Check the status of available migrations
|
|
4403
|
-
*
|
|
4404
|
-
* @param config
|
|
4405
|
-
* @param options
|
|
4406
|
-
* @param destroyAll
|
|
4407
|
-
* @returns
|
|
4408
|
-
*/
|
|
4409
|
-
async status(config, options = {}, destroyAll = false) {
|
|
4410
|
-
const { arquebus: arquebus2, migrator } = await this.setupConnection(config);
|
|
4411
|
-
const getAllMigrationFiles = async () => {
|
|
4412
|
-
return await migrator.getMigrationFiles(
|
|
4413
|
-
await Utils.getMigrationPaths(
|
|
4414
|
-
this.basePath ?? process.cwd(),
|
|
4415
|
-
migrator,
|
|
4416
|
-
config.migrations.path,
|
|
4417
|
-
options.path
|
|
4418
|
-
)
|
|
4419
|
-
);
|
|
4420
|
-
};
|
|
4421
|
-
async function getStatusFor(ran2, batches2) {
|
|
4422
|
-
const files = await getAllMigrationFiles();
|
|
4423
|
-
return Object.values(files).map((migration) => {
|
|
4424
|
-
const migrationName = migrator.getMigrationName(migration);
|
|
4425
|
-
return {
|
|
4426
|
-
name: migrationName,
|
|
4427
|
-
ran: ran2.includes(migrationName),
|
|
4428
|
-
batch: ran2.includes(migrationName) ? batches2[migrationName] : null
|
|
4429
|
-
};
|
|
4430
|
-
});
|
|
4431
|
-
}
|
|
4432
|
-
const exists = await migrator.repositoryExists();
|
|
4433
|
-
if (!exists) {
|
|
4434
|
-
this.callback("ERROR: Migration table does not exist.", "error");
|
|
4435
|
-
}
|
|
4436
|
-
const ran = await migrator.repository.getRan();
|
|
4437
|
-
const batches = await migrator.getRepository().getMigrationBatches();
|
|
4438
|
-
const migrations = await getStatusFor(ran, batches);
|
|
4439
|
-
if (destroyAll) {
|
|
4440
|
-
await arquebus2.destroyAll();
|
|
4441
|
-
}
|
|
4442
|
-
return migrations;
|
|
4443
|
-
}
|
|
4444
|
-
/**
|
|
4445
|
-
* Setup the database connection
|
|
4446
|
-
*
|
|
4447
|
-
* @param config
|
|
4448
|
-
* @returns
|
|
4449
|
-
*/
|
|
4450
|
-
async setupConnection(config) {
|
|
4451
|
-
const table = config?.migrations?.table || "migrations";
|
|
4452
|
-
arquebus_default.addConnection(config, "default");
|
|
4453
|
-
Object.entries(config.connections || {}).forEach(([name, connection]) => {
|
|
4454
|
-
arquebus_default.addConnection(connection, name);
|
|
4455
|
-
});
|
|
4456
|
-
const repository = new migration_repository_default(arquebus_default, table);
|
|
4457
|
-
const migrator = new migrator_default(repository, arquebus_default);
|
|
4458
|
-
return { arquebus: arquebus_default, migrator };
|
|
4459
|
-
}
|
|
4460
|
-
};
|
|
4461
|
-
|
|
4462
|
-
// src/migrations/migration.ts
|
|
4463
|
-
var Inference3 = class {
|
|
4464
|
-
};
|
|
4465
|
-
var Migration = class extends Inference3 {
|
|
4466
|
-
connection;
|
|
4467
|
-
withinTransaction = true;
|
|
4468
|
-
getConnection() {
|
|
4469
|
-
return this.connection;
|
|
4470
|
-
}
|
|
4471
|
-
};
|
|
4472
|
-
var migration_default = Migration;
|
|
4473
|
-
|
|
4474
|
-
// src/pivot.ts
|
|
4475
|
-
var pivot_default = Pivot;
|
|
4476
|
-
|
|
4477
|
-
// src/soft-deleting-scope.ts
|
|
4478
|
-
var hasJoins = (statements) => {
|
|
4479
|
-
for (const statement of statements) {
|
|
4480
|
-
if (statement?.grouping === "join") {
|
|
4481
|
-
return true;
|
|
4482
|
-
}
|
|
4483
|
-
}
|
|
4484
|
-
return false;
|
|
4485
|
-
};
|
|
4486
|
-
var SoftDeletingScope = class extends scope_default {
|
|
4487
|
-
extensions = [
|
|
4488
|
-
"Restore",
|
|
4489
|
-
"RestoreOrCreate",
|
|
4490
|
-
"CreateOrRestore",
|
|
4491
|
-
"WithTrashed",
|
|
4492
|
-
"WithoutTrashed",
|
|
4493
|
-
"OnlyTrashed"
|
|
4494
|
-
];
|
|
4495
|
-
apply(builder, model) {
|
|
4496
|
-
builder.whereNull(model.getQualifiedDeletedAtColumn());
|
|
4497
|
-
}
|
|
4498
|
-
extend(builder) {
|
|
4499
|
-
for (const extension of this.extensions) {
|
|
4500
|
-
this[`add${extension}`](builder);
|
|
4501
|
-
}
|
|
4502
|
-
builder.onDelete(async (builder2) => {
|
|
4503
|
-
const column = this.getDeletedAtColumn(builder2);
|
|
4504
|
-
return await builder2.update({
|
|
4505
|
-
[column]: builder2.getModel().freshTimestampString()
|
|
4506
|
-
});
|
|
4507
|
-
});
|
|
4508
|
-
}
|
|
4509
|
-
getDeletedAtColumn(builder) {
|
|
4510
|
-
if (hasJoins(builder.getQuery()._statements)) {
|
|
4511
|
-
return builder.getModel().getQualifiedDeletedAtColumn();
|
|
4512
|
-
}
|
|
4513
|
-
return builder.getModel().getDeletedAtColumn();
|
|
4514
|
-
}
|
|
4515
|
-
addRestore(builder) {
|
|
4516
|
-
builder.macro("restore", (builder2) => {
|
|
4517
|
-
builder2.withTrashed();
|
|
4518
|
-
return builder2.update({
|
|
4519
|
-
[builder2.getModel().getDeletedAtColumn()]: null
|
|
4520
|
-
});
|
|
4521
|
-
});
|
|
4522
|
-
}
|
|
4523
|
-
addRestoreOrCreate(builder) {
|
|
4524
|
-
builder.macro("restoreOrCreate", async (builder2, attributes = {}, values = {}) => {
|
|
4525
|
-
builder2.withTrashed();
|
|
4526
|
-
return tap(await builder2.firstOrCreate(attributes, values), async (instance) => {
|
|
4527
|
-
await instance.restore();
|
|
4528
|
-
});
|
|
4529
|
-
});
|
|
4530
|
-
}
|
|
4531
|
-
addCreateOrRestore(builder) {
|
|
4532
|
-
builder.macro("createOrRestore", async (builder2, attributes = {}, values = {}) => {
|
|
4533
|
-
builder2.withTrashed();
|
|
4534
|
-
return tap(await builder2.createOrFirst(attributes, values), async (instance) => {
|
|
4535
|
-
await instance.restore();
|
|
4536
|
-
});
|
|
4537
|
-
});
|
|
4538
|
-
}
|
|
4539
|
-
addWithTrashed(builder) {
|
|
4540
|
-
builder.macro("withTrashed", (builder2, withTrashed = true) => {
|
|
4541
|
-
if (!withTrashed) {
|
|
4542
|
-
return builder2.withoutTrashed();
|
|
4543
|
-
}
|
|
4544
|
-
return builder2.withoutGlobalScope(this);
|
|
4545
|
-
});
|
|
4546
|
-
}
|
|
4547
|
-
addWithoutTrashed(builder) {
|
|
4548
|
-
builder.macro("withoutTrashed", (builder2) => {
|
|
4549
|
-
const model = builder2.getModel();
|
|
4550
|
-
builder2.withoutGlobalScope(this).whereNull(model.getQualifiedDeletedAtColumn());
|
|
4551
|
-
return builder2;
|
|
4552
|
-
});
|
|
4553
|
-
}
|
|
4554
|
-
addOnlyTrashed(builder) {
|
|
4555
|
-
builder.macro("onlyTrashed", (builder2) => {
|
|
4556
|
-
const model = builder2.getModel();
|
|
4557
|
-
builder2.withoutGlobalScope(this).whereNotNull(model.getQualifiedDeletedAtColumn());
|
|
4558
|
-
return builder2;
|
|
4559
|
-
});
|
|
4560
|
-
}
|
|
4561
|
-
};
|
|
4562
|
-
var soft_deleting_scope_default = SoftDeletingScope;
|
|
4563
|
-
|
|
4564
|
-
// src/soft-deletes.ts
|
|
4565
|
-
import { isNullish } from "radashi";
|
|
4566
|
-
var softDeletes = (Model2) => {
|
|
4567
|
-
return class extends Model2 {
|
|
4568
|
-
forceDeleting = false;
|
|
4569
|
-
static bootSoftDeletes() {
|
|
4570
|
-
this.addGlobalScope(new soft_deleting_scope_default());
|
|
4571
|
-
}
|
|
4572
|
-
initialize() {
|
|
4573
|
-
super.initialize();
|
|
4574
|
-
this.constructor.bootSoftDeletes();
|
|
4575
|
-
this.addPluginInitializer("initializeSoftDeletes");
|
|
4576
|
-
}
|
|
4577
|
-
initializeSoftDeletes() {
|
|
4578
|
-
if (this.casts[this.getDeletedAtColumn()] === void 0) {
|
|
4579
|
-
this.casts[this.getDeletedAtColumn()] = "datetime";
|
|
4580
|
-
}
|
|
4581
|
-
}
|
|
4582
|
-
async forceDelete() {
|
|
4583
|
-
if (this.execHooks("forceDeleting") === false) {
|
|
4584
|
-
return false;
|
|
4585
|
-
}
|
|
4586
|
-
this.forceDeleting = true;
|
|
4587
|
-
return tap(await this.delete(), (deleted) => {
|
|
4588
|
-
this.forceDeleting = false;
|
|
4589
|
-
if (deleted) {
|
|
4590
|
-
this.execHooks("forceDeleted", false);
|
|
4591
|
-
}
|
|
4592
|
-
});
|
|
4593
|
-
}
|
|
4594
|
-
forceDeleteQuietly() {
|
|
4595
|
-
return this.withoutEvents(() => this.forceDelete());
|
|
4596
|
-
}
|
|
4597
|
-
async performDeleteOnModel(options = {}) {
|
|
4598
|
-
if (this.forceDeleting) {
|
|
4599
|
-
return tap(await this.setKeysForSaveQuery(this.newModelQuery()).forceDelete(), () => {
|
|
4600
|
-
this.exists = false;
|
|
4601
|
-
});
|
|
4602
|
-
}
|
|
4603
|
-
return await this.runSoftDelete(options);
|
|
4604
|
-
}
|
|
4605
|
-
async runSoftDelete(options = {}) {
|
|
4606
|
-
const query = this.setKeysForSaveQuery(this.newModelQuery());
|
|
4607
|
-
const time = this.freshTimestamp();
|
|
4608
|
-
const columns = {
|
|
4609
|
-
[this.getDeletedAtColumn()]: this.fromDateTime(time)
|
|
4610
|
-
};
|
|
4611
|
-
this[this.getDeletedAtColumn()] = time;
|
|
4612
|
-
if (this.usesTimestamps() && this.getUpdatedAtColumn()) {
|
|
4613
|
-
this[this.getUpdatedAtColumn()] = time;
|
|
4614
|
-
columns[this.getUpdatedAtColumn()] = this.fromDateTime(time);
|
|
4615
|
-
}
|
|
4616
|
-
await query.update(columns);
|
|
4617
|
-
this.syncOriginalAttributes(Object.keys(columns));
|
|
4618
|
-
this.execHooks("trashed", options);
|
|
4619
|
-
}
|
|
4620
|
-
async restore(options = {}) {
|
|
4621
|
-
if (this.execHooks("restoring", options) === false) {
|
|
4622
|
-
return false;
|
|
4623
|
-
}
|
|
4624
|
-
this[this.getDeletedAtColumn()] = null;
|
|
4625
|
-
this.exists = true;
|
|
4626
|
-
const result = await this.save();
|
|
4627
|
-
this.execHooks("restored", options);
|
|
4628
|
-
return result;
|
|
4629
|
-
}
|
|
4630
|
-
restoreQuietly() {
|
|
4631
|
-
return this.withoutEvents(() => this.restore());
|
|
4632
|
-
}
|
|
4633
|
-
trashed() {
|
|
4634
|
-
return !isNullish(this[this.getDeletedAtColumn()]);
|
|
4635
|
-
}
|
|
4636
|
-
static softDeleted(callback) {
|
|
4637
|
-
this.addHook("trashed", callback);
|
|
4638
|
-
}
|
|
4639
|
-
static restoring(callback) {
|
|
4640
|
-
this.addHook("restoring", callback);
|
|
4641
|
-
}
|
|
4642
|
-
static restored(callback) {
|
|
4643
|
-
this.addHook("restored", callback);
|
|
4644
|
-
}
|
|
4645
|
-
static forceDeleting(callback) {
|
|
4646
|
-
this.addHook("forceDeleting", callback);
|
|
4647
|
-
}
|
|
4648
|
-
static forceDeleted(callback) {
|
|
4649
|
-
this.addHook("forceDeleted", callback);
|
|
4650
|
-
}
|
|
4651
|
-
isForceDeleting() {
|
|
4652
|
-
return this.forceDeleting;
|
|
4653
|
-
}
|
|
4654
|
-
getDeletedAtColumn() {
|
|
4655
|
-
return this.constructor.DELETED_AT || "deleted_at";
|
|
4656
|
-
}
|
|
4657
|
-
getQualifiedDeletedAtColumn() {
|
|
4658
|
-
return this.qualifyColumn(this.getDeletedAtColumn());
|
|
4659
|
-
}
|
|
4660
|
-
};
|
|
4661
|
-
};
|
|
4662
|
-
var soft_deletes_default = softDeletes;
|
|
4663
|
-
|
|
4664
|
-
// src/index.ts
|
|
4665
|
-
var make = (model, data, options = {}) => {
|
|
4666
|
-
const { paginated } = options;
|
|
4667
|
-
if (paginated) {
|
|
4668
|
-
return new paginator_default(
|
|
4669
|
-
data.data.map((item) => model.make(item)),
|
|
4670
|
-
data.total,
|
|
4671
|
-
data.per_page,
|
|
4672
|
-
data.current_page
|
|
4673
|
-
);
|
|
4674
|
-
}
|
|
4675
|
-
if (Array.isArray(data)) {
|
|
4676
|
-
return new collection_default(data.map((item) => model.make(item)));
|
|
4677
|
-
}
|
|
4678
|
-
return model.make(data);
|
|
4679
|
-
};
|
|
4680
|
-
var makeCollection = (model, data) => new collection_default(data.map((item) => model.make(item)));
|
|
4681
|
-
var makePaginator = (model, data) => new paginator_default(
|
|
4682
|
-
data.data.map((item) => model.make(item)),
|
|
4683
|
-
data.total,
|
|
4684
|
-
data.per_page,
|
|
4685
|
-
data.current_page
|
|
4686
|
-
);
|
|
4687
|
-
export {
|
|
4688
|
-
attribute_default as Attribute,
|
|
4689
|
-
builder_default as Builder,
|
|
4690
|
-
casts_attributes_default as CastsAttributes,
|
|
4691
|
-
collection_default as Collection,
|
|
4692
|
-
has_unique_ids_default as HasUniqueIds,
|
|
4693
|
-
InvalidArgumentError,
|
|
4694
|
-
Migrate,
|
|
4695
|
-
migration_default as Migration,
|
|
4696
|
-
model_default as Model,
|
|
4697
|
-
ModelNotFoundError,
|
|
4698
|
-
paginator_default as Paginator,
|
|
4699
|
-
pivot_default as Pivot,
|
|
4700
|
-
query_builder_default as QueryBuilder,
|
|
4701
|
-
RelationNotFoundError,
|
|
4702
|
-
scope_default as Scope,
|
|
4703
|
-
soft_deletes_default as SoftDeletes,
|
|
4704
|
-
arquebus_default as arquebus,
|
|
4705
|
-
compose,
|
|
4706
|
-
defineConfig,
|
|
4707
|
-
flattenDeep,
|
|
4708
|
-
getAttrMethod,
|
|
4709
|
-
getAttrName,
|
|
4710
|
-
getGetterMethod,
|
|
4711
|
-
getRelationMethod,
|
|
4712
|
-
getRelationName,
|
|
4713
|
-
getScopeMethod,
|
|
4714
|
-
getScopeName,
|
|
4715
|
-
getSetterMethod,
|
|
4716
|
-
kebabCase,
|
|
4717
|
-
make,
|
|
4718
|
-
makeCollection,
|
|
4719
|
-
makePaginator,
|
|
4720
|
-
now,
|
|
4721
|
-
snakeCase,
|
|
4722
|
-
tap
|
|
4723
|
-
};
|
|
1
|
+
import{trim as t,assign as e,diff as s,pick as i,omit as r,isEmpty as n,isArray as a,isEqual as o,isString as h,snake as l,flat as c,set as u,get as g,camel as d,dash as y,isNullish as m}from"radashi";import p from"dayjs/plugin/advancedFormat.js";import f from"dayjs";import w,{collect as b,Collection as C}from"collect.js";import v from"knex";import K from"pluralize";import P from"chalk";import N,{access as A}from"fs/promises";import D from"path";import x from"escalade/sync";import T from"resolve-from";var R=Object.defineProperty,S=class t{get;set;withCaching=!1;withObjectCaching=!0;constructor({get:t=null,set:e=null}){this.get=t,this.set=e}static make({get:e=null,set:s=null}){return new t({get:e,set:s})}static get(e){return new t({get:e})}static set(e){return new t({set:e})}withoutObjectCaching(){return this.withObjectCaching=!1,this}shouldCache(){return this.withCaching=!0,this}},q=class extends Error{constructor(t,e){super(t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.message=t}},M=class extends q{model;ids=[];constructor(){super("")}setModel(t,e=[]){return this.model=t,this.ids=a(e)?e:[e],this.message=`No query results for model [${t}]`,this.ids.length>0?this.message+=" "+this.ids.join(", "):this.message+=".",this}getModel(){return this.model}getIds(){return this.ids}},k=class extends q{},I=class extends q{},Q={};function E(t,...e){return e.reduce((t,e)=>"function"==typeof e&&e.prototype?class extends t{constructor(...t){super(...t),Object.getOwnPropertyNames(e.prototype).forEach(t=>{"constructor"!==t&&Object.defineProperty(this,t,Object.getOwnPropertyDescriptor(e.prototype,t))})}}:"function"==typeof e?e(t):t,t)}((t,e)=>{for(var s in e)R(t,s,{get:e[s],enumerable:!0})})(Q,{compose:()=>E}),f.extend(p);var _=(t="YYYY-MM-DD HH:mm:ss")=>f().format(t),F=t=>l(t.substring(8)),O=t=>l(t.substring(5)),W=t=>d(`relation_${t}`),B=t=>d(`scope_${t}`),H=t=>d(`attribute_${t}`),j=t=>d(`get_${t}_attribute`),L=t=>d(`set_${t}_attribute`),U=t=>t.substring(3,t.length-9).toLowerCase(),$=(t,e)=>{const s=e(t);return s instanceof Promise?s.then(()=>t):t},{compose:J}=Q,z=t=>Array.isArray(t)?t.reduce((t,e)=>t.concat(z(e)),[]):[t],G=e=>t(y(e.replace(/[^a-zA-Z0-9_-]/g,"-")),"_-"),Y=e=>t(l(e.replace(/[^a-zA-Z0-9_-]/g,"-")),"_-"),V=t=>t,Z=class{query;parent;related;eagerKeysWereEmpty=!1;static constraints=!0;static selfJoinCount=0;constructor(t,e){this.query=t,this.parent=e,this.related=this.query.model}static extend(t){for(const e in t)this.prototype[e]=t[e]}static noConstraints(t){const e=this.constraints;this.constraints=!1;try{return t()}finally{this.constraints=e}}asProxy(){return new Proxy(this,{get:function(t,e){return void 0!==t[e]?t[e]:"string"==typeof e&&"function"==typeof t.query[e]?(...s)=>(t.query[e](...s),t.asProxy()):void 0}})}getRelated(){return this.related}getKeys(t,e){return t.map(t=>e?t.attributes[e]:t.getKey()).sort()}getRelationQuery(){return this.query}whereInEager(t,e,s,i=null){(i||this.query)[t](e,s),0===s.length&&(this.eagerKeysWereEmpty=!0)}whereInMethod(t,e){return"whereIn"}getEager(){return this.eagerKeysWereEmpty?this.query.getModel().newCollection():this.get()}async get(t=["*"]){return await this.query.get(t)}async first(t=["*"]){return await this.query.first(t)}async paginate(...t){return await this.query.paginate(...t)}async count(...t){return await this.query.clearSelect().count(...t)}toSql(){return this.query.toSql()}addConstraints(){}getRelationCountHash(t=!0){return"arquebus_reserved_"+(t?this.constructor.selfJoinCount++:this.constructor.selfJoinCount)}getRelationExistenceQuery(t,e,s=["*"]){return t.select(s).whereColumn(this.getQualifiedParentKeyName(),"=",this.getExistenceCompareKey())}getRelationExistenceCountQuery(t,e){const s=this.related.getConnection();return this.getRelationExistenceQuery(t,e,s.raw("count(*)"))}getQualifiedParentKeyName(){return this.parent.getQualifiedKeyName()}getExistenceCompareKey(){return this.getQualifiedForeignKeyName?.()}},X=t=>class extends t{_withDefault;withDefault(t=!0){return this._withDefault=t,this}getDefaultFor(t){if(!this._withDefault)return null;const e=this.newRelatedInstanceFor(t);if("function"==typeof this._withDefault)return this._withDefault(e,t)||e;if("object"==typeof this._withDefault)for(const t in this._withDefault)e.setAttribute(t,this._withDefault[t]);return e}},tt=class extends(J(Z,X)){foreignKey;ownerKey;child;relationName;constructor(t,e,s,i,r){return super(t,e),this.foreignKey=s,this.ownerKey=i,this.child=e,this.relationName=r,this.addConstraints(),this.asProxy()}async getResults(){if(null===this.child[this.foreignKey])return this.getDefaultFor(this.parent);return await this.query.first()||this.getDefaultFor(this.parent)}match(t,e,s){const i=this.foreignKey,r=this.ownerKey,n={};return e.map(t=>{const e=t.attributes[r];n[e]=t}),t.map(t=>{const e=t[i];void 0!==n[e]&&t.setRelation(s,n[e])}),t}getQualifiedForeignKeyName(){return this.child.qualifyColumn(this.foreignKey)}getRelationExistenceQuery(t,e,s=["*"]){return e.getQuery()._single.table===t.getQuery()._single.table?this.getRelationExistenceQueryForSelfRelation(t,e,s):t.select(s).whereColumn(this.getQualifiedForeignKeyName(),"=",t.qualifyColumn(this.ownerKey))}getRelationExistenceQueryForSelfRelation(t,e,s=["*"]){const i=this.getRelationCountHash();return t.select(s).from(t.getModel().getTable()+" as "+i),t.getModel().setTable(i),t.whereColumn(`${i}.${this.ownerKey}`,"=",this.getQualifiedForeignKeyName())}initRelation(t,e){return t.forEach(t=>{t.setRelation(e,this.getDefaultFor(t))}),t}addEagerConstraints(t){const e=`${this.related.getTable()}.${this.ownerKey}`;this.query.whereIn(e,this.getEagerModelKeys(t))}getEagerModelKeys(t){const e=[];return t.forEach(t=>{const s=t[this.foreignKey];null!=s&&e.push(s)}),e.sort(),[...new Set(e)]}associate(t){const e=t instanceof vt?t.attributes[this.ownerKey]:t;return this.child[this.foreignKey]=e,t instanceof vt?this.child.setRelation(this.relationName,t):this.child.unsetRelation(this.relationName),this.child}dissociate(){return this.child[this.foreignKey]=null,this.child.setRelation(this.relationName,null)}addConstraints(){if(this.constructor.constraints){const t=this.related.getTable();this.query.where(`${t}.${this.ownerKey}`,"=",this.child[this.foreignKey])}}newRelatedInstanceFor(t){return this.related.newInstance()}},et=class t{constructor(){if(this.constructor===t)throw new Error("CastsAttributes cannot be instantiated")}static get(t,e,s,i){throw new Error("get not implemented")}static set(t,e,s,i){throw new Error("set not implemented")}},st=t=>class extends t{static castTypeCache={};attributes={};original={};casts={};changes={};appends=[];setAppends(t){return this.appends=t,this}append(...t){const e=z(t);return this.appends=[...this.appends,...e],this}normalizeCastClassResponse(t,e){return"Object"===e?.constructor?.name?e:{[t]:e}}syncOriginal(){return this.original=this.getAttributes(),this}syncChanges(){return this.changes=this.getDirty(),this}syncOriginalAttribute(t){this.syncOriginalAttributes(t)}syncOriginalAttributes(...t){t=z(t);const e=this.getAttributes();for(const s of t)this.original[s]=e[s];return this}isDirty(...t){const e=this.getDirty();if(0===(t=z(t)).length)return Object.keys(e).length>0;for(const s of t)if(s in e)return!0;return!1}getDirty(){const t={},e=this.getAttributes();for(const s in e){const i=e[s];this.originalIsEquivalent(s)||(t[s]=i)}return t}originalIsEquivalent(t){if(void 0===this.original[t])return!1;return this.attributes[t]===this.original[t]}setAttributes(t){this.attributes={...t}}setRawAttributes(t,e=!1){return this.attributes=t,e&&this.syncOriginal(),this}getAttributes(){return{...this.attributes}}setAttribute(t,e){const s=L(t);if("function"==typeof this[s])return this[s](e),this;const i=H(t);if("function"==typeof this[i]){const s=this[i]().set||(e=>{this.attributes[t]=e});return this.attributes={...this.attributes,...this.normalizeCastClassResponse(t,s(e,this.attributes))},this}const r=this.getCasts()[t];return this.isCustomCast(r)&&"string"!=typeof r&&(e=r.set(this,t,e,this.attributes)??""),"json"===r&&(e=JSON.stringify(e)),"collection"===r&&(e=JSON.stringify(e)),null!==e&&this.isDateAttribute(t)&&(e=this.fromDateTime(e)),this.attributes[t]=e,this}getAttribute(t){if(!t)return;const e=j(t);if("function"==typeof this[e])return this[e](this.attributes[t],this.attributes);const s=H(t);if("function"==typeof this[s]){return this[s]().get(this.attributes[t],this.attributes)}return t in this.attributes?this.hasCast(t)?this.castAttribute(t,this.attributes[t]):this.getDates().includes(t)?this.asDateTime(this.attributes[t]):this.attributes[t]:t in this.relations?this.relations[t]:void 0}castAttribute(t,e){const s=this.getCastType(t);if(!s)return e;if(null===e)return e;switch(s){case"int":case"integer":return parseInt(e);case"real":case"float":case"double":return parseFloat(e);case"decimal":return this.asDecimal(e,s.split(":")[1]);case"string":return String(e);case"bool":case"boolean":return Boolean(e);case"object":case"json":try{return JSON.parse(e)}catch{return null}case"collection":try{return w(JSON.parse(e))}catch{return w([])}case"date":return this.asDate(e);case"datetime":case"custom_datetime":return this.asDateTime(e);case"timestamp":return this.asTimestamp(e)}return this.isCustomCast(s)?s.get(this,t,e,this.attributes):e}attributesToData(){let t={...this.attributes};for(const e in t)this.hidden.includes(e)&&(t=r(t,[e])),this.visible.length>0&&!1===this.visible.includes(e)&&(t=r(t,[e]));for(const e of this.getDates())void 0!==t[e]&&(t[e]=this.serializeDate(this.asDateTime(t[e])));const e=this.getCasts();for(const s in e){const i=e[s];s in t!=!1&&(t[s]=this.castAttribute(s,t[s]),s in t&&["date","datetime"].includes(String(i))&&(t[s]=this.serializeDate(t[s])),s in t&&this.isCustomDateTimeCast(i)&&(t[s]=f(t[s]).format(String(i).split(":")[1])))}for(const e of this.appends)t[e]=this.mutateAttribute(e,null);return t}mutateAttribute(t,e){if("function"==typeof this[j(t)])return this[j(t)](e);if("function"==typeof this[H(t)]){return this[H(t)]().get(t,this.attributes)}return t in this?this[t]:e}mutateAttributeForArray(t,e){}isDateAttribute(t){return this.getDates().includes(t)||this.isDateCastable(t)}serializeDate(t){return t?f(t).toISOString():null}getDates(){return this.usesTimestamps()?[this.getCreatedAtColumn(),this.getUpdatedAtColumn()]:[]}getCasts(){return this.getIncrementing()?{[this.getKeyName()]:this.getKeyType(),...this.casts}:this.casts}getCastType(t){const e=this.getCasts()[t];let s,i;return"string"==typeof e?s=e:new e instanceof et&&(s=e.name),s&&void 0!==this.getConstructor().castTypeCache[s]?this.getConstructor().castTypeCache[s]:(i=this.isCustomDateTimeCast(e)?"custom_datetime":this.isDecimalCast(e)?"decimal":this.isCustomCast(e)?e:String(e).toLocaleLowerCase().trim(),this.getConstructor()[s]=i)}hasCast(t,e=[]){return t in this.casts&&(!((e=c(e)).length>0)||e.includes(this.getCastType(t)))}withDayjs(t){return f(t)}isCustomCast(t){return"function"==typeof t&&new t instanceof et}isCustomDateTimeCast(t){return"string"==typeof t&&(t.startsWith("date:")||t.startsWith("datetime:"))}isDecimalCast(t){return"string"==typeof t&&t.startsWith("decimal:")}isDateCastable(t){return this.hasCast(t,["date","datetime"])}fromDateTime(t){return f(this.asDateTime(t)).format(this.getDateFormat())}getDateFormat(){return this.dateFormat||"YYYY-MM-DD HH:mm:ss"}asDecimal(t,e){return parseFloat(t).toFixed(e)}asDateTime(t){return null===t?null:t instanceof Date?t:"number"==typeof t?new Date(1e3*t):new Date(t)}asDate(t){const e=this.asDateTime(t);return f(e).startOf("day").toDate()}},it=class t{constructor(){if(this.constructor===t)throw new Error("Scope cannot be instantiated")}apply(t,e){throw new Error("apply not implemented")}},rt=t=>class extends t{static globalScopes;static addGlobalScope(t,e=null){if("string"==typeof t&&e instanceof it)return this.globalScopes=u(this.globalScopes??{},this.name+"."+t,e),e;if(t instanceof it)return this.globalScopes=u(this.globalScopes??{},this.name+"."+t.constructor.name,t),t;throw new I("Global scope must be an instance of Scope.")}static hasGlobalScope(t){return null!==this.getGlobalScope(t)}static getGlobalScope(t){return g(this.globalScopes,"string"==typeof t?this.name+"."+t:this.name+"."+t.constructor.name)}static getAllGlobalScopes(){return this.globalScopes}static setAllGlobalScopes(t){this.globalScopes=t}getGlobalScopes(){return g(this.constructor.globalScopes,this.constructor.name,{})}},nt=class{hooks={creating:[],created:[],updating:[],updated:[],saving:[],saved:[],deleting:[],deleted:[],restoring:[],restored:[],trashed:[],forceDeleting:[],forceDeleted:[]};add(t,e){this.hooks[t].push(e)}async exec(t,e){const s=this.hooks[t]??[];for(const t of s)await t(...e);return!0}},at=t=>class extends t{static hooks=null;static addHook(t,e){this.hooks instanceof nt==!1&&(this.hooks=new nt),this.hooks.add(t,e)}static creating(t){this.addHook("creating",t)}static created(t){this.addHook("created",t)}static updating(t){this.addHook("updating",t)}static updated(t){this.addHook("updated",t)}static saving(t){this.addHook("saving",t)}static saved(t){this.addHook("saved",t)}static deleting(t){this.addHook("deleting",t)}static deleted(t){this.addHook("deleted",t)}static restoring(t){this.addHook("restoring",t)}static restored(t){this.addHook("restored",t)}static trashed(t){this.addHook("trashed",t)}static forceDeleted(t){this.addHook("forceDeleted",t)}async execHooks(t,e){if(this.constructor.hooks instanceof nt!=!1)return await this.constructor.hooks.exec(t,[this,e])}},ot=t=>class extends t{getRelationValue(t,e,s){const i=t[e];return"one"===s?i[0]:new Nt(i)}matchOneOrMany(t,e,s,i){const r=this.buildDictionary(e);return t.map(t=>{const e=t.attributes[this.localKey];void 0!==r[e]&&t.setRelation(s,this.getRelationValue(r,e,i))}),t}buildDictionary(t){const e=this.getForeignKeyName();return w(t).mapToDictionary(t=>[t[e],t]).all()}async save(t){return this.setForeignAttributesForCreate(t),!!await t.save()&&t}async saveMany(t){return await Promise.all(t.map(async t=>{await this.save(t)})),t instanceof Nt?t:new Nt(t)}async create(t={}){return await $(this.related.constructor.init(t),async t=>{this.setForeignAttributesForCreate(t),await t.save()})}async createMany(t){const e=await Promise.all(t.map(async t=>await this.create(t)));return e instanceof Nt?e:new Nt(e)}setForeignAttributesForCreate(t){t[this.getForeignKeyName()]=this.getParentKey()}getForeignKeyName(){const t=this.getQualifiedForeignKeyName().split(".");return t[t.length-1]}getParentKey(){return this.parent.attributes[this.localKey]}getQualifiedForeignKeyName(){return this.foreignKey}getExistenceCompareKey(){return this.getQualifiedForeignKeyName()}addConstraints(){if(this.constructor.constraints){const t=this.getRelationQuery();t.where(this.foreignKey,"=",this.getParentKey()),t.whereNotNull(this.foreignKey)}}},ht=class extends(J(Z,ot)){foreignKey;localKey;constructor(t,e,s,i){return super(t,e),this.foreignKey=s,this.localKey=i,this.addConstraints(),this.asProxy()}initRelation(t,e){return t.map(t=>{t.setRelation(e,new Nt([]))}),t}async getResults(){return null!==this.getParentKey()?await this.query.get():new Nt([])}getForeignKeyName(){const t=this.foreignKey?.split(".");return t?.pop()}buildDictionary(t){const e=this.getForeignKeyName();return b(t).mapToDictionary(t=>[t[e],t]).all()}match(t,e,s){return this.matchOneOrMany(t,e,s,"many")}addEagerConstraints(t){this.query.whereIn(this.foreignKey,this.getKeys(t,this.localKey))}},lt=class extends(J(Z,ot,X)){foreignKey;localKey;constructor(t,e,s,i){return super(t,e),this.foreignKey=s,this.localKey=i,this.addConstraints(),this.asProxy()}initRelation(t,e){return t.map(t=>{t.setRelation(e,this.getDefaultFor(t))}),t}matchOne(t,e,s){return this.matchOneOrMany(t,e,s,"one")}getForeignKeyName(){const t=this.foreignKey?.split(".");return t?.pop()}async getResults(){if(null===this.getParentKey())return this.getDefaultFor(this.parent);return await this.query.first()||this.getDefaultFor(this.parent)}match(t,e,s){return this.matchOneOrMany(t,e,s,"one")}addEagerConstraints(t){this.query.whereIn(this.foreignKey,this.getKeys(t,this.localKey))}newRelatedInstanceFor(t){return this.related.newInstance().setAttribute(this.getForeignKeyName(),t[this.localKey])}},ct=class extends Z{throughParent;farParent;firstKey;secondKey;localKey;secondLocalKey;constructor(t,e,s,i,r,n,a){return super(t,s),this.localKey=n,this.firstKey=i,this.secondKey=r,this.farParent=e,this.throughParent=s,this.secondLocalKey=a,this.asProxy()}addConstraints(){const t=this.farParent[this.localKey];this.performJoin(),this.constructor.constraints&&this.query.where(this.getQualifiedFirstKeyName(),"=",t)}performJoin(t=null){t=t||this.query;const e=this.getQualifiedFarKeyName();t.join(this.throughParent.getTable(),this.getQualifiedParentKeyName(),"=",e),this.throughParentSoftDeletes()&&t.withGlobalScope("SoftDeletableHasManyThrough",t=>{t.whereNull(this.throughParent.getQualifiedDeletedAtColumn())})}getQualifiedParentKeyName(){return this.parent.qualifyColumn(this.secondLocalKey)}throughParentSoftDeletes(){return void 0!==this.throughParent.pluginInitializers.SoftDeletes}withTrashedParents(){return this.query.withoutGlobalScope("SoftDeletableHasManyThrough"),this}addEagerConstraints(t){const e=this.whereInMethod(this.farParent,this.localKey);this.whereInEager(e,this.getQualifiedFirstKeyName(),this.getKeys(t,this.localKey))}initRelation(t,e){for(const s of t)s.setRelation(e,this.related.newCollection());return t}match(t,e,s){const i=this.buildDictionary(e);for(const e of t){const t=this.getDictionaryKey(e.getAttribute(this.localKey));void 0!==i[t]&&e.setRelation(s,this.related.newCollection(i[t]))}return t}buildDictionary(t){const e={};for(const s of t)void 0===e[s.laravel_through_key]&&(e[s.laravel_through_key]=[]),e[s.laravel_through_key].push(s);return e}async firstOrNew(t){return await this.where(t).first()||this.related.newInstance(t)}async updateOrCreate(t,e={}){return $(await this.firstOrCreate(t,e),async t=>{t.wasRecentlyCreated||await t.fill(e).save()})}async firstWhere(t,e=null,s=null,i="and"){return await this.where(t,e,s,i).first()}async first(t=["*"]){const e=await this.take(1).get(t);return e.count()>0?e.first():null}async firstOrFail(t=["*"]){const e=await this.first(t);if(e)return e;throw(new M).setModel(this.related.constructor)}async firstOr(t=["*"],e=null){"function"==typeof t&&(e=t,t=["*"]);const s=await this.first(t);return s||e?.()}async find(t,e=["*"]){return a(t)?await this.findMany(t,e):await this.where(this.getRelated().getQualifiedKeyName(),"=",t).first(e)}async findMany(t,e=["*"]){return 0===t.length?this.getRelated().newCollection():await this.whereIn(this.getRelated().getQualifiedKeyName(),t).get(e)}async findOrFail(t,e=["*"]){const s=await this.find(t,e);if(Array.isArray(t)){if(s.count()===t.length)return s}else if(s)return s;throw(new M).setModel(this.related.constructor,t)}async getResults(){return this.farParent[this.localKey]?await this.get():this.related.newCollection()}async get(t=["*"]){const e=this.prepareQueryBuilder(t);let s=await e.getModels();return s.count()>0&&(s=await e.eagerLoadRelations(s)),this.related.newCollection(s)}async paginate(t=null,e=["*"],s="page",i=null){return this.query.addSelect(this.shouldSelect(e)),await this.query.paginate(t,e,s,i)}shouldSelect(t=["*"]){return"*"==t?.at(0)&&(t=[this.related.getTable()+".*"]),[...t,this.getQualifiedFirstKeyName()+" as laravel_through_key"]}async chunk(t,e){return await this.prepareQueryBuilder().chunk(t,e)}prepareQueryBuilder(t=["*"]){const e=this.query.applyScopes();return e.addSelect(this.shouldSelect(e.getQuery().columns?[]:t))}getRelationExistenceQuery(t,e,s=["*"]){return e.getQuery().from===t.getQuery().from?this.getRelationExistenceQueryForSelfRelation(t,e,s):e.getQuery().from===this.throughParent.getTable()?this.getRelationExistenceQueryForThroughSelfRelation(t,e,s):(this.performJoin(t),t.select(s).where(this.getQualifiedLocalKeyName(),"=",this.getQualifiedFirstKeyName()))}getRelationExistenceQueryForSelfRelation(t,e,s=["*"]){const i=this.getRelationCountHash();return t.from(t.getModel().getTable()+" as "+i),t.join(this.throughParent.getTable(),this.getQualifiedParentKeyName(),"=",i+"."+this.secondKey),this.throughParentSoftDeletes()&&t.whereNull(this.throughParent.getQualifiedDeletedAtColumn()),t.getModel().setTable(i),t.select(s).whereColumn(e.getQuery().from+"."+this.localKey,"=",this.getQualifiedFirstKeyName())}getRelationExistenceQueryForThroughSelfRelation(t,e,s=["*"]){const i=this.getRelationCountHash(),r=this.throughParent.getTable()+" as "+i;return t.join(r,i+"."+this.secondLocalKey,"=",this.getQualifiedFarKeyName()),this.throughParentSoftDeletes()&&t.whereNull(i+"."+this.throughParent.getDeletedAtColumn()),t.select(s).where(e.getQuery().from+"."+this.localKey,"=",i+"."+this.firstKey)}getQualifiedFarKeyName(){return this.getQualifiedForeignKeyName()}getFirstKeyName(){return this.firstKey}getQualifiedFirstKeyName(){return this.throughParent.qualifyColumn(this.firstKey)}getForeignKeyName(){return this.secondKey}getQualifiedForeignKeyName(){return this.related.qualifyColumn(this.secondKey)}getLocalKeyName(){return this.localKey}getQualifiedLocalKeyName(){return this.farParent.qualifyColumn(this.localKey)}getSecondLocalKeyName(){return this.secondLocalKey}},ut=class extends(J(ct,X)){async getResults(){return await this.first()||this.getDefaultFor(this.farParent)}initRelation(t,e){for(const s of t)s.setRelation(e,this.getDefaultFor(s));return t}match(t,e,s){const i=this.buildDictionary(e);for(const e of t){const t=this.getDictionaryKey(e.getAttribute(this.localKey));if(void 0!==i[t]){const r=i[t];e.setRelation(s,r[0])}}return t}newRelatedInstanceFor(t){return this.related.newInstance()}},gt=t=>class extends t{relations={};getRelation(t){return this.relations[t]}setRelation(t,e){return this.relations[t]=e,this}unsetRelation(t){return this.relations=r(this.relations,[t]),this}relationLoaded(t){return void 0!==this.relations[t]}related(t){if("function"!=typeof this[W(t)]){const e=`Model [${this.constructor.name}]'s relation [${t}] doesn't exist.`;throw new k(e)}return this[W(t)]()}async getRelated(t){return await this.related(t).getResults()}relationsToData(){const t={};for(const e in this.relations)this.hidden.includes(e)||this.visible.length>0&&!1===this.visible.includes(e)||(t[e]=this.relations[e]instanceof Array?this.relations[e].map(t=>t.toData()):null===this.relations[e]?null:this.relations[e].toData());return t}guessBelongsToRelation(){const t=(new Error).stack.split("\n")[2].split(" ")[5];return F(t)}joiningTable(t,e=null){return[e?e.joiningTableSegment():Y(t.name),this.joiningTableSegment()].sort().join("_").toLocaleLowerCase()}joiningTableSegment(){return Y(this.constructor.name)}hasOne(t,e=null,s=null){const i=t.query(),r=new t;return e=e||this.getForeignKey(),s=s||this.getKeyName(),new lt(i,this,r.getTable()+"."+e,s)}hasMany(t,e=null,s=null){const i=t.query(),r=new t;return e=e||this.getForeignKey(),s=s||this.getKeyName(),new ht(i,this,r.getTable()+"."+e,s)}belongsTo(t,e=null,s=null,i=null){const r=t.query(),n=new t;return e=e||n.getForeignKey(),s=s||n.getKeyName(),i=i||this.guessBelongsToRelation(),new tt(r,this,e,s,i)}belongsToMany(t,e=null,s=null,i=null,r=null,n=null){const a=t.query(),o=new t;return e=e||this.joiningTable(t,o),s=s||this.getForeignKey(),i=i||o.getForeignKey(),r=r||this.getKeyName(),n=n||o.getKeyName(),new Dt(a,this,e,s,i,r,n)}hasOneThrough(t,e,s=null,i=null,r=null,n=null){e=new e;const a=t.query();return s=s||this.getForeignKey(),i=i||e.getForeignKey(),new ut(a,this,e,s,i,r||this.getKeyName(),n||e.getKeyName())}hasManyThrough(t,e,s=null,i=null,r=null,n=null){e=new e;const a=t.query();return s=s||this.getForeignKey(),i=i||e.getForeignKey(),new ct(a,this,e,s,i,r||this.getKeyName(),n||e.getKeyName())}},dt=t=>class extends t{static CREATED_AT="created_at";static UPDATED_AT="updated_at";static DELETED_AT="deleted_at";timestamps=!0;dateFormat="YYYY-MM-DD HH:mm:ss";usesTimestamps(){return this.timestamps}updateTimestamps(){const t=this.freshTimestampString(),e=this.getUpdatedAtColumn();e&&!this.isDirty(e)&&this.setUpdatedAt(t);const s=this.getCreatedAtColumn();return this.exists||!s||this.isDirty(s)||this.setCreatedAt(t),this}getCreatedAtColumn(){return this.constructor.CREATED_AT}getUpdatedAtColumn(){return this.constructor.UPDATED_AT}setCreatedAt(t){return this.attributes[this.getCreatedAtColumn()]=t,this}setUpdatedAt(t){return this.attributes[this.getUpdatedAtColumn()]=t,this}freshTimestamp(){const t=new Date;return t.setMilliseconds(0),t}freshTimestampString(){return this.fromDateTime(this.freshTimestamp())}},yt=t=>class extends t{hidden=[];visible=[];makeVisible(...t){const e=z(t);return this.visible.length>0&&(this.visible=[...this.visible,...e]),this.hidden=s(this.hidden,e),this}makeHidden(t,...e){const s=z([...t,...e]);return this.hidden.length>0&&(this.hidden=[...this.hidden,...s]),this}getHidden(){return this.hidden}getVisible(){return this.visible}setHidden(t){return this.hidden=t,this}setVisible(t){return this.visible=t,this}},mt=t=>class extends t{useUniqueIds=!1;usesUniqueIds(){return this.useUniqueIds}uniqueIds(){return[]}newUniqueId(){return null}setUniqueIds(){const t=this.uniqueIds();for(const e of t)null!==this[e]&&void 0!==this[e]||(this[e]=this.newUniqueId())}},pt=class{static formatter;_items;_total;_perPage;_lastPage;_currentPage;hasMore=!1;options={};static setFormatter(t){if("function"!=typeof t&&null!=t)throw new Error("Paginator formatter must be a function or null");this.formatter=t}constructor(t,e,s,i=1,r={}){this.options=r;for(const t in r){const e=r[t];this[t]=e}this._items=new Nt([]),this._total=e,this._perPage=parseInt(String(s)),this._lastPage=Math.max(Math.ceil(e/s),1),this._currentPage=i,this.setItems(t)}setItems(t){this._items=t instanceof Nt?t:new Nt(t),this.hasMore=this._items.count()>this._perPage,this._items=this._items.slice(0,this._perPage)}firstItem(){return this.count()>0?(this._currentPage-1)*this._perPage+1:null}lastItem(){return this.count()>0?(this.firstItem()??0)+this.count()-1:null}hasMorePages(){return this._currentPage<this._lastPage}get(t){return this._items.get(t)}count(){return this._items.count()}items(){return this._items}map(t){return this._items.map(t)}currentPage(){return this._currentPage}onFirstPage(){return 1===this._currentPage}perPage(){return this._perPage}lastPage(){return this._lastPage}total(){return this._total}toData(){return this.constructor.formatter&&"function"==typeof this.constructor.formatter?this.constructor.formatter(this):{current_page:this._currentPage,data:this._items.toData(),per_page:this._perPage,total:this._total,last_page:this._lastPage,count:this.count()}}toJSON(){return this.toData()}toJson(...t){return JSON.stringify(this.toData(),...t)}},ft=class{},wt=class t extends ft{model;schema;connector;constructor(t,e){return super(),this.connector=e(t),this.asProxy()}asProxy(){return new Proxy(this,{get:function(t,e){return void 0!==t[e]?t[e]:["destroy","schema"].includes(e)?t.connector.schema:["select","from","where","orWhere","whereColumn","whereRaw","whereNot","orWhereNot","whereIn","orWhereIn","whereNotIn","orWhereNotIn","whereNull","orWhereNull","whereNotNull","orWhereNotNull","whereExists","orWhereExists","whereNotExists","orWhereNotExists","whereBetween","orWhereBetween","whereNotBetween","orWhereNotBetween","whereLike","orWhereLike","whereILike","orWhereILike","whereJsonObject","whereJsonPath","whereJsonSupersetOf","whereJsonSubsetOf","join","joinRaw","leftJoin","leftOuterJoin","rightJoin","rightOuterJoin","crossJoin","transacting","groupBy","groupByRaw","returning","having","havingRaw","havingBetween","limit","offset","orderBy","orderByRaw","union","insert","forUpdate","forShare","distinct","clearOrder","clear","clearSelect","clearWhere","clearHaving","clearGroup"].includes(e)?(...s)=>(t.connector[e](...s),t.asProxy()):t.connector[e]},set:function(t,e,s){return void 0!==t[e]?(t[e]=s,t):(t.connector[e]=s,t)}})}async beginTransaction(){return await this.connector.transaction()}table(e){const s=this.connector.table(e);return new t(null,()=>s)}transaction(e){return e?this.connector.transaction(s=>e(new t(null,()=>s))):e}async find(t,e=["*"]){return await this.connector.where("id",t).first(...e)}async get(t=["*"]){return await this.connector}async exists(){return null!==await this.connector.first()}skip(...t){return this.offset(...t)}take(...t){return this.limit(...t)}async chunk(t,e){if(0===this.connector._statements.filter(t=>"order"===t.grouping).length)throw new Error("You must specify an orderBy clause when using this function.");let s,i=1;do{const r=this.clone(),n=await r.forPage(i,t).get();if(s=n.length,0==s)break;if(!1===await e(n,i))return!1;i++}while(s===t);return!0}async paginate(t=1,e=15){const s=this.clone(),i=await s.clearOrder().count("*");let r;if(i>0){const s=(t-1)*e;this.take(e).skip(s),r=await this.get()}else r=[];return new pt(r,parseInt(i),e,t)}forPage(t=1,e=15){return this.offset((t-1)*e).limit(e)}toSQL(...t){return this.connector.toSQL(...t)}async count(t){const[{aggregate:e}]=await this.connector.count(t,{as:"aggregate"});return Number(e)}async min(t){const[{aggregate:e}]=await this.connector.min(t,{as:"aggregate"});return Number(e)}async max(t){const[{aggregate:e}]=await this.connector.max(t,{as:"aggregate"});return Number(e)}async sum(t){const[{aggregate:e}]=await this.connector.sum(t,{as:"aggregate"});return Number(e)}async avg(t){const[{aggregate:e}]=await this.connector.avg(t,{as:"aggregate"});return Number(e)}clone(){const e=this.connector.clone();return new t(null,()=>e)}async delete(){return await this.connector.delete()}async insert(...t){return await this.connector.insert(...t)}async update(...t){return await this.connector.update(...t)}destroy(...t){return this.connector.destroy(...t)}get _statements(){return this.connector._statements}get _single(){return this.connector._single}get from(){return this.connector.from}},bt=class t{static connectorFactory=null;static instance=null;manager;connections;models;constructor(){this.manager={},this.connections={},this.models={}}getConstructor(){return this.constructor}static getInstance(){return null===this.instance&&(this.instance=new t),this.instance}static connection(t=null){return this.getInstance().getConnection(t)}static setConnectorFactory(t){this.connectorFactory=t}static getConnectorFactory(){return this.connectorFactory??v}static addConnection(t,e="default"){return this.getInstance().addConnection(t,e)}static beginTransaction(t=null){return this.getInstance().beginTransaction(t)}static transaction(t,e=null){return this.getInstance().transaction(t,e)}static table(t,e=null){return this.getInstance().table(t,e)}static schema(t=null){return this.getInstance().schema(t)}static async destroyAll(){await this.getInstance().destroyAll()}static createModel(t,e){return this.getInstance().createModel(t,e)}connection(t=null){return this.getConnection(t)}getConnection(e=null){if(e=e||"default",void 0===this.manager[e]){const s=new wt(this.connections[e],t.getConnectorFactory());this.manager[e]=s}return this.manager[e]}addConnection(t,e="default"){this.connections[e]={...t,connection:{...t.connection,dateStrings:!0,typeCast:function(t,e){return"JSON"===t.type?t.string("utf8"):e()}}}}beginTransaction(t=null){return this.connection(t).beginTransaction()}transaction(t,e=null){return this.connection(e).transaction(t)}table(t,e=null){return this.connection(e).table(t)}schema(t=null){return this.connection(t).schema}async destroyAll(){await Promise.all(Object.values(this.manager).map(t=>t?.destroy()))}createModel(t,e={}){let s=vt;if("plugins"in e&&(s=J(s,...e.plugins??[])),this.models={...this.models,[t]:class extends s{table=e?.table??null;connection=e?.connection??null;timestamps=e?.timestamps??!0;primaryKey=e?.primaryKey??"id";keyType=e?.keyType??"int";incrementing=e?.incrementing??!0;with=e?.with??[];casts=e?.casts??{};static CREATED_AT=e?.CREATED_AT??"created_at";static UPDATED_AT=e?.UPDATED_AT??"updated_at";static DELETED_AT=e?.DELETED_AT??"deleted_at"}},"attributes"in e)for(const s in e.attributes){if(e.attributes[s]instanceof S==!1)throw new Error('Attribute must be an instance of "Attribute"');this.models[t].prototype[H(s)]=()=>e.attributes?.[s]}if("relations"in e)for(const s in e.relations)this.models[t].prototype[W(s)]=function(){return e.relations?.[s](this)};if("scopes"in e)for(const s in e.scopes)this.models[t].prototype[B(s)]=e.scopes[s];return this.models[t].setConnectionResolver(this),this.models[t]}},Ct=J(class{},st,yt,gt,dt,at,rt,mt),vt=class t extends Ct{primaryKey="id";builder=null;table=null;keyType="int";incrementing=!0;withCount=[];perPage=15;static globalScopes={};static pluginInitializers={};static _booted={};static resolver;connection=null;eagerLoad={};exists=!1;with=[];trx=null;constructor(t={}){return super(),this.bootIfNotBooted(),this.initializePlugins(),this.syncOriginal(),this.fill(t),this.asProxy()}static query(t=null){return(new this).newQuery(t)}static on(t=null){const e=new this;return e.setConnection(t),e.newQuery()}static init(t={}){return new this(t)}static extend(t,e){t(this,e)}static make(t={}){const e=new this;for(const s in t)if("function"!=typeof e[W(s)])e.setAttribute(s,t[s]);else{const i=e[W(s)](),r=i.getRelated().constructor;i instanceof lt||i instanceof tt?e.setRelation(s,r.make(t[s])):(i instanceof ht||i instanceof Dt)&&Array.isArray(t[s])&&e.setRelation(s,new Nt(t[s].map(t=>r.make(t))))}return e}getConstructor(){return this.constructor}bootIfNotBooted(){void 0===this.constructor._booted[this.constructor.name]&&(this.constructor._booted[this.constructor.name]=!0,this.constructor.booting(),this.initialize(),this.constructor.boot(),this.constructor.booted())}static booting(){}static boot(){}static booted(){}static setConnectionResolver(t){this.resolver=t}initialize(){}initializePlugins(){if(void 0!==this.constructor.pluginInitializers[this.constructor.name])for(const t of this.constructor.pluginInitializers[this.constructor.name])this[t]()}addPluginInitializer(t){this.constructor.pluginInitializers[this.constructor.name]||(this.constructor.pluginInitializers[this.constructor.name]=[]),this.constructor.pluginInitializers[this.constructor.name].push(t)}newInstance(t={},e=!1){const s=new this.constructor;return s.exists=e,s.setConnection(this.getConnectionName()),s.setTable(this.getTable()),s.fill(t),s}newFromBuilder(t={},e=null){const s=this.newInstance({},!0);return s.setRawAttributes(t,!0),s.setConnection(e||this.getConnectionName()),s}asProxy(){return new Proxy(this,{get:function(t,e){return void 0!==t[e]?t[e]:"string"==typeof e?t.getAttribute(e):void 0},set:function(t,e,s){return void 0!==t[e]&&"function"!=typeof t?(t[e]=s,t):"string"==typeof e?t.setAttribute(e,s):t}})}getKey(){return this.getAttribute(this.getKeyName())}getKeyName(){return this.primaryKey}getForeignKey(){return Y(this.constructor.name)+"_"+this.getKeyName()}getConnectionName(){return this.connection}getTable(){return this.table||K(Y(this.constructor.name))}getConnection(){return this.constructor.resolver?this.constructor.resolver.getConnection(this.connection):bt.connection(this.connection)}setConnection(t){return this.connection=t,this}getKeyType(){return this.keyType}newQuery(t=null){return this.addGlobalScopes(this.newQueryWithoutScopes(t))}newQueryWithoutScopes(t=null){return this.newModelQuery(t).with(this.with).withCount(this.withCount)}newModelQuery(t=null){return new Tt(t||this.getConnection()).setModel(this)}addGlobalScopes(t){const e=this.getGlobalScopes();for(const s in e){const i=e[s];t.withGlobalScope(s,i)}return t}hasNamedScope(t){return"function"==typeof this[B(t)]}callNamedScope(t,e){return this[B(t)](...e)}setTable(t){return this.table=t,this}newCollection(t=[]){return new Nt(t)}async load(...t){const e=this.constructor.query().with(...t);return await e.eagerLoadRelations([this]),this}async loadAggregate(t,e,s=null){return console.log(t),await new Nt([this]).loadAggregate(t,e,s),this}async loadCount(...t){return t=z(t),await this.loadAggregate(t,"*","count")}async loadMax(t,e){return await this.loadAggregate(t,e,"max")}async loadMin(t,e){return await this.loadAggregate(t,e,"min")}async loadSum(t,e){return await this.loadAggregate(t,e,"sum")}async increment(t,e=1,s={},i={}){return await this.incrementOrDecrement(t,e,s,"increment",i)}async decrement(t,e=1,s={},i={}){return await this.incrementOrDecrement(t,e,s,"decrement",i)}async incrementOrDecrement(t,e,s,i,r){const n=this.newModelQuery(r.client);if(!this.exists)return await n[i](t,e,s);this.attributes[t]=this[t]+("increment"===i?e:-1*e);for(const t in s)this.attributes[t]=s[t];return await this.execHooks("updating",r),await $(await n.where(this.getKeyName(),this.getKey())[i](t,e,s),async()=>{this.syncChanges(),await this.execHooks("updated",r),this.syncOriginalAttribute(t)})}toData(){return e(this.attributesToData(),this.relationsToData())}toJSON(){return this.toData()}toJson(...t){return JSON.stringify(this.toData(),...t)}toString(){return this.toJson()}fill(t){for(const e in t)this.setAttribute(e,t[e]);return this}transacting(t){return this.trx=t,this}trashed(){return null!==this[this.getDeletedAtColumn()]}getIncrementing(){return this.incrementing}setIncrementing(t){return this.incrementing=t,this}async save(t={}){const e=this.newModelQuery(t.client);let s;if(await this.execHooks("saving",t),this.exists)if(!1===this.isDirty())s=!0;else{await this.execHooks("updating",t),this.usesTimestamps()&&this.updateTimestamps();const i=this.getDirty();Object.keys(i).length>0&&(await e.where(this.getKeyName(),this.getKey()).query.update(i),this.syncChanges(),await this.execHooks("updated",t)),s=!0}else{this.usesUniqueIds()&&this.setUniqueIds(),await this.execHooks("creating",t),this.usesTimestamps()&&this.updateTimestamps();const i=this.getAttributes();if(this.getIncrementing()){const t=this.getKeyName(),s=await e.insert([i],[t]);this.setAttribute(t,s[0]?.[t]||s[0])}else Object.keys(i).length>0&&await e.insert(i);this.exists=!0,await this.execHooks("created",t),s=!0}return s&&(await this.execHooks("saved",t),this.syncOriginal()),s}async update(t={},e={}){if(!this.exists)return!1;for(const e in t)this[e]=t[e];return await this.save(e)}async delete(t={}){return await this.execHooks("deleting",t),await this.performDeleteOnModel(t),await this.execHooks("deleted",t),!0}async performDeleteOnModel(t={}){await this.setKeysForSaveQuery(this.newModelQuery(t.client)).delete(),this.exists=!1}setKeysForSaveQuery(t){return t.where(this.getKeyName(),"=",this.getKey()),t}async forceDelete(t={}){return await this.delete(t)}fresh(){if(this.exists)return this.constructor.query().where(this.getKeyName(),this.getKey()).first()}async refresh(){if(!this.exists)return Promise.resolve(void 0);const t=await this.constructor.query().where(this.getKeyName(),this.getKey()).first();return this.attributes={...t.attributes},await this.load(w(this.relations).reject(t=>t instanceof Kt).keys().all()),this.syncOriginal(),this}newPivot(t,e,s,i,r=null){return r?r.fromRawAttributes(t,e,s,i):Kt.fromAttributes(t,e,s,i)}qualifyColumn(t){return t.includes(".")?t:`${this.getTable()}.${t}`}getQualifiedKeyName(){return this.qualifyColumn(this.getKeyName())}async push(t={}){if(!await this.save(t))return!1;for(const e in this.relations){let s=this.relations[e];s=s instanceof Nt?s.all():[s];for(const e of s)if(!await e.push(t))return!1}return!0}is(e){return e&&e instanceof t&&this.getKey()===e.getKey()&&this.getTable()===e.getTable()&&this.getConnectionName()===e.getConnectionName()}isNot(t){return!this.is(t)}},Kt=class extends vt{incrementing=!1;guarded=[];pivotParent=null;foreignKey=null;relatedKey=null;setPivotKeys(t,e){return this.foreignKey=t,this.relatedKey=e,this}static fromRawAttributes(t,e,s,i=!1){const r=this.fromAttributes(t,{},s,i);return r.timestamps=r.hasTimestampAttributes(e),r.attributes=e,r.exists=i,r}static fromAttributes(t,e,s,i=!1){const r=new this;return r.timestamps=r.hasTimestampAttributes(e),r.setConnection(t.connection).setTable(s).fill(e).syncOriginal(),r.pivotParent=t,r.exists=i,r}hasTimestampAttributes(t=null){return void 0!==(t||this.attributes)[this.constructor.CREATED_AT]}},Pt=vt,Nt=class t extends C{newConstructor(...t){return new(this.getConstructor())(...t)}getConstructor(){return this.constructor}async load(...t){if(this.isNotEmpty()){const e=this.first().constructor.query().with(...t),s=await e.eagerLoadRelations(this.items);return this.newConstructor(s)}return this}async loadAggregate(t,e,r=null){if(this.isEmpty())return this;const n=(await this.first().newModelQuery().whereIn(this.first().getKeyName(),this.modelKeys()).select(this.first().getKeyName()).withAggregate(t,e,r).get()).keyBy(this.first().getKeyName()),a=s(Object.keys(n.first().getAttributes()),[n.first().getKeyName()]);return this.each(t=>{const e=i(n.get(t.getKey()).getAttributes(),a);t.fill(e).syncOriginalAttributes(...a)}),this}loadCount(t){return this.loadAggregate(t,"*","count")}loadMax(t,e){return this.loadAggregate(t,e,"max")}loadMin(t,e){return this.loadAggregate(t,e,"min")}loadSum(t,e){return this.loadAggregate(t,e,"sum")}loadAvg(t,e){return this.loadAggregate(t,e,"avg")}mapThen(t){return Promise.all(this.map(t))}modelKeys(){return this.all().map(t=>t.getKey())}contains(t,e,s){return arguments.length>1?super.contains(t,s??e):t instanceof Pt?super.contains(e=>e.is(t)):super.contains(e=>e.getKey()==t)}diff(t){const e=new this.constructor,s=this.getDictionary(t);return this.items.map(t=>{void 0===s[t.getKey()]&&e.add(t)}),e}except(t){const e=r(this.getDictionary(),t);return new this.constructor(Object.values(e))}intersect(t){const e=new this.constructor;if(n(t))return e;const s=this.getDictionary(t);for(const t of this.items)void 0!==s[t.getKey()]&&e.add(t);return e}unique(t,e=!1){return t?super.unique(t):new this.constructor(Object.values(this.getDictionary()))}find(t,e=null){return t instanceof Pt&&(t=t.getKey()),a(t)?this.isEmpty()?new this.constructor:this.whereIn(this.first().getKeyName(),t):(b(this.items).first(e=>e.getKey()==t),this.items.filter(e=>e.getKey()==t)[0]||e)}async fresh(...t){if(this.isEmpty())return new this.constructor;const e=this.first(),s=(await e.newQuery().with(...t).whereIn(e.getKeyName(),this.modelKeys()).get()).getDictionary();return this.filter(t=>t.exists&&void 0!==s[t.getKey()]).map(t=>s[t.getKey()])}makeVisible(t){return this.each(e=>{e.makeVisible(t)})}makeHidden(t){return this.each(e=>{e.makeHidden(t)})}append(t){return this.each(e=>{e.append(t)})}only(e){if(null===e)return new t(this.items);const s=i(this.getDictionary(),e);return new this.constructor(Object.values(s))}getDictionary(t){t=t||this.items;const e={};return t.map(t=>{e[t.getKey()]=t}),e}toQuery(){const t=this.first();if(!t)throw new Error("Unable to create query for empty collection.");const e=t.constructor.name;if(this.filter(t=>!(t instanceof e)).isNotEmpty())throw new Error("Unable to create query for collection with mixed types.");return t.newModelQuery().whereKey(this.modelKeys())}toData(){return this.all().map(t=>"function"==typeof t.toData?t.toData():t)}toJSON(){return this.toData()}toJson(...t){return JSON.stringify(this.toData(),...t)}[Symbol.iterator]=()=>{const t=this.items,e=this.items.length;let s=0;return{next:()=>s<e?{value:t[s++],done:!1}:{done:!0}}}},At=t=>class extends t{newExistingPivot(t=[]){return this.newPivot(t,!0)}newPivot(t=[],e=!1){return this.related.newPivot(this.parent,t,this.getTable(),e,this.using).setPivotKeys(this.foreignPivotKey,this.relatedPivotKey)}async attach(t,e={},s=!0){this.using?await this.attachUsingCustomClass(t,e):await this.newPivotStatement().insert(this.formatAttachRecords(this.parseIds(t),e))}async detach(t,e=!0){let s;if(this.using&&null!==t&&0==this.pivotWheres.length&&0==this.pivotWhereIns.length&&0==this.pivotWhereNulls.length)s=await this.detachUsingCustomClass(t);else{const e=this.newPivotQuery();if(null!==t){if(0==(t=this.parseIds(t)).length)return 0;e.whereIn(this.getQualifiedRelatedPivotKeyName(),t)}s=await e.delete()}return s}async sync(t,i=!0){let r,n={attached:[],detached:[],updated:[]};const a=await this.getCurrentlyAttachedPivots(),o=0===a.length?[]:a.map(t=>t.toData()).pluck(this.relatedPivotKey).all().map(t=>String(t)),h=s(o,Object.keys(r=this.formatRecordsList(this.parseIds(t))));return i&&h.length>0&&(await this.detach(h),n.detached=this.castKeys(h)),n=e(n,await this.attachNew(r,o,!1)),n}syncWithoutDetaching(t){return this.sync(t,!1)}syncWithPivotValues(t,e,s=!0){return this.sync(b(this.parseIds(t)).mapWithKeys(t=>[t,e]),s)}withPivot(t){return this.pivotColumns=this.pivotColumns.concat(a(t)?t:Array.prototype.slice.call(t)),this}async attachNew(t,e,s=!0){const i={attached:[],updated:[]};for(const r in t){const n=t[r];e.includes(r)?Object.keys(n).length>0&&await this.updateExistingPivot(r,n,s)&&i.updated.push(this.castKey(r)):(await this.attach(r,n,s),i.attached.push(this.castKey(r)))}return i}async updateExistingPivot(t,e,s=!0){if(this.using&&this.pivotWheres.length>0&&this.pivotWhereInspivotWheres.length>0&&this.pivotWhereNullspivotWheres.length>0)return await this.updateExistingPivotUsingCustomClass(t,e,s);this.hasPivotColumn(this.updatedAt())&&(e=this.addTimestampsToAttachment(e,!0));return this.newPivotStatementForId(this.parseId(t)).update(this.castAttributes(e))}addTimestampsToAttachment(t,e=!1){let s=this.parent.freshTimestamp();if(this.using){s=(new this.using).fromDateTime(s)}return!e&&this.hasPivotColumn(this.createdAt())&&(t[this.createdAt()]=s),this.hasPivotColumn(this.updatedAt())&&(t[this.updatedAt()]=s),t}async updateExistingPivotUsingCustomClass(t,e,s){const i=await this.getCurrentlyAttachedPivots().where(this.foreignPivotKey,this.parent[this.parentKey]).where(this.relatedPivotKey,this.parseId(t)).first(),r=!!i&&i.fill(e).isDirty();return r&&await i.save(),parseInt(r)}formatRecordsList(t){return b(t).mapWithKeys((t,e)=>(a(t)||([e,t]=[t,{}]),[e,t])).all()}async getCurrentlyAttachedPivots(){const t=this.newPivotQuery();return(await t.get()).map(t=>(this.using||Kt).fromRawAttributes(this.parent,t,this.getTable(),!0).setPivotKeys(this.foreignPivotKey,this.relatedPivotKey))}castKeys(t){return t.map(t=>this.castKey(t))}castKey(t){return this.getTypeSwapValue(this.related.getKeyType(),t)}getTypeSwapValue(t,e){switch(t.toLowerCase()){case"int":case"integer":return parseInt(e);case"real":case"float":case"double":return parseFloat(e);case"string":return String(e);default:return e}}newPivotQuery(){const t=this.newPivotStatement();return this.pivotWheres.map(e=>{t.where(...e)}),this.pivotWhereIns.map(e=>{t.whereIn(...e)}),this.pivotWhereNulls.map(e=>{t.whereNull(...e)}),t.where(this.getQualifiedForeignPivotKeyName(),this.parent[this.parentKey])}async detachUsingCustomClass(t){let e=0;for(const s in this.parseIds(t))e+=await this.newPivot({[this.foreignPivotKey]:this.parent[this.parentKey],[this.relatedPivotKey]:s},!0).delete();return e}newPivotStatement(){const t=this.parent.newQuery();return t.setTable(this.table),t}async attachUsingCustomClass(t,e){const s=this.formatAttachRecords(this.parseIds(t),e);await Promise.all(s.map(async t=>{await this.newPivot(t,!1).save()}))}formatAttachRecords(t,e){const s=[],i=this.hasPivotColumn(this.createdAt())||this.hasPivotColumn(this.updatedAt());for(const r in t){const n=t[r];s.push(this.formatAttachRecord(r,n,e,i))}return s}formatAttachRecord(t,s,i,r){const[n,a]=this.extractAttachIdAndAttributes(t,s,i);return e(this.baseAttachRecord(n,r),a)}baseAttachRecord(t,e){let s={};return s[this.relatedPivotKey]=t,s[this.foreignPivotKey]=this.parent[this.parentKey],e&&(s=this.addTimestampsToAttachment(s)),this.pivotValues.map(t=>{s[t.column]=t.value}),s}extractAttachIdAndAttributes(t,e,s){return a(e)?[t,{...e,...s}]:[e,s]}hasPivotColumn(t){return this.pivotColumns.includes(t)}parseIds(t){return t instanceof vt?[t[this.relatedKey]]:t instanceof Nt?t.pluck(this.relatedKey).all():a(t)?t:[t]}},Dt=class extends(J(Z,At)){table;foreignPivotKey;relatedPivotKey;parentKey;relatedKey;pivotColumns=[];pivotValues=[];pivotWheres=[];pivotWhereIns=[];pivotWhereNulls=[];accessor="pivot";using;pivotCreatedAt;pivotUpdatedAt;constructor(t,e,s,i,r,n,a){return super(t,e),this.table=s,this.foreignPivotKey=i,this.relatedPivotKey=r,this.parentKey=n,this.relatedKey=a,this.addConstraints(),this.asProxy()}initRelation(t,e){return t.map(t=>{t.setRelation(e,new Nt([]))}),t}addConstraints(){this.performJoin(),this.constructor.constraints&&this.addWhereConstraints()}performJoin(t=null){return(t=t||this.query).join(this.getTable(),this.getQualifiedRelatedKeyName(),"=",this.qualifyPivotColumn(this.relatedPivotKey)),this}getTable(){return this.table}getQualifiedRelatedKeyName(){return this.related.qualifyColumn(this.relatedKey)}async getResults(){return null!==this.parent[this.parentKey]?await this.get():new Nt([])}addWhereConstraints(){return this.query.where(this.getQualifiedForeignPivotKeyName(),"=",this.parent[this.parentKey]),this}async get(t){const e=this.query.applyScopes();t=e.query?._statements?.find(t=>"columns"==t.grouping)?[]:t;let s=await e.select(this.shouldSelect(t)).getModels();return this.hydratePivotRelation(s),s.length>0&&(s=await e.eagerLoadRelations(s)),new Nt(s)}async first(t=["*"]){const e=await this.take(1).get(t);return e.count()>0?e.first():null}async firstOrFail(t=["*"]){const e=await this.first(t);if(null!==e)return e;throw(new M).setModel(this.related.constructor)}async paginate(t=1,e=15,s=["*"]){return this.query.select(this.shouldSelect(s)),$(await this.query.paginate(t,e),t=>{this.hydratePivotRelation(t.items())})}async chunk(t,e){return await this.prepareQueryBuilder().chunk(t,async(t,s)=>(this.hydratePivotRelation(t.all()),await e(t,s)))}setUsing(t){return this.using=t,this}as(t){return this.accessor=t,this}prepareQueryBuilder(){return this.query.select(this.shouldSelect())}hydratePivotRelation(t){t.map(t=>{t.setRelation(this.accessor,this.newExistingPivot(this.migratePivotAttributes(t)))})}migratePivotAttributes(t){const e={};for(const s in t.attributes){const i=t.attributes[s];s.startsWith("pivot_")&&(e[s.substring(6)]=i,t.attributes=r(t.attributes,[s]))}return e}withTimestamps(t=null,e=null){return this.pivotCreatedAt=t,this.pivotUpdatedAt=e,this.withPivot(this.createdAt(),this.updatedAt())}shouldSelect(t=["*"]){return o(t,["*"])&&(t=[this.related.getTable()+".*"]),t.concat(this.aliasedPivotColumns())}aliasedPivotColumns(){const t=[this.foreignPivotKey,this.relatedPivotKey];return b(t.concat(this.pivotColumns)).map(t=>this.qualifyPivotColumn(t)+" as pivot_"+t).unique().all()}qualifyPivotColumn(t){return t.includes(".")?t:this.getTable()+"."+t}match(t,e,s){const i=this.buildDictionary(e);return t.map(t=>{const e=t.getKey();void 0!==i[e]&&t.setRelation(s,i[e])}),t}buildDictionary(t){const e={};return t.map(t=>{const s=t[this.accessor][this.foreignPivotKey];void 0===e[s]&&(e[s]=new Nt([])),e[s].push(t)}),e}addEagerConstraints(t){this.query.whereIn(this.getQualifiedForeignPivotKeyName(),this.getKeys(t,this.parentKey))}getQualifiedForeignPivotKeyName(){return this.qualifyPivotColumn(this.foreignPivotKey)}getQualifiedRelatedPivotKeyName(){return this.qualifyPivotColumn(this.relatedPivotKey)}wherePivot(t,e=null,s=null,i="and"){return this.pivotWheres.push(Array.prototype.slice.call(arguments)),this.where(this.qualifyPivotColumn(t),e,s,i)}wherePivotBetween(t,e,s="and",i=!1){return this.whereBetween(this.qualifyPivotColumn(t),e,s,i)}orWherePivotBetween(t,e){return this.wherePivotBetween(t,e,"or")}wherePivotNotBetween(t,e,s="and"){return this.wherePivotBetween(t,e,s,!0)}orWherePivotNotBetween(t,e){return this.wherePivotBetween(t,e,"or",!0)}wherePivotIn(t,e,s="and",i=!1){return this.whereIn(this.qualifyPivotColumn(t),e,s,i)}orWherePivot(t,e=null,s=null){return this.wherePivot(t,e,s,"or")}orWherePivotIn(t,e){return this.wherePivotIn(t,e,"or")}wherePivotNotIn(t,e,s="and"){return this.wherePivotIn(t,e,s,!0)}orWherePivotNotIn(t,e){return this.wherePivotNotIn(t,e,"or")}wherePivotNull(t,e="and",s=!1){return this.whereNull(this.qualifyPivotColumn(t),e,s)}wherePivotNotNull(t,e="and"){return this.wherePivotNull(t,e,!0)}orWherePivotNull(t,e=!1){return this.wherePivotNull(t,"or",e)}orWherePivotNotNull(t){return this.orWherePivotNull(t,!0)}orderByPivot(t,e="asc"){return this.orderBy(this.qualifyPivotColumn(t),e)}createdAt(){return this.pivotCreatedAt||this.parent.getCreatedAtColumn()}updatedAt(){return this.pivotUpdatedAt||this.parent.getUpdatedAtColumn()}getExistenceCompareKey(){return this.getQualifiedForeignPivotKeyName()}getRelationExistenceQuery(t,e,s=["*"]){return e.getQuery()._single.table==t.getQuery()._single.table?this.getRelationExistenceQueryForSelfJoin(t,e,s):(this.performJoin(t),super.getRelationExistenceQuery(t,e,s))}getRelationExistenceQueryForSelfJoin(t,e,s=["*"]){const i=this.getRelationCountHash();return t.select(s).from(this.related.getTable()+" as "+i),this.related.setTable(i),this.performJoin(t),super.getRelationExistenceQuery(t,e,s)}},xt=class{},Tt=class t extends xt{query;connection;model;actions;localMacros={};eagerLoad={};globalScopes={};onDeleteCallback;constructor(t){return super(),this.query=t,this.asProxy()}asProxy(){return new Proxy(this,{get(t,e){if(void 0!==t[e])return t[e];if(["select","from","where","orWhere","whereColumn","whereRaw","whereNot","orWhereNot","whereIn","orWhereIn","whereNotIn","orWhereNotIn","whereNull","orWhereNull","whereNotNull","orWhereNotNull","whereExists","orWhereExists","whereNotExists","orWhereNotExists","whereBetween","orWhereBetween","whereNotBetween","orWhereNotBetween","whereLike","orWhereLike","whereILike","orWhereILike","whereJsonObject","whereJsonPath","whereJsonSupersetOf","whereJsonSubsetOf","join","joinRaw","leftJoin","leftOuterJoin","rightJoin","rightOuterJoin","crossJoin","transacting","groupBy","groupByRaw","returning","having","havingRaw","havingBetween","limit","offset","orderBy","orderByRaw","union","insert","forUpdate","forShare","distinct","clearOrder","clear","clearSelect","clearWhere","clearHaving","clearGroup"].includes(e))return(...s)=>(t.query[e](...s),t.asProxy());if(["avg","max","min","sum","count"].includes(e))return s=>{const i=t.asProxy();return i.applyScopes(),s=s||"count"!==e?s:"*",i.query[e](s)};if("string"==typeof e){if(t.hasMacro(e)){const s=t.asProxy();return(...t)=>s.localMacros[e](s,...t)}if(t.hasNamedScope(e)){const s=t.asProxy();return(...t)=>(s.callNamedScope(e,t),s)}if(e.startsWith("where")){const s=l(e.substring(5));return(...e)=>(t.query.where(s,...e),t.asProxy())}}}})}orWhere(...t){if("function"==typeof t[0]){const e=t[0];return this.query.orWhere(t=>{this.query=t,e(this)}),this}return this.query.orWhere(...t),this}async chunk(t,e){let s,i=1;do{this.enforceOrderBy();const r=this.clone(),n=await r.forPage(i,t).get();if(s=n.count(),0==s)break;if(!1===await e(n,i))return!1;i++}while(s===t);return!0}enforceOrderBy(){0===this.query._statements.filter(t=>"order"===t.grouping).length&&this.orderBy(this.model.getQualifiedKeyName(),"asc")}clone(){const t=this.query.clone(),e=new this.constructor(t);return e.connection=this.connection,e.setModel(this.model),e.globalScopes={...this.globalScopes},e.localMacros={...this.localMacros},e.eagerLoad={...this.eagerLoad},e}forPage(t,e=15){return this.offset((t-1)*e).limit(e)}insert(...t){return this.query.insert(...t)}update(t){return this.applyScopes(),this.query.update(this.addUpdatedAtColumn(t))}increment(t,e=1,s={}){this.applyScopes();const i=this.model.getConnection();return this.query.update(this.addUpdatedAtColumn({...s,[t]:i.raw(`${t} + ${e}`)}))}decrement(t,e=1,s={}){this.applyScopes();const i=this.model.getConnection();return this.query.update(this.addUpdatedAtColumn({...s,[t]:i.raw(`${t} - ${e}`)}))}addUpdatedAtColumn(t){if(!this.model.usesTimestamps()||null===this.model.getUpdatedAtColumn())return t;const s=this.model.getUpdatedAtColumn();return t=e({[s]:this.model.freshTimestampString()},t)}delete(){return this.onDeleteCallback?this.onDeleteCallback(this):this.query.delete()}onDelete(t){this.onDeleteCallback=t}forceDelete(){return this.query.delete()}async create(t={}){return await $(this.newModelInstance(t),async t=>{await t.save({client:this.query})})}newModelInstance(t={}){return this.model.newInstance(t).setConnection(this.model.getConnectionName())}getQuery(){return this.query}getModel(){return this.model}setModel(t){return this.model=t,"function"==typeof this.query?.client?.table?this.query=this.query.client.table(this.model.getTable()):this.query=this.query.table(this.model.getTable()),this}qualifyColumn(t){return this.model.qualifyColumn(t)}setTable(t){return this.query=this.query.table(t),this}applyScopes(){if(!this.globalScopes)return this;for(const t in this.globalScopes){const e=this.globalScopes[t];e instanceof it?e.apply(this,this.getModel()):e(this)}return this}hasNamedScope(t){return this.model&&this.model.hasNamedScope(t)}callNamedScope(t,e){return this.model.callNamedScope(t,[this,...e])}callScope(t,e=[]){return t(this,...e)||this}scopes(t){return t.map(t=>{const e=B(t);"function"==typeof this.model[e]&&(this.globalScopes[t]=this.model[e])}),this}withGlobalScope(t,e){return this.globalScopes[t]=e,"function"==typeof e.extend&&e.extend(this),this}withoutGlobalScope(t){return"string"!=typeof t&&(t=t.constructor.name),this.globalScopes=r(this.globalScopes,[t]),this}macro(t,e){return this.localMacros[t]=e,this}hasMacro(t){return t in this.localMacros}getMacro(t){return this.localMacros[t]}with(...t){let s={};if("function"==typeof t[1]){const s=this.parseWithRelations({[t[0]]:t[1]});return this.eagerLoad=e(this.eagerLoad,s),this}const i=z(t);if(0===i.length)return this;for(const t of i){let i;"string"==typeof t?i={[t]:t=>t}:"object"==typeof t&&(i=t),s=e(s,i)}return this.eagerLoad=e(this.eagerLoad,this.parseWithRelations(s)),this}has(t,e=">=",s=1,i="and",r=null){if(h(t)){if(t.includes("."))return this.hasNested(t,e,s,i,r);t=this.getRelationWithoutConstraints(W(t))}const n=t[this.canUseExistsForExistenceCheck(e,s)?"getRelationExistenceQuery":"getRelationExistenceCountQuery"](t.getRelated().newModelQuery(),this);return r&&r(n),this.addHasWhere(n,t,e,s,i)}orHas(t,e=">=",s=1){return this.has(t,e,s,"or")}doesntHave(t,e="and",s=null){return this.has(t,"<",1,e,s)}orDoesntHave(t){return this.doesntHave(t,"or")}whereHas(t,e=null,s=">=",i=1){return this.has(t,s,i,"and",e)}orWhereHas(t,e=null,s=">=",i=1){return this.has(t,s,i,"or",e)}whereRelation(t,...e){const s=e.shift();return this.whereHas(t,t=>{"function"==typeof s?s(t):t.where(s,...e)})}orWhereRelation(t,...e){const s=e.shift();return this.orWhereHas(t,function(t){"function"==typeof s?s(t):t.where(s,...e)})}hasNested(t,e=">=",s=1,i="and",r=null){t=t.split(".");const n="<"===e&&1===s;n&&(e=">=",s=1);const a=i=>(t.length>1?i.whereHas(t.shift(),a):i.has(t.shift(),e,s,"and",r),null);return this.has(t.shift(),n?"<":">=",1,i,a)}canUseExistsForExistenceCheck(t,e){return(">="===t||"<"===t)&&1===e}addHasWhere(t,e,s,i,r){return t.mergeConstraintsFrom(e.getQuery()),this.canUseExistsForExistenceCheck(s,i)?this.addWhereExistsQuery(t.getQuery(),r,"<"===s&&1===i):this.addWhereCountQuery(t.getQuery(),s,i,r)}addWhereExistsQuery(t,e="and",s=!1){const i=s?"NotExists":"Exists";return this["and"===e?"where"+i:"orWhere"+i](t.connector),this}addWhereCountQuery(t,e=">=",s=1,i="and"){const r=this.model.getConnection();return this.where(r.raw("("+t.toSQL().sql+")"),e,"number"==typeof s?r.raw(s):s,i)}withAggregate(t,s,i=null){if(0===t.length)return this;t=z([t]);let r={};for(const s of t){let t;"string"==typeof s?t={[s]:t=>t}:"object"==typeof s&&(t=s),r=e(r,t)}t=r;const n=this.model.getConnection();0===this.query._statements.filter(t=>"columns"==t.grouping).map(t=>t.value).flat().length&&this.query.select([this.query._single.table+".*"]);const a=this.parseWithRelations(t);for(let t in a){const e=a[t],r=t.split(" ");let o,h;3===r.length&&"as"===r[1].toLocaleLowerCase()&&([t,o]=[r[0],r[2]]);const c=this.getRelationWithoutConstraints(W(t));if(i){const t=this.query._single.table===c.query.query._single.table?`${c.getRelationCountHash(!1)}.${s}`:s,e="*"===s?s:c.getRelated().qualifyColumn(t);h="exists"===i?e:`${i}(${e})`}else h=s;const u=c.getRelationExistenceQuery(c.getRelated().newModelQuery(),this,n.raw(h));e(u),o=o||l(`${t} ${i} ${s}`.replace("/[^[:alnum:][:space:]_]/u","")),"exists"===i?this.select(n.raw(`exists(${u.toSql().sql}) as ${o}`)):this.selectSub(i?u:u.limit(1),o)}return this}toSql(){const t=this.clone();return t.applyScopes(),t.query.toSQL()}mergeConstraintsFrom(t){return this}selectSub(t,e){const[s,i]=this.createSub(t),r=this.model.getConnection();return this.select(r.raw("("+s+") as "+e,i))}createSub(t){return this.parseSub(t)}parseSub(e){if(e instanceof t||e instanceof Z)return[e.toSql().sql,e.toSql().bindings];if(h(e))return[e,[]];throw new Error("A subquery must be a query builder instance, a Closure, or a string.")}prependDatabaseNameIfCrossDatabaseQuery(t){if(t.query._single.table!==this.query._single.table){const e=t.query._single.table;t.query._single.table.startsWith(e)||t.query._single.table.contains(".")||t.from(e+"."+t.from)}return t}getRelationWithoutConstraints(t){return Z.noConstraints(()=>this.getModel()[t]())}withCount(...t){return this.withAggregate(z(t),"*","count")}withMax(t,e){return this.withAggregate(t,e,"max")}withMin(t,e){return this.withAggregate(t,e,"min")}withAvg(t,e){return this.withAggregate(t,e,"avg")}withSum(t,e){return this.withAggregate(t,e,"sum")}withExists(t){return this.withAggregate(t,"*","exists")}parseWithRelations(t){if(0===t.length)return[];let e={};const s=this.prepareNestedWithRelationships(t);for(const t in s)e=this.addNestedWiths(t,e),e[t]=s[t];return e}addNestedWiths(t,e){const s=[];return t.split(".").map(t=>{s.push(t);const i=s.join(".");void 0===e[i]&&(e[i]=()=>{})}),e}prepareNestedWithRelationships(t,e=""){let s={};""!==e&&(e+=".");for(const i in t){const n=t[i];if(h(n)||Number.isFinite(parseInt(n)))continue;const[a,o]=this.parseNameAndAttributeSelectionConstraint(i,n);s=Object.assign({},s,{[`${e}${a}`]:o},this.prepareNestedWithRelationships(n,`${e}${a}`)),t=r(t,[i])}for(const i in t){const r=t[i];let n=i,a=r;h(r)&&([n,a]=this.parseNameAndAttributeSelectionConstraint(r)),s[`${e}${n}`]=this.combineConstraints([a,s[`${e}${n}`]||(()=>{})])}return s}combineConstraints(t){return e=>(t.map(t=>{e=t(e)||e}),e)}parseNameAndAttributeSelectionConstraint(t,e){return t.includes(":")?this.createSelectWithConstraint(t):[t,e]}createSelectWithConstraint(t){return[t.split(":")[0],e=>{e.select(t.split(":")[1].split(",").map(t=>t.includes(".")?t:e instanceof Dt?e.related.getTable()+"."+t:t))}]}related(t){if("function"!=typeof this.model[W(t)]){const e=`Model [${this.model.constructor.name}]'s relation [${t}] doesn't exist.`;throw new k(e)}return this.model[W(t)]()}take(...t){return this.limit(...t)}skip(...t){return this.offset(...t)}async first(...t){this.applyScopes(),this.limit(1);let e=await this.getModels(t);return e.length>0&&(e=await this.eagerLoadRelations(e)),e[0]||null}async firstOrFail(...t){const e=await this.first(...t);if(null===e)throw(new M).setModel(this.model.constructor.name);return e}async findOrFail(...t){const e=await this.find(...t);if(a(t[0])){if(e.count()!==t[0].length)throw(new M).setModel(this.model.constructor.name,s(t[0],e.modelKeys()));return e}if(null===e)throw(new M).setModel(this.model.constructor.name,t[0]);return e}async findOrNew(t,e=["*"]){const s=await this.find(t,e);return null!==s?s:this.newModelInstance()}async firstOrNew(t={},s={}){const i=await this.where(t).first();return null!==i?i:this.newModelInstance(e(t,s))}async firstOrCreate(t={},s={}){const i=await this.where(t).first();return null!==i?i:$(this.newModelInstance(e(t,s)),async t=>{await t.save({client:this.query})})}async updateOrCreate(t,e={}){return await $(await this.firstOrNew(t),async t=>{await t.fill(e).save({client:this.query})})}latest(t="id"){return null===t&&(t=this.model.getCreatedAtColumn()||"created_at"),this.query.orderBy(t,"desc"),this}oldest(t="id"){return null===t&&(t=this.model.getCreatedAtColumn()||"created_at"),this.query.orderBy(t,"asc"),this}async find(t,e){return a(t)||t instanceof Nt?await this.findMany(t,e):await this.where(this.model.getKeyName(),t).first(e)}async findMany(t,e=["*"]){return t instanceof Nt&&(t=t.modelKeys()),0===(t=a(t)?t:[t]).length?new Nt([]):await this.whereIn(this.model.getKeyName(),t).get(e)}async pluck(t){const e=await this.query.pluck(t);return new Nt(e)}async destroy(t){if(t instanceof Nt&&(t=t.modelKeys()),t instanceof C&&(t=t.all()),0===(t=a(t)?t:Array.prototype.slice.call(t)).length)return 0;const e=this.model.newInstance().getKeyName();let s=0;const i=await this.model.newModelQuery().whereIn(e,t).get();for(const t of i)await t.delete()&&s++;return s}async get(t=["*"]){this.applyScopes();let e=await this.getModels(t);return e.length>0&&(e=await this.eagerLoadRelations(e)),new Nt(e)}async all(t=["*"]){return await this.model.newModelQuery().get(t)}async paginate(t=1,e=10){t=t||1,e=e||this?.model?.perPage||15,this.applyScopes();const s=this.query.clone(),i=await s.clearOrder().clearSelect().count(this.primaryKey);let r=[];if(i>0){const s=(t-1)*(e??10);this.take(e).skip(s),r=await this.getModels(),r.length>0&&(r=await this.eagerLoadRelations(r))}else r=[];return new pt(r,parseInt(i),e,t)}async getModels(...t){return(t=c(t)).length>0&&0==this.query._statements.filter(t=>"columns"==t.grouping).length&&"*"!==t[0]&&this.query.select(...t),this.hydrate(await this.query.get()).all()}getRelation(t){if("function"!=typeof this.model[W(t)]){const e=`Model [${this.model.constructor.name}]'s relation [${t}] doesn't exist.`;throw new k(e)}const e=Z.noConstraints(()=>this.model.newInstance(this.model.attributes)[W(t)]()),s=this.relationsNestedUnder(t);return Object.keys(s).length>0&&e.query.with(s),e.asProxy()}relationsNestedUnder(t){const e={};for(const s in this.eagerLoad){const i=this.eagerLoad[s];this.isNestedUnder(t,s)&&(e[s.substring((t+".").length)]=i)}return e}isNestedUnder(t,e){return e.includes(".")&&e.startsWith(t+".")}async eagerLoadRelation(t,e,s){const i=this.getRelation(e);return i.addEagerConstraints(t),s(i),i.match(i.initRelation(t,e),await i.get(),e)}async eagerLoadRelations(t){for(const e in this.eagerLoad){const s=this.eagerLoad[e];e.includes(".")||(t=await this.eagerLoadRelation(t,e,s))}return t}hydrate(t){return new Nt(t.map(t=>{if(!this.model)return t;return this.model.newFromBuilder(t)}))}},Rt=t=>class extends t{useUniqueIds=!0;uniqueIds(){return[this.getKeyName()]}getKeyType(){return this.uniqueIds().includes(this.getKeyName())?"string":this.keyType}getIncrementing(){return!this.uniqueIds().includes(this.getKeyName())&&this.incrementing}},St=class{resolver;table;connection=null;constructor(t,e){this.resolver=t,this.table=e}async getRan(){return await this.getTable().orderBy("batch","asc").orderBy("migration","asc").pluck("migration")}async getMigrations(t){const e=this.getTable().where("batch",">=","1");return await e.orderBy("batch","desc").orderBy("migration","desc").take(t).get()}async getMigrationsByBatch(t){return await this.getTable().where("batch",t).orderBy("migration","desc").get()}async getLast(){const t=this.getTable().where("batch",await this.getLastBatchNumber());return await t.orderBy("migration","desc").get()}async getMigrationBatches(){const t=await this.getTable().select("batch","migration").orderBy("batch","asc").orderBy("migration","asc").get(),e={};return t.map(t=>{e[t.migration]=t.batch}),e}async log(t,e){await this.getTable().insert({migration:t,batch:e})}async delete(t){await this.getTable().where("migration",t.migration).delete()}async getNextBatchNumber(){return await this.getLastBatchNumber()+1}async getLastBatchNumber(){return await this.getTable().max("batch")}async createRepository(){const t=this.getConnection().schema;await t.createTable(this.table,function(t){t.increments("id"),t.string("migration"),t.integer("batch")})}repositoryExists(){return this.getConnection().schema.hasTable(this.table)}async deleteRepository(){const t=this.getConnection().schema;await t.drop(this.table)}getTable(){return this.getConnection().table(this.table)}getConnection(){return this.resolver.connection(this.connection)}setSource(t){this.connection=t}};async function qt(t){const e=await N.readdir(t),s=[];for(const i of e){const e=`${t}/${i}`,r=await N.stat(e);if(r.isFile())s.push(e);else if(r.isDirectory()){const t=await qt(e);s.push(...t)}}return s}var Mt=class{events=null;repository;files;resolver;connection;paths=[];output=null;constructor(t,e=null,s=null,i=null){this.repository=t,this.files=s,this.resolver=e,this.events=i}async run(t=[],e={}){const s=await this.getMigrationFiles(t),i=await this.repository.getRan(),r=this.pendingMigrations(s,i);return await this.runPending(r,e),r}pendingMigrations(t,e){return Object.values(t).filter(t=>!e.includes(this.getMigrationName(t)))}async runPending(t,e={}){if(0===t.length)return void this.write("Nothing to migrate");let s=await this.repository.getNextBatchNumber();const i=e.pretend||!1,r=e.step||!1;this.write("Running migrations.");for(const e of t)await this.runUp(e,s,i),r&&s++}async runUp(t,e,s){const i=await this.resolvePath(t),r=this.getMigrationName(t);await this.writeTask(r,()=>this.runMigration(i,"up")),await this.repository.log(r,e)}async runDown(t,e,s){const i=await this.resolvePath(t),r=this.getMigrationName(t);await this.writeTask(r,()=>this.runMigration(i,"down")),await this.repository.delete(e)}async rollback(t=[],e={}){const s=await this.getMigrationsForRollback(e);return 0===s.length?(this.write("Nothing to rollback."),[]):await this.rollbackMigrations(s,t,e)}async getMigrationsForRollback(t){return t.step&&t.step>0?await this.repository.getMigrations(t.step):t.batch&&t.batch>0?await this.repository.getMigrationsByBatch(t.batch):await this.repository.getLast()}async rollbackMigrations(t,e,s){const i=[],r=await this.getMigrationFiles(e);this.write("Rolling back migrations.");for(const e of t){const t=r[e.migration];t?(i.push(t),await this.runDown(t,e,s.pretend||!1)):this.writeTwoColumns(e.migration,P.yellow("Migration not found"))}return i}reset(t=[],e=!1){return this.repository.getRan().then(t=>t.reverse()),[]}resetMigrations(t,e,s=!1){return this.rollbackMigrations(t,e,{pretend:s})}async runMigration(t,e){const s=this.resolveConnection(t.getConnection()),i=async s=>{"function"==typeof t[e]&&await this.runMethod(s,t,e)};t.withinTransaction?await s.transaction(i):await i(s)}async runMethod(t,e,s){await(e[s]?.(t.schema,t))}async resolvePath(t){try{return new((await import(t)).default)}catch{}return new class{}}getMigrationClass(t){return t.split("_").slice(4).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}async getMigrationFiles(t){const e=[];for(const s of t)s.endsWith(".js")||s.endsWith(".ts")?e.push(s):e.push(...await qt(s));return e.filter(Boolean).reduce((t,e)=>(t[this.getMigrationName(e)]=e,t),{})}getMigrationName(t){return D.basename(t).replace(".js","")}path(t){this.paths=Array.from(new Set([...this.paths,t]))}getPaths(){return this.paths}getConnection(){return this.connection}resolveConnection(t){return this.resolver.connection(t||this.connection)}getRepository(){return this.repository}repositoryExists(){return this.repository.repositoryExists()}async hasRunAnyMigrations(){const t=await this.repository.getRan();return await this.repositoryExists()&&t.length>0}deleteRepository(){this.repository.deleteRepository()}setOutput(t){return this.output=t,this}write(...t){this.output&&console.log(...t)}writeTwoColumns(t,...e){const s=e.join(" "),i=/\x1b\[\d+m/g,r=Math.min(process.stdout.columns,100),n=Math.max(r-t.replace(i,"").length-s.replace(i,"").length-10,0);this.write(t,P.gray(".".repeat(n)),s)}async writeTask(t,e){const s=process.hrtime();let i=!1;try{i=await(e||(()=>!0))()}finally{const e=process.hrtime(s),r=(1e9*e[0]+e[1])/1e6;this.writeTwoColumns(P.green(t),P.gray(`${Math.floor(r)}ms`),!1!==i?P.green("✔"):P.red("✘"))}}},kt=D.join,It=class{static textFormat(t,e){return String(t).split(":").map((t,s,i)=>0==s&&i.length>1?e(" "+t+": "):t).join("")}static output(){return{success:(t,e=!1)=>{console.log(P.green("✓"),this.textFormat(t,P.bgGreen),"\n"),e&&process.exit(0)},info:(t,e=!1)=>{console.log(P.blue("ℹ"),this.textFormat(t,P.bgBlue),"\n"),e&&process.exit(0)},error:(t,e=!0)=>{t instanceof Error?(t.message&&console.error(P.red("✖"),this.textFormat(t.message,P.bgRed)),console.error(P.red(`${t.detail?`${t.detail}\n`:""}${t.stack}`),"\n")):console.error(P.red("✖"),this.textFormat(t,P.bgRed),"\n"),e&&process.exit(1)},quiet:()=>{process.exit(0)}}}static findModulePkg(t,e){const s=t.replace(/\\/g,"/").split("/");let i="";s.length>0&&"@"===s[0][0]&&(i+=s.shift()+"/"),i+=s.shift();const r=D.join(i,"package.json"),n=T.silent(e??process.cwd(),r);if(n)return D.join(D.dirname(n),s.join("/"))}static async getMigrationPaths(t,e,s,i){return i?[kt(t,i)]:[...e.getPaths(),kt(t,s)]}static twoColumnDetail(t,e){const s=/\x1b\[\d+m/g,i=Math.min(process.stdout.columns,100),r=Math.max(i-t.replace(s,"").length-e.replace(s,"").length-10,0);return console.log(t,P.gray(".".repeat(r)),e)}static async fileExists(t){try{return await A(t),!0}catch{return!1}}static findUpConfig(t,e,s){return x(t,(t,i)=>{for(const t of s){const s=`${e}.${t}`;if(i.includes(s))return s}return!1})}},Qt=class{constructor(t,e,s){this.basePath=t,this.customStubPath=e,this.callback=s??((t="")=>{})}callback;async run(t,e={},s=!1){const{arquebus:i,migrator:r}=await this.setupConnection(t);await this.prepareDatabase(r);const n=await It.getMigrationPaths(this.basePath??process.cwd(),r,t.migrations.path,e.path);await r.setOutput(!0).run(n,{step:e.step,pretend:e.pretend}),s&&await i.destroyAll()}async rollback(t,e={},s=!1){const{arquebus:i,migrator:r}=await this.setupConnection(t),n=await It.getMigrationPaths(this.basePath??process.cwd(),r,t.migrations.path,e.path);await r.setOutput(!0).rollback(n,{step:e.step||0,pretend:e.pretend,batch:e.batch||0}),s&&await i.destroyAll()}async prepareDatabase(t){await t.repositoryExists()||(this.callback("INFO: Preparing database.","info"),this.callback("INFO: Creating migration table...","info"),await t.repository.createRepository(),this.callback("SUCCESS: Migration table created successfully.","success"))}async status(t,e={},s=!1){const{arquebus:i,migrator:r}=await this.setupConnection(t),n=async()=>await r.getMigrationFiles(await It.getMigrationPaths(this.basePath??process.cwd(),r,t.migrations.path,e.path));await r.repositoryExists()||this.callback("ERROR: Migration table does not exist.","error");const a=await r.repository.getRan(),o=await r.getRepository().getMigrationBatches(),h=await async function(t,e){const s=await n();return Object.values(s).map(s=>{const i=r.getMigrationName(s);return{name:i,ran:t.includes(i),batch:t.includes(i)?e[i]:null}})}(a,o);return s&&await i.destroyAll(),h}async setupConnection(t){const e=t?.migrations?.table||"migrations";bt.addConnection(t,"default"),Object.entries(t.connections||{}).forEach(([t,e])=>{bt.addConnection(e,t)});const s=new St(bt,e),i=new Mt(s,bt);return{arquebus:bt,migrator:i}}},Et=class{},_t=class extends Et{connection;withinTransaction=!0;getConnection(){return this.connection}},Ft=Kt,Ot=class extends it{extensions=["Restore","RestoreOrCreate","CreateOrRestore","WithTrashed","WithoutTrashed","OnlyTrashed"];apply(t,e){t.whereNull(e.getQualifiedDeletedAtColumn())}extend(t){for(const e of this.extensions)this[`add${e}`](t);t.onDelete(async t=>{const e=this.getDeletedAtColumn(t);return await t.update({[e]:t.getModel().freshTimestampString()})})}getDeletedAtColumn(t){return(t=>{for(const e of t)if("join"===e?.grouping)return!0;return!1})(t.getQuery()._statements)?t.getModel().getQualifiedDeletedAtColumn():t.getModel().getDeletedAtColumn()}addRestore(t){t.macro("restore",t=>(t.withTrashed(),t.update({[t.getModel().getDeletedAtColumn()]:null})))}addRestoreOrCreate(t){t.macro("restoreOrCreate",async(t,e={},s={})=>(t.withTrashed(),$(await t.firstOrCreate(e,s),async t=>{await t.restore()})))}addCreateOrRestore(t){t.macro("createOrRestore",async(t,e={},s={})=>(t.withTrashed(),$(await t.createOrFirst(e,s),async t=>{await t.restore()})))}addWithTrashed(t){t.macro("withTrashed",(t,e=!0)=>e?t.withoutGlobalScope(this):t.withoutTrashed())}addWithoutTrashed(t){t.macro("withoutTrashed",t=>{const e=t.getModel();return t.withoutGlobalScope(this).whereNull(e.getQualifiedDeletedAtColumn()),t})}addOnlyTrashed(t){t.macro("onlyTrashed",t=>{const e=t.getModel();return t.withoutGlobalScope(this).whereNotNull(e.getQualifiedDeletedAtColumn()),t})}},Wt=t=>class extends t{forceDeleting=!1;static bootSoftDeletes(){this.addGlobalScope(new Ot)}initialize(){super.initialize(),this.constructor.bootSoftDeletes(),this.addPluginInitializer("initializeSoftDeletes")}initializeSoftDeletes(){void 0===this.casts[this.getDeletedAtColumn()]&&(this.casts[this.getDeletedAtColumn()]="datetime")}async forceDelete(){return!1!==this.execHooks("forceDeleting")&&(this.forceDeleting=!0,$(await this.delete(),t=>{this.forceDeleting=!1,t&&this.execHooks("forceDeleted",!1)}))}forceDeleteQuietly(){return this.withoutEvents(()=>this.forceDelete())}async performDeleteOnModel(t={}){return this.forceDeleting?$(await this.setKeysForSaveQuery(this.newModelQuery()).forceDelete(),()=>{this.exists=!1}):await this.runSoftDelete(t)}async runSoftDelete(t={}){const e=this.setKeysForSaveQuery(this.newModelQuery()),s=this.freshTimestamp(),i={[this.getDeletedAtColumn()]:this.fromDateTime(s)};this[this.getDeletedAtColumn()]=s,this.usesTimestamps()&&this.getUpdatedAtColumn()&&(this[this.getUpdatedAtColumn()]=s,i[this.getUpdatedAtColumn()]=this.fromDateTime(s)),await e.update(i),this.syncOriginalAttributes(Object.keys(i)),this.execHooks("trashed",t)}async restore(t={}){if(!1===this.execHooks("restoring",t))return!1;this[this.getDeletedAtColumn()]=null,this.exists=!0;const e=await this.save();return this.execHooks("restored",t),e}restoreQuietly(){return this.withoutEvents(()=>this.restore())}trashed(){return!m(this[this.getDeletedAtColumn()])}static softDeleted(t){this.addHook("trashed",t)}static restoring(t){this.addHook("restoring",t)}static restored(t){this.addHook("restored",t)}static forceDeleting(t){this.addHook("forceDeleting",t)}static forceDeleted(t){this.addHook("forceDeleted",t)}isForceDeleting(){return this.forceDeleting}getDeletedAtColumn(){return this.constructor.DELETED_AT||"deleted_at"}getQualifiedDeletedAtColumn(){return this.qualifyColumn(this.getDeletedAtColumn())}},Bt=(t,e,s={})=>{const{paginated:i}=s;return i?new pt(e.data.map(e=>t.make(e)),e.total,e.per_page,e.current_page):Array.isArray(e)?new Nt(e.map(e=>t.make(e))):t.make(e)},Ht=(t,e)=>new Nt(e.map(e=>t.make(e))),jt=(t,e)=>new pt(e.data.map(e=>t.make(e)),e.total,e.per_page,e.current_page);export{S as Attribute,Tt as Builder,et as CastsAttributes,Nt as Collection,Rt as HasUniqueIds,I as InvalidArgumentError,Qt as Migrate,_t as Migration,Pt as Model,M as ModelNotFoundError,pt as Paginator,Ft as Pivot,wt as QueryBuilder,k as RelationNotFoundError,it as Scope,Wt as SoftDeletes,bt as arquebus,J as compose,V as defineConfig,z as flattenDeep,H as getAttrMethod,U as getAttrName,j as getGetterMethod,W as getRelationMethod,F as getRelationName,B as getScopeMethod,O as getScopeName,L as getSetterMethod,G as kebabCase,Bt as make,Ht as makeCollection,jt as makePaginator,_ as now,Y as snakeCase,$ as tap};
|