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