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