@h3ravel/arquebus 0.6.7 → 0.6.9

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