@h3ravel/arquebus 0.6.6 → 0.6.7

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