@h3ravel/arquebus 0.3.5 → 0.4.0

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