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