@h3ravel/arquebus 2.0.0 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/index.cjs +580 -451
- package/bin/index.js +566 -437
- package/dist/browser/index.cjs +54 -51
- package/dist/browser/index.d.ts +804 -737
- package/dist/browser/index.js +48 -44
- package/dist/concerns/index.cjs +152 -143
- package/dist/concerns/index.d.ts +849 -776
- package/dist/concerns/index.js +143 -133
- package/dist/index.cjs +186 -185
- package/dist/index.d.ts +856 -782
- package/dist/index.js +179 -177
- package/dist/inspector/index.cjs +175 -174
- package/dist/inspector/index.d.ts +0 -1
- package/dist/inspector/index.js +161 -159
- package/dist/migrations/index.cjs +183 -182
- package/dist/migrations/index.d.ts +799 -727
- package/dist/migrations/index.js +172 -170
- package/dist/relations/index.cjs +152 -143
- package/dist/relations/index.d.ts +835 -762
- package/dist/relations/index.js +143 -133
- package/dist/seeders/index.cjs +7 -5
- package/dist/seeders/index.d.ts +797 -724
- package/dist/seeders/index.js +8 -6
- package/dist/{migrations/stubs/stubs → stubs}/migration-js.stub +1 -0
- package/dist/{migrations/stubs/stubs → stubs}/migration-ts.stub +1 -0
- package/dist/{migrations/stubs/stubs → stubs}/migration.create-js.stub +1 -0
- package/dist/{migrations/stubs/stubs → stubs}/migration.create-ts.stub +1 -0
- package/dist/{migrations/stubs/stubs → stubs}/migration.update-js.stub +1 -0
- package/dist/{migrations/stubs/stubs → stubs}/migration.update-ts.stub +1 -0
- package/dist/stubs/model-ts.stub +9 -0
- package/package.json +31 -31
- package/types/builder.ts +1 -1
- package/types/database.ts +69 -0
- package/types/index.ts +3 -0
- package/types/model-builder.ts +132 -0
- package/types/query-builder.ts +0 -1
- package/types/query-methods.ts +0 -1
- package/types/schema.ts +92 -0
- package/types/utils.ts +1 -40
- package/dist/stubs/stubs/model-ts.stub +0 -5
- /package/dist/stubs/{stubs/arquebus.config-js.stub → arquebus.config-js.stub} +0 -0
- /package/dist/stubs/{stubs/arquebus.config-ts.stub → arquebus.config-ts.stub} +0 -0
- /package/dist/stubs/{stubs/model-js.stub → model-js.stub} +0 -0
- /package/dist/stubs/{stubs/seeder-js.stub → seeder-js.stub} +0 -0
- /package/dist/stubs/{stubs/seeder-ts.stub → seeder-ts.stub} +0 -0
package/bin/index.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import
|
|
5
|
-
import resolveFrom from "resolve-from";
|
|
2
|
+
import { FileSystem, Logger, TaskManager, importFile } from "@h3ravel/shared";
|
|
3
|
+
import { Command, Kernel } from "@h3ravel/musket";
|
|
4
|
+
import { Arr, Obj, Str, data_get, data_set } from "@h3ravel/support";
|
|
6
5
|
import fs, { access, copyFile, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
|
7
|
-
import
|
|
6
|
+
import path from "path";
|
|
7
|
+
import path$1, { dirname } from "node:path";
|
|
8
|
+
import { existsSync } from "node:fs";
|
|
8
9
|
import { fileURLToPath } from "node:url";
|
|
9
|
-
import
|
|
10
|
-
import
|
|
11
|
-
import
|
|
12
|
-
import collect, { Collection, collect as collect$1 } from "collect.js";
|
|
10
|
+
import * as dayjsModule from "dayjs";
|
|
11
|
+
import * as advancedFormatModule from "dayjs/plugin/advancedFormat.js";
|
|
12
|
+
import { Collection, collect } from "@h3ravel/collect.js";
|
|
13
13
|
import Knex from "knex";
|
|
14
|
-
import { existsSync } from "fs";
|
|
14
|
+
import { existsSync as existsSync$1 } from "fs";
|
|
15
15
|
import pluralize from "pluralize";
|
|
16
|
-
import
|
|
16
|
+
import resolveFrom from "resolve-from";
|
|
17
17
|
import { config } from "dotenv";
|
|
18
18
|
//#region \0rolldown/runtime.js
|
|
19
19
|
var __defProp = Object.defineProperty;
|
|
@@ -27,39 +27,168 @@ var __exportAll = (all, no_symbols) => {
|
|
|
27
27
|
return target;
|
|
28
28
|
};
|
|
29
29
|
//#endregion
|
|
30
|
-
//#region src/cli/
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
const packageJson = path.join(packageName, "package.json");
|
|
39
|
-
const resolved = resolveFrom.silent(cwd ?? process.cwd(), packageJson);
|
|
40
|
-
if (!resolved) return;
|
|
41
|
-
return path.join(path.dirname(resolved), parts.join("/"));
|
|
30
|
+
//#region src/cli/commands.ts
|
|
31
|
+
var ArquebusCommand = class extends Command {
|
|
32
|
+
pathOption(signature) {
|
|
33
|
+
return signature.option("path", {
|
|
34
|
+
short: "p",
|
|
35
|
+
optionalValue: true,
|
|
36
|
+
description: "The path used by the command."
|
|
37
|
+
});
|
|
42
38
|
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
39
|
+
};
|
|
40
|
+
var InitCommand = class extends ArquebusCommand {
|
|
41
|
+
buildSignature(signature) {
|
|
42
|
+
return signature.command("init").describe("Create a fresh Arquebus config.").argument("type", {
|
|
43
|
+
required: false,
|
|
44
|
+
default: "js",
|
|
45
|
+
choices: ["js", "ts"],
|
|
46
|
+
description: "Type of config to generate."
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
async handle() {
|
|
50
|
+
await this.app.initialize(this.argument("type", "js"));
|
|
46
51
|
}
|
|
47
52
|
};
|
|
48
|
-
var
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
}
|
|
60
|
-
|
|
53
|
+
var MakeMigrationCommand = class extends ArquebusCommand {
|
|
54
|
+
buildSignature(signature) {
|
|
55
|
+
return this.pathOption(signature.command("make:migration").describe("Create a new migration file.").argument("name", { description: "The migration name." }).option("type", {
|
|
56
|
+
short: "l",
|
|
57
|
+
default: "js",
|
|
58
|
+
choices: ["js", "ts"],
|
|
59
|
+
description: "Type of migration file to generate."
|
|
60
|
+
}).option("table", {
|
|
61
|
+
short: "t",
|
|
62
|
+
optionalValue: true,
|
|
63
|
+
description: "The table to migrate."
|
|
64
|
+
}).option("create", {
|
|
65
|
+
short: "c",
|
|
66
|
+
optionalValue: true,
|
|
67
|
+
description: "The table to create."
|
|
68
|
+
}));
|
|
69
|
+
}
|
|
70
|
+
async handle() {
|
|
71
|
+
await this.app.makeMigration(this.argument("name"), this.options());
|
|
61
72
|
}
|
|
62
73
|
};
|
|
74
|
+
var PublishMigrationsCommand = class extends ArquebusCommand {
|
|
75
|
+
buildSignature(signature) {
|
|
76
|
+
return this.pathOption(signature.command("migrate:publish").describe("Publish migration files from a package.").argument("package", { description: "The package to publish from." }));
|
|
77
|
+
}
|
|
78
|
+
async handle() {
|
|
79
|
+
await this.app.publishMigrations(this.argument("package"), this.options());
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
var MigrationPathCommand = class extends ArquebusCommand {
|
|
83
|
+
buildSignature(signature) {
|
|
84
|
+
return this.pathOption(signature.command(this.commandName).describe(this.commandDescription));
|
|
85
|
+
}
|
|
86
|
+
async handle() {
|
|
87
|
+
await this.execute(this.options());
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
var MigrateCommand = class extends ArquebusCommand {
|
|
91
|
+
buildSignature(signature) {
|
|
92
|
+
return this.pathOption(signature.command("migrate").describe("Run all pending migrations.").option("step", {
|
|
93
|
+
short: "s",
|
|
94
|
+
optionalValue: true,
|
|
95
|
+
description: "Run migrations in individual batches."
|
|
96
|
+
}));
|
|
97
|
+
}
|
|
98
|
+
async handle() {
|
|
99
|
+
await this.app.migrate(this.options());
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
var RollbackCommand = class extends ArquebusCommand {
|
|
103
|
+
buildSignature(signature) {
|
|
104
|
+
return this.pathOption(signature.command("migrate:rollback").describe("Rollback the last database migration.").option("step", {
|
|
105
|
+
short: "s",
|
|
106
|
+
optionalValue: true,
|
|
107
|
+
description: "The number of migrations to revert."
|
|
108
|
+
}));
|
|
109
|
+
}
|
|
110
|
+
async handle() {
|
|
111
|
+
await this.app.rollback(this.options());
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
var ResetCommand = class extends MigrationPathCommand {
|
|
115
|
+
commandName = "migrate:reset";
|
|
116
|
+
commandDescription = "Rollback all database migrations.";
|
|
117
|
+
execute(options) {
|
|
118
|
+
return this.app.reset(options);
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
var RefreshCommand = class extends MigrationPathCommand {
|
|
122
|
+
commandName = "migrate:refresh";
|
|
123
|
+
commandDescription = "Reset and re-run all migrations.";
|
|
124
|
+
execute(options) {
|
|
125
|
+
return this.app.refresh(options);
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
var FreshCommand = class extends MigrationPathCommand {
|
|
129
|
+
commandName = "migrate:fresh";
|
|
130
|
+
commandDescription = "Drop all tables and re-run all migrations.";
|
|
131
|
+
execute(options) {
|
|
132
|
+
return this.app.fresh(options);
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
var MigrationStatusCommand = class extends MigrationPathCommand {
|
|
136
|
+
commandName = "migrate:status";
|
|
137
|
+
commandDescription = "Show the status of each migration.";
|
|
138
|
+
execute(options) {
|
|
139
|
+
return this.app.status(options);
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
var SeedCommand = class extends MigrationPathCommand {
|
|
143
|
+
commandName = "db:seed";
|
|
144
|
+
commandDescription = "Run database seeders.";
|
|
145
|
+
execute(options) {
|
|
146
|
+
return this.app.seed(options);
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
var MakeFileCommand = class extends ArquebusCommand {
|
|
150
|
+
buildSignature(signature) {
|
|
151
|
+
return this.pathOption(signature.command(this.commandName).describe(this.commandDescription).argument("name", { description: `The ${this.fileDescription} name.` }).option("type", {
|
|
152
|
+
short: "l",
|
|
153
|
+
default: "js",
|
|
154
|
+
choices: ["js", "ts"],
|
|
155
|
+
description: `Type of ${this.fileDescription} file to generate.`
|
|
156
|
+
}).option("force", { description: `Overwrite an existing ${this.fileDescription} file.` }));
|
|
157
|
+
}
|
|
158
|
+
async handle() {
|
|
159
|
+
await this.execute(this.argument("name"), this.options());
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
var MakeSeederCommand = class extends MakeFileCommand {
|
|
163
|
+
commandName = "make:seeder";
|
|
164
|
+
commandDescription = "Create a new seeder file.";
|
|
165
|
+
fileDescription = "seeder";
|
|
166
|
+
execute(name, options) {
|
|
167
|
+
return this.app.makeSeeder(name, options);
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
var MakeModelCommand = class extends MakeFileCommand {
|
|
171
|
+
commandName = "make:model";
|
|
172
|
+
commandDescription = "Create a new model file.";
|
|
173
|
+
fileDescription = "model";
|
|
174
|
+
execute(name, options) {
|
|
175
|
+
return this.app.makeModel(name, options);
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
const ArquebusCommands = [
|
|
179
|
+
InitCommand,
|
|
180
|
+
MakeMigrationCommand,
|
|
181
|
+
PublishMigrationsCommand,
|
|
182
|
+
MigrateCommand,
|
|
183
|
+
RollbackCommand,
|
|
184
|
+
ResetCommand,
|
|
185
|
+
RefreshCommand,
|
|
186
|
+
FreshCommand,
|
|
187
|
+
MigrationStatusCommand,
|
|
188
|
+
SeedCommand,
|
|
189
|
+
MakeSeederCommand,
|
|
190
|
+
MakeModelCommand
|
|
191
|
+
];
|
|
63
192
|
//#endregion
|
|
64
193
|
//#region src/migrations/migration-repository.ts
|
|
65
194
|
var MigrationRepository = class {
|
|
@@ -206,8 +335,7 @@ var CockroachDB = class {
|
|
|
206
335
|
*/
|
|
207
336
|
async hasTable(table) {
|
|
208
337
|
const subquery = this.knex.select().from("information_schema.tables").whereIn("table_schema", this.explodedSchema).andWhere({ table_name: table });
|
|
209
|
-
|
|
210
|
-
return (record === null || record === void 0 ? void 0 : record.exists) || false;
|
|
338
|
+
return (await this.knex.select(this.knex.raw("exists (?)", [subquery])).first())?.exists || false;
|
|
211
339
|
}
|
|
212
340
|
/**
|
|
213
341
|
* Get all the available columns in the current schema/database. Can be filtered to a specific table
|
|
@@ -307,18 +435,17 @@ var CockroachDB = class {
|
|
|
307
435
|
${column ? "AND att.attname = ?" : ""}
|
|
308
436
|
`, bindings)]);
|
|
309
437
|
const parsedColumms = columns.rows.map((col) => {
|
|
310
|
-
var _col$default_value;
|
|
311
438
|
const constraintsForColumn = constraints.rows.filter((constraint) => constraint.table === col.table && constraint.column === col.name);
|
|
312
439
|
const foreignKeyConstraint = constraintsForColumn.find((constraint) => constraint.type === "f");
|
|
313
440
|
return {
|
|
314
441
|
...col,
|
|
315
442
|
is_unique: constraintsForColumn.some((constraint) => ["u", "p"].includes(constraint.type)),
|
|
316
443
|
is_primary_key: constraintsForColumn.some((constraint) => constraint.type === "p"),
|
|
317
|
-
has_auto_increment: ["integer", "bigint"].includes(col.data_type) && (
|
|
444
|
+
has_auto_increment: ["integer", "bigint"].includes(col.data_type) && (col.default_value?.startsWith("nextval(") ?? false),
|
|
318
445
|
default_value: parseDefaultValue$5(col.default_value),
|
|
319
|
-
foreign_key_schema:
|
|
320
|
-
foreign_key_table:
|
|
321
|
-
foreign_key_column:
|
|
446
|
+
foreign_key_schema: foreignKeyConstraint?.foreign_key_schema ?? null,
|
|
447
|
+
foreign_key_table: foreignKeyConstraint?.foreign_key_table ?? null,
|
|
448
|
+
foreign_key_column: foreignKeyConstraint?.foreign_key_column ?? null
|
|
322
449
|
};
|
|
323
450
|
});
|
|
324
451
|
if (table && column) return parsedColumms[0];
|
|
@@ -332,8 +459,7 @@ var CockroachDB = class {
|
|
|
332
459
|
table_name: table,
|
|
333
460
|
column_name: column
|
|
334
461
|
});
|
|
335
|
-
|
|
336
|
-
return (record === null || record === void 0 ? void 0 : record.exists) || false;
|
|
462
|
+
return (await this.knex.select(this.knex.raw("exists (?)", [subquery])).first())?.exists || false;
|
|
337
463
|
}
|
|
338
464
|
/**
|
|
339
465
|
* Get the primary key column for the given table
|
|
@@ -645,14 +771,13 @@ var MSSQL = class {
|
|
|
645
771
|
WHERE
|
|
646
772
|
OBJECT_SCHEMA_NAME (f.parent_object_id) = ?;
|
|
647
773
|
`, [this.schema]);
|
|
648
|
-
if (table) return result
|
|
774
|
+
if (table) return result?.filter((row) => row.table === table);
|
|
649
775
|
return result;
|
|
650
776
|
}
|
|
651
777
|
};
|
|
652
778
|
//#endregion
|
|
653
779
|
//#region src/inspector/dialects/mysql.ts
|
|
654
780
|
function rawColumnToColumn$1(rawColumn) {
|
|
655
|
-
var _rawColumn$EXTRA;
|
|
656
781
|
let dataType = rawColumn.COLUMN_TYPE.replace(/\(.*?\)/, "");
|
|
657
782
|
if (rawColumn.COLUMN_TYPE.startsWith("tinyint(1)")) dataType = "boolean";
|
|
658
783
|
return {
|
|
@@ -665,7 +790,7 @@ function rawColumnToColumn$1(rawColumn) {
|
|
|
665
790
|
max_length: rawColumn.CHARACTER_MAXIMUM_LENGTH,
|
|
666
791
|
numeric_precision: rawColumn.NUMERIC_PRECISION,
|
|
667
792
|
numeric_scale: rawColumn.NUMERIC_SCALE,
|
|
668
|
-
is_generated: !!
|
|
793
|
+
is_generated: !!rawColumn.EXTRA?.endsWith("GENERATED"),
|
|
669
794
|
is_nullable: rawColumn.IS_NULLABLE === "YES",
|
|
670
795
|
is_unique: rawColumn.COLUMN_KEY === "UNI",
|
|
671
796
|
is_primary_key: rawColumn.CONSTRAINT_NAME === "PRIMARY" || rawColumn.COLUMN_KEY === "PRI",
|
|
@@ -858,11 +983,10 @@ var oracleDB = class {
|
|
|
858
983
|
* Check if a table exists in the current schema/database
|
|
859
984
|
*/
|
|
860
985
|
async hasTable(table) {
|
|
861
|
-
|
|
986
|
+
return !!(await this.knex.select(this.knex.raw(`
|
|
862
987
|
/*+ OPTIMIZER_FEATURES_ENABLE('${OPTIMIZER_FEATURES}') */
|
|
863
988
|
COUNT(*) "count"
|
|
864
|
-
`)).from("USER_TABLES").where({ TABLE_NAME: table }).first();
|
|
865
|
-
return !!(result === null || result === void 0 ? void 0 : result.count);
|
|
989
|
+
`)).from("USER_TABLES").where({ TABLE_NAME: table }).first())?.count;
|
|
866
990
|
}
|
|
867
991
|
/**
|
|
868
992
|
* Get all the available columns in the current schema/database. Can be filtered to a specific table
|
|
@@ -938,15 +1062,14 @@ var oracleDB = class {
|
|
|
938
1062
|
* Check if a table exists in the current schema/database
|
|
939
1063
|
*/
|
|
940
1064
|
async hasColumn(table, column) {
|
|
941
|
-
|
|
1065
|
+
return !!(await this.knex.select(this.knex.raw(`
|
|
942
1066
|
/*+ OPTIMIZER_FEATURES_ENABLE('${OPTIMIZER_FEATURES}') NO_QUERY_TRANSFORMATION */
|
|
943
1067
|
COUNT(*) "count"
|
|
944
1068
|
`)).from("USER_TAB_COLS").where({
|
|
945
1069
|
TABLE_NAME: table,
|
|
946
1070
|
COLUMN_NAME: column,
|
|
947
1071
|
HIDDEN_COLUMN: "NO"
|
|
948
|
-
}).first();
|
|
949
|
-
return !!(result === null || result === void 0 ? void 0 : result.count);
|
|
1072
|
+
}).first())?.count;
|
|
950
1073
|
}
|
|
951
1074
|
/**
|
|
952
1075
|
* Get the primary key column for the given table
|
|
@@ -1112,13 +1235,12 @@ var Postgres = class {
|
|
|
1112
1235
|
`, bindings)).rows;
|
|
1113
1236
|
}
|
|
1114
1237
|
async columnInfo(table, column) {
|
|
1115
|
-
var _versionResponse$rows;
|
|
1116
1238
|
const { knex } = this;
|
|
1117
1239
|
const bindings = [];
|
|
1118
1240
|
if (table) bindings.push(table);
|
|
1119
1241
|
if (column) bindings.push(column);
|
|
1120
1242
|
const schemaIn = this.explodedSchema.map((schemaName) => `${this.knex.raw("?", [schemaName])}::regnamespace`);
|
|
1121
|
-
const majorVersion = (
|
|
1243
|
+
const majorVersion = (await this.knex.raw("SHOW server_version")).rows?.[0]?.server_version?.split(".")?.[0] ?? 10;
|
|
1122
1244
|
let generationSelect = `
|
|
1123
1245
|
NULL AS generation_expression,
|
|
1124
1246
|
pg_get_expr(ad.adbin, ad.adrelid) AS default_value,
|
|
@@ -1210,9 +1332,9 @@ var Postgres = class {
|
|
|
1210
1332
|
is_primary_key: constraintsForColumn.some((constraint) => constraint.type === "p"),
|
|
1211
1333
|
has_auto_increment: constraintsForColumn.some((constraint) => constraint.has_auto_increment),
|
|
1212
1334
|
default_value: parseDefaultValue$1(col.default_value),
|
|
1213
|
-
foreign_key_schema:
|
|
1214
|
-
foreign_key_table:
|
|
1215
|
-
foreign_key_column:
|
|
1335
|
+
foreign_key_schema: foreignKeyConstraint?.foreign_key_schema ?? null,
|
|
1336
|
+
foreign_key_table: foreignKeyConstraint?.foreign_key_table ?? null,
|
|
1337
|
+
foreign_key_column: foreignKeyConstraint?.foreign_key_column ?? null
|
|
1216
1338
|
};
|
|
1217
1339
|
});
|
|
1218
1340
|
if (table && column) return parsedColumms[0];
|
|
@@ -1384,16 +1506,14 @@ var SeederRunner = class {
|
|
|
1384
1506
|
this.resolver = resolver;
|
|
1385
1507
|
}
|
|
1386
1508
|
path(p) {
|
|
1387
|
-
this.paths = Array.from(new Set([...this.paths, p]));
|
|
1509
|
+
this.paths = Array.from(/* @__PURE__ */ new Set([...this.paths, p]));
|
|
1388
1510
|
}
|
|
1389
1511
|
getPaths() {
|
|
1390
1512
|
return this.paths;
|
|
1391
1513
|
}
|
|
1392
1514
|
resolveConnection(connection) {
|
|
1393
|
-
var _getInstance, _ref, _instance$connections;
|
|
1394
1515
|
const name = connection || this.connection || "default";
|
|
1395
|
-
|
|
1396
|
-
if (!!!(instance === null || instance === void 0 || (_instance$connections = instance.connections) === null || _instance$connections === void 0 ? void 0 : _instance$connections[name])) this.resolver.autoLoad().catch(() => {
|
|
1516
|
+
if (!!!(this.resolver.getInstance?.() ?? null)?.connections?.[name]) this.resolver.autoLoad().catch(() => {
|
|
1397
1517
|
/** noop */
|
|
1398
1518
|
});
|
|
1399
1519
|
return this.resolver.fire(name);
|
|
@@ -1431,9 +1551,6 @@ var SeederRunner = class {
|
|
|
1431
1551
|
}
|
|
1432
1552
|
};
|
|
1433
1553
|
//#endregion
|
|
1434
|
-
//#region src/seeders/index.ts
|
|
1435
|
-
var seeders_exports = /* @__PURE__ */ __exportAll({ SeederRunner: () => SeederRunner });
|
|
1436
|
-
//#endregion
|
|
1437
1554
|
//#region src/casts/attribute.ts
|
|
1438
1555
|
var Attribute = class Attribute {
|
|
1439
1556
|
get;
|
|
@@ -1483,7 +1600,7 @@ var ModelNotFoundError = class extends BaseError {
|
|
|
1483
1600
|
}
|
|
1484
1601
|
setModel(model, ids = []) {
|
|
1485
1602
|
this.model = model;
|
|
1486
|
-
this.ids = isArray(ids) ? ids : [ids];
|
|
1603
|
+
this.ids = Array.isArray(ids) ? ids : [ids];
|
|
1487
1604
|
this.message = `No query results for model [${model}]`;
|
|
1488
1605
|
if (this.ids.length > 0) this.message += " " + this.ids.join(", ");
|
|
1489
1606
|
else this.message += ".";
|
|
@@ -1574,25 +1691,29 @@ function compose$1(Base, ...mixins) {
|
|
|
1574
1691
|
}, Base);
|
|
1575
1692
|
}
|
|
1576
1693
|
//#endregion
|
|
1577
|
-
//#region src/
|
|
1694
|
+
//#region src/dayjs.ts
|
|
1695
|
+
const dayjs = dayjsModule.default ?? dayjsModule;
|
|
1696
|
+
const advancedFormat = advancedFormatModule.default ?? advancedFormatModule;
|
|
1578
1697
|
dayjs.extend(advancedFormat);
|
|
1698
|
+
//#endregion
|
|
1699
|
+
//#region src/utils.ts
|
|
1579
1700
|
const getRelationName = (relationMethod) => {
|
|
1580
|
-
return snake(relationMethod.substring(8));
|
|
1701
|
+
return Str.snake(relationMethod.substring(8));
|
|
1581
1702
|
};
|
|
1582
1703
|
const getRelationMethod = (relation) => {
|
|
1583
|
-
return camel(`relation_${relation}`);
|
|
1704
|
+
return Str.camel(`relation_${relation}`);
|
|
1584
1705
|
};
|
|
1585
1706
|
const getScopeMethod = (scope) => {
|
|
1586
|
-
return camel(`scope_${scope}`);
|
|
1707
|
+
return Str.camel(`scope_${scope}`);
|
|
1587
1708
|
};
|
|
1588
1709
|
const getAttrMethod = (attr) => {
|
|
1589
|
-
return camel(`attribute_${attr}`);
|
|
1710
|
+
return Str.camel(`attribute_${attr}`);
|
|
1590
1711
|
};
|
|
1591
1712
|
const getGetterMethod = (attr) => {
|
|
1592
|
-
return camel(`get_${attr}_attribute`);
|
|
1713
|
+
return Str.camel(`get_${attr}_attribute`);
|
|
1593
1714
|
};
|
|
1594
1715
|
const getSetterMethod = (attr) => {
|
|
1595
|
-
return camel(`set_${attr}_attribute`);
|
|
1716
|
+
return Str.camel(`set_${attr}_attribute`);
|
|
1596
1717
|
};
|
|
1597
1718
|
/**
|
|
1598
1719
|
* Tap into a model a collection instance
|
|
@@ -1608,7 +1729,7 @@ const tap = (instance, callback) => {
|
|
|
1608
1729
|
const { compose } = mixin_exports;
|
|
1609
1730
|
const flatten = (arr) => arr.flat();
|
|
1610
1731
|
const flattenDeep = (arr) => Array.isArray(arr) ? arr.reduce((a, b) => a.concat(flattenDeep(b)), []) : [arr];
|
|
1611
|
-
const snakeCase = (str) => trim(snake(str.replace(/[^a-zA-Z0-9_-]/g, "-")), "_-");
|
|
1732
|
+
const snakeCase = (str) => Str.trim(Str.snake(str.replace(/[^a-zA-Z0-9_-]/g, "-")), "_-").replace(/_+/g, "_");
|
|
1612
1733
|
//#endregion
|
|
1613
1734
|
//#region src/relations/relation.ts
|
|
1614
1735
|
var Relation = class {
|
|
@@ -1695,8 +1816,7 @@ var Relation = class {
|
|
|
1695
1816
|
return this.parent.getQualifiedKeyName();
|
|
1696
1817
|
}
|
|
1697
1818
|
getExistenceCompareKey() {
|
|
1698
|
-
|
|
1699
|
-
return (_this$getQualifiedFor = this.getQualifiedForeignKeyName) === null || _this$getQualifiedFor === void 0 ? void 0 : _this$getQualifiedFor.call(this);
|
|
1819
|
+
return this.getQualifiedForeignKeyName?.();
|
|
1700
1820
|
}
|
|
1701
1821
|
};
|
|
1702
1822
|
//#endregion
|
|
@@ -1837,8 +1957,7 @@ const HasAttributes = (Model) => {
|
|
|
1837
1957
|
return this;
|
|
1838
1958
|
}
|
|
1839
1959
|
normalizeCastClassResponse(key, value) {
|
|
1840
|
-
|
|
1841
|
-
return (value === null || value === void 0 || (_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor.name) === "Object" ? value : { [key]: value };
|
|
1960
|
+
return value?.constructor?.name === "Object" ? value : { [key]: value };
|
|
1842
1961
|
}
|
|
1843
1962
|
syncOriginal() {
|
|
1844
1963
|
this.original = this.getAttributes();
|
|
@@ -1963,8 +2082,8 @@ const HasAttributes = (Model) => {
|
|
|
1963
2082
|
attributesToData() {
|
|
1964
2083
|
let attributes = { ...this.attributes };
|
|
1965
2084
|
for (const key in attributes) {
|
|
1966
|
-
if (this.hidden.includes(key)) attributes =
|
|
1967
|
-
if (this.visible.length > 0 && this.visible.includes(key) === false) attributes =
|
|
2085
|
+
if (this.hidden.includes(key)) attributes = Arr.except(attributes, [key]);
|
|
2086
|
+
if (this.visible.length > 0 && this.visible.includes(key) === false) attributes = Arr.except(attributes, [key]);
|
|
1968
2087
|
}
|
|
1969
2088
|
for (const key of this.getDates()) {
|
|
1970
2089
|
if (attributes[key] === void 0) continue;
|
|
@@ -2019,7 +2138,7 @@ const HasAttributes = (Model) => {
|
|
|
2019
2138
|
}
|
|
2020
2139
|
hasCast(key, types = []) {
|
|
2021
2140
|
if (key in this.casts) {
|
|
2022
|
-
types =
|
|
2141
|
+
types = flatten(types);
|
|
2023
2142
|
return types.length > 0 ? types.includes(this.getCastType(key)) : true;
|
|
2024
2143
|
}
|
|
2025
2144
|
return false;
|
|
@@ -2078,10 +2197,14 @@ const HasGlobalScopes = (Model) => {
|
|
|
2078
2197
|
static globalScopes;
|
|
2079
2198
|
static addGlobalScope(scope, implementation = null) {
|
|
2080
2199
|
if (typeof scope === "string" && implementation instanceof Scope) {
|
|
2081
|
-
|
|
2200
|
+
const scopes = this.globalScopes ?? {};
|
|
2201
|
+
data_set(scopes, this.name + "." + scope, implementation);
|
|
2202
|
+
this.globalScopes = scopes;
|
|
2082
2203
|
return implementation;
|
|
2083
2204
|
} else if (scope instanceof Scope) {
|
|
2084
|
-
|
|
2205
|
+
const scopes = this.globalScopes ?? {};
|
|
2206
|
+
data_set(scopes, this.name + "." + scope.constructor.name, scope);
|
|
2207
|
+
this.globalScopes = scopes;
|
|
2085
2208
|
return scope;
|
|
2086
2209
|
}
|
|
2087
2210
|
throw new InvalidArgumentError("Global scope must be an instance of Scope.");
|
|
@@ -2090,8 +2213,8 @@ const HasGlobalScopes = (Model) => {
|
|
|
2090
2213
|
return this.getGlobalScope(scope) !== null;
|
|
2091
2214
|
}
|
|
2092
2215
|
static getGlobalScope(scope) {
|
|
2093
|
-
if (typeof scope === "string") return
|
|
2094
|
-
return
|
|
2216
|
+
if (typeof scope === "string") return data_get(this.globalScopes ?? {}, this.name + "." + scope);
|
|
2217
|
+
return data_get(this.globalScopes ?? {}, this.name + "." + scope.constructor.name);
|
|
2095
2218
|
}
|
|
2096
2219
|
static getAllGlobalScopes() {
|
|
2097
2220
|
return this.globalScopes;
|
|
@@ -2100,7 +2223,7 @@ const HasGlobalScopes = (Model) => {
|
|
|
2100
2223
|
this.globalScopes = scopes;
|
|
2101
2224
|
}
|
|
2102
2225
|
getGlobalScopes() {
|
|
2103
|
-
return
|
|
2226
|
+
return data_get(this.constructor.globalScopes ?? {}, this.constructor.name, {});
|
|
2104
2227
|
}
|
|
2105
2228
|
};
|
|
2106
2229
|
};
|
|
@@ -2271,13 +2394,11 @@ var HasMany = class extends compose(Relation, HasOneOrMany) {
|
|
|
2271
2394
|
return this.getParentKey() !== null ? await this.query.get() : new Collection$1([]);
|
|
2272
2395
|
}
|
|
2273
2396
|
getForeignKeyName() {
|
|
2274
|
-
|
|
2275
|
-
const segments = (_this$foreignKey = this.foreignKey) === null || _this$foreignKey === void 0 ? void 0 : _this$foreignKey.split(".");
|
|
2276
|
-
return segments === null || segments === void 0 ? void 0 : segments.pop();
|
|
2397
|
+
return (this.foreignKey?.split("."))?.pop();
|
|
2277
2398
|
}
|
|
2278
2399
|
buildDictionary(results) {
|
|
2279
2400
|
const foreign = this.getForeignKeyName();
|
|
2280
|
-
return collect
|
|
2401
|
+
return collect(results).mapToDictionary((result) => [result[foreign], result]).all();
|
|
2281
2402
|
}
|
|
2282
2403
|
match(models, results, relation) {
|
|
2283
2404
|
return this.matchOneOrMany(models, results, relation, "many");
|
|
@@ -2308,9 +2429,7 @@ var HasOne = class extends compose(Relation, HasOneOrMany, SupportsDefaultModels
|
|
|
2308
2429
|
return this.matchOneOrMany(models, results, relation, "one");
|
|
2309
2430
|
}
|
|
2310
2431
|
getForeignKeyName() {
|
|
2311
|
-
|
|
2312
|
-
const segments = (_this$foreignKey = this.foreignKey) === null || _this$foreignKey === void 0 ? void 0 : _this$foreignKey.split(".");
|
|
2313
|
-
return segments === null || segments === void 0 ? void 0 : segments.pop();
|
|
2432
|
+
return (this.foreignKey?.split("."))?.pop();
|
|
2314
2433
|
}
|
|
2315
2434
|
async getResults() {
|
|
2316
2435
|
if (this.getParentKey() === null) return this.getDefaultFor(this.parent);
|
|
@@ -2419,10 +2538,10 @@ var HasManyThrough = class extends Relation {
|
|
|
2419
2538
|
}
|
|
2420
2539
|
const model = await this.first(columns);
|
|
2421
2540
|
if (model) return model;
|
|
2422
|
-
return callback
|
|
2541
|
+
return callback?.();
|
|
2423
2542
|
}
|
|
2424
2543
|
async find(id, columns = ["*"]) {
|
|
2425
|
-
if (isArray(id)) return await this.findMany(id, columns);
|
|
2544
|
+
if (Array.isArray(id)) return await this.findMany(id, columns);
|
|
2426
2545
|
return await this.where(this.getRelated().getQualifiedKeyName(), "=", id).first(columns);
|
|
2427
2546
|
}
|
|
2428
2547
|
async findMany(ids, columns = ["*"]) {
|
|
@@ -2450,7 +2569,7 @@ var HasManyThrough = class extends Relation {
|
|
|
2450
2569
|
return await this.query.paginate(perPage ?? 15, columns, pageName, page);
|
|
2451
2570
|
}
|
|
2452
2571
|
shouldSelect(columns = ["*"]) {
|
|
2453
|
-
if (
|
|
2572
|
+
if (columns?.at(0) == "*") columns = [this.related.getTable() + ".*"];
|
|
2454
2573
|
return [...columns, this.getQualifiedFirstKeyName() + " as laravel_through_key"];
|
|
2455
2574
|
}
|
|
2456
2575
|
async chunk(count, callback) {
|
|
@@ -2544,7 +2663,7 @@ const HasRelations = (Model) => {
|
|
|
2544
2663
|
return this;
|
|
2545
2664
|
}
|
|
2546
2665
|
unsetRelation(relation) {
|
|
2547
|
-
this.relations =
|
|
2666
|
+
this.relations = Arr.except(this.relations, [relation]);
|
|
2548
2667
|
return this;
|
|
2549
2668
|
}
|
|
2550
2669
|
relationLoaded(relation) {
|
|
@@ -2567,8 +2686,7 @@ const HasRelations = (Model) => {
|
|
|
2567
2686
|
return data;
|
|
2568
2687
|
}
|
|
2569
2688
|
guessBelongsToRelation() {
|
|
2570
|
-
|
|
2571
|
-
const functionName = (((_e$stack = (/* @__PURE__ */ new Error()).stack) === null || _e$stack === void 0 ? void 0 : _e$stack.split("\n")[2]) ?? "").split(" ")[5];
|
|
2689
|
+
const functionName = ((/* @__PURE__ */ new Error()).stack?.split("\n")[2] ?? "").split(" ")[5];
|
|
2572
2690
|
return getRelationName(functionName);
|
|
2573
2691
|
}
|
|
2574
2692
|
joiningTable(related, instance = null) {
|
|
@@ -2678,7 +2796,7 @@ const HidesAttributes = (Model) => {
|
|
|
2678
2796
|
makeVisible(...keys) {
|
|
2679
2797
|
const visible = flattenDeep(keys);
|
|
2680
2798
|
if (this.visible.length > 0) this.visible = [...this.visible, ...visible];
|
|
2681
|
-
this.hidden =
|
|
2799
|
+
this.hidden = collect(this.hidden).diff(visible).all();
|
|
2682
2800
|
return this;
|
|
2683
2801
|
}
|
|
2684
2802
|
makeHidden(key, ...keys) {
|
|
@@ -2822,10 +2940,9 @@ var QueryBuilder = class QueryBuilder extends Inference$1 {
|
|
|
2822
2940
|
asProxy() {
|
|
2823
2941
|
return new Proxy(this, {
|
|
2824
2942
|
get: function(target, prop) {
|
|
2825
|
-
var _target$connector$cli;
|
|
2826
2943
|
if (typeof target[prop] !== "undefined") return target[prop];
|
|
2827
2944
|
if (["destroy", "schema"].includes(prop)) return target.connector.schema;
|
|
2828
|
-
const skipReturning = !!
|
|
2945
|
+
const skipReturning = !!target.connector.client.config?.client?.includes("mysql") && prop === "returning";
|
|
2829
2946
|
if ([
|
|
2830
2947
|
"select",
|
|
2831
2948
|
"from",
|
|
@@ -3028,6 +3145,9 @@ var arquebus = class arquebus {
|
|
|
3028
3145
|
if (this.instance === null) this.instance = new arquebus();
|
|
3029
3146
|
return this.instance;
|
|
3030
3147
|
}
|
|
3148
|
+
static withSchema() {
|
|
3149
|
+
return this;
|
|
3150
|
+
}
|
|
3031
3151
|
/**
|
|
3032
3152
|
* Initialize a new database connection
|
|
3033
3153
|
*
|
|
@@ -3116,13 +3236,13 @@ var arquebus = class arquebus {
|
|
|
3116
3236
|
const jsPath = path.resolve("arquebus.config.js");
|
|
3117
3237
|
const tsPath = path.resolve("arquebus.config.ts");
|
|
3118
3238
|
const instance = this.getInstance();
|
|
3119
|
-
if (existsSync(jsPath)) {
|
|
3120
|
-
config = (await
|
|
3239
|
+
if (existsSync$1(jsPath)) {
|
|
3240
|
+
config = (await importFile(jsPath)).default;
|
|
3121
3241
|
if (addConnection) instance.addConnection(config, config.client);
|
|
3122
3242
|
return config;
|
|
3123
3243
|
}
|
|
3124
|
-
if (existsSync(tsPath)) if (process.env.NODE_ENV !== "production") {
|
|
3125
|
-
config = (await
|
|
3244
|
+
if (existsSync$1(tsPath)) if (process.env.NODE_ENV !== "production") {
|
|
3245
|
+
config = (await importFile(tsPath)).default;
|
|
3126
3246
|
if (addConnection) instance.addConnection(config, config.client);
|
|
3127
3247
|
return config;
|
|
3128
3248
|
} else throw new Error("arquebus.config.ts found in production without build step");
|
|
@@ -3138,7 +3258,7 @@ var arquebus = class arquebus {
|
|
|
3138
3258
|
"cjs"
|
|
3139
3259
|
], dir);
|
|
3140
3260
|
if (found) if (!found.endsWith(".ts") || process.env.NODE_ENV !== "production") {
|
|
3141
|
-
config = (await
|
|
3261
|
+
config = (await importFile(found)).default;
|
|
3142
3262
|
if (addConnection) instance.addConnection(config, config.client);
|
|
3143
3263
|
return config;
|
|
3144
3264
|
} else throw new Error("arquebus.config.ts found in production without build step");
|
|
@@ -3159,7 +3279,7 @@ var arquebus = class arquebus {
|
|
|
3159
3279
|
}
|
|
3160
3280
|
async destroyAll() {
|
|
3161
3281
|
await Promise.all(Object.values(this.manager).map((connection) => {
|
|
3162
|
-
return connection
|
|
3282
|
+
return connection?.destroy();
|
|
3163
3283
|
}));
|
|
3164
3284
|
}
|
|
3165
3285
|
createModel(name, options = {}) {
|
|
@@ -3168,29 +3288,25 @@ var arquebus = class arquebus {
|
|
|
3168
3288
|
this.models = {
|
|
3169
3289
|
...this.models,
|
|
3170
3290
|
[name]: class extends BaseModel {
|
|
3171
|
-
table =
|
|
3172
|
-
connection =
|
|
3173
|
-
timestamps =
|
|
3174
|
-
primaryKey =
|
|
3175
|
-
keyType =
|
|
3176
|
-
incrementing =
|
|
3177
|
-
with =
|
|
3178
|
-
casts =
|
|
3179
|
-
static CREATED_AT =
|
|
3180
|
-
static UPDATED_AT =
|
|
3181
|
-
static DELETED_AT =
|
|
3291
|
+
table = options?.table ?? null;
|
|
3292
|
+
connection = options?.connection ?? null;
|
|
3293
|
+
timestamps = options?.timestamps ?? true;
|
|
3294
|
+
primaryKey = options?.primaryKey ?? "id";
|
|
3295
|
+
keyType = options?.keyType ?? "int";
|
|
3296
|
+
incrementing = options?.incrementing ?? true;
|
|
3297
|
+
with = options?.with ?? [];
|
|
3298
|
+
casts = options?.casts ?? {};
|
|
3299
|
+
static CREATED_AT = options?.CREATED_AT ?? "created_at";
|
|
3300
|
+
static UPDATED_AT = options?.UPDATED_AT ?? "updated_at";
|
|
3301
|
+
static DELETED_AT = options?.DELETED_AT ?? "deleted_at";
|
|
3182
3302
|
}
|
|
3183
3303
|
};
|
|
3184
3304
|
if ("attributes" in options) for (const attribute in options.attributes) {
|
|
3185
3305
|
if (options.attributes[attribute] instanceof Attribute === false) throw new Error("Attribute must be an instance of \"Attribute\"");
|
|
3186
|
-
this.models[name].prototype[getAttrMethod(attribute)] = () =>
|
|
3187
|
-
var _options$attributes;
|
|
3188
|
-
return (_options$attributes = options.attributes) === null || _options$attributes === void 0 ? void 0 : _options$attributes[attribute];
|
|
3189
|
-
};
|
|
3306
|
+
this.models[name].prototype[getAttrMethod(attribute)] = () => options.attributes?.[attribute];
|
|
3190
3307
|
}
|
|
3191
3308
|
if ("relations" in options) for (const relation in options.relations) this.models[name].prototype[getRelationMethod(relation)] = function() {
|
|
3192
|
-
|
|
3193
|
-
return (_options$relations = options.relations) === null || _options$relations === void 0 ? void 0 : _options$relations[relation](this);
|
|
3309
|
+
return options.relations?.[relation](this);
|
|
3194
3310
|
};
|
|
3195
3311
|
if ("scopes" in options) for (const scope in options.scopes) this.models[name].prototype[getScopeMethod(scope)] = options.scopes[scope];
|
|
3196
3312
|
this.models[name].setConnectionResolver(this);
|
|
@@ -3228,6 +3344,9 @@ var Model = class Model extends BaseModel {
|
|
|
3228
3344
|
this.buildRelationships(attributes);
|
|
3229
3345
|
return this.asProxy();
|
|
3230
3346
|
}
|
|
3347
|
+
static define() {
|
|
3348
|
+
return this;
|
|
3349
|
+
}
|
|
3231
3350
|
static query(trx = null) {
|
|
3232
3351
|
return new this().newQuery(trx);
|
|
3233
3352
|
}
|
|
@@ -3411,7 +3530,7 @@ var Model = class Model extends BaseModel {
|
|
|
3411
3530
|
});
|
|
3412
3531
|
}
|
|
3413
3532
|
toData() {
|
|
3414
|
-
return
|
|
3533
|
+
return Obj.deepMerge(this.attributesToData(), this.relationsToData());
|
|
3415
3534
|
}
|
|
3416
3535
|
toJSON() {
|
|
3417
3536
|
return this.toData();
|
|
@@ -3422,6 +3541,15 @@ var Model = class Model extends BaseModel {
|
|
|
3422
3541
|
toString() {
|
|
3423
3542
|
return this.toJson();
|
|
3424
3543
|
}
|
|
3544
|
+
getAttributes() {
|
|
3545
|
+
return super.getAttributes();
|
|
3546
|
+
}
|
|
3547
|
+
getAttribute(key) {
|
|
3548
|
+
return super.getAttribute(key);
|
|
3549
|
+
}
|
|
3550
|
+
setAttribute(key, value) {
|
|
3551
|
+
return super.setAttribute(key, value);
|
|
3552
|
+
}
|
|
3425
3553
|
fill(attributes) {
|
|
3426
3554
|
for (const key in attributes) this.setAttribute(key, attributes[key]);
|
|
3427
3555
|
return this;
|
|
@@ -3462,10 +3590,9 @@ var Model = class Model extends BaseModel {
|
|
|
3462
3590
|
if (this.usesTimestamps()) this.updateTimestamps();
|
|
3463
3591
|
const attributes = this.getAttributes();
|
|
3464
3592
|
if (this.getIncrementing()) {
|
|
3465
|
-
var _data$;
|
|
3466
3593
|
const keyName = this.getKeyName();
|
|
3467
3594
|
const data = await query.insert([attributes], [keyName]);
|
|
3468
|
-
this.setAttribute(keyName,
|
|
3595
|
+
this.setAttribute(keyName, data[0]?.[keyName] || data[0]);
|
|
3469
3596
|
} else if (Object.keys(attributes).length > 0) await query.insert(attributes);
|
|
3470
3597
|
this.exists = true;
|
|
3471
3598
|
await this.execHooks("created", options);
|
|
@@ -3571,7 +3698,7 @@ var Pivot = class extends Model {
|
|
|
3571
3698
|
};
|
|
3572
3699
|
//#endregion
|
|
3573
3700
|
//#region src/collection.ts
|
|
3574
|
-
var Collection$1 = class
|
|
3701
|
+
var Collection$1 = class extends Collection {
|
|
3575
3702
|
newConstructor(...args) {
|
|
3576
3703
|
return new (this.getConstructor())(...args);
|
|
3577
3704
|
}
|
|
@@ -3580,17 +3707,18 @@ var Collection$1 = class Collection$1 extends Collection {
|
|
|
3580
3707
|
}
|
|
3581
3708
|
async load(...relations) {
|
|
3582
3709
|
if (this.isNotEmpty()) {
|
|
3583
|
-
const items = await this.first().constructor.query().with(...relations).eagerLoadRelations(this.
|
|
3710
|
+
const items = await this.first().constructor.query().with(...relations).eagerLoadRelations(this.all());
|
|
3584
3711
|
return this.newConstructor(items);
|
|
3585
3712
|
}
|
|
3586
3713
|
return this;
|
|
3587
3714
|
}
|
|
3588
3715
|
async loadAggregate(relations, column, action = null) {
|
|
3589
3716
|
if (this.isEmpty()) return this;
|
|
3590
|
-
const
|
|
3591
|
-
const
|
|
3717
|
+
const first = this.first();
|
|
3718
|
+
const models = (await first.newModelQuery().whereIn(first.getKeyName(), this.modelKeys()).select(first.getKeyName()).withAggregate(relations, column, action).get()).keyBy(first.getKeyName());
|
|
3719
|
+
const attributes = collect(Object.keys(models.first().getAttributes())).diff([models.first().getKeyName()]).all();
|
|
3592
3720
|
this.each((model) => {
|
|
3593
|
-
const extraAttributes =
|
|
3721
|
+
const extraAttributes = Arr.select(models.get(model.getKey()).getAttributes(), attributes);
|
|
3594
3722
|
model.fill(extraAttributes).syncOriginalAttributes(...attributes);
|
|
3595
3723
|
});
|
|
3596
3724
|
return this;
|
|
@@ -3628,20 +3756,21 @@ var Collection$1 = class Collection$1 extends Collection {
|
|
|
3628
3756
|
diff(items) {
|
|
3629
3757
|
const diff = new this.constructor();
|
|
3630
3758
|
const dictionary = this.getDictionary(items);
|
|
3631
|
-
this.
|
|
3759
|
+
this.all().map((item) => {
|
|
3632
3760
|
if (dictionary[item.getKey()] === void 0) diff.add(item);
|
|
3633
3761
|
});
|
|
3634
3762
|
return diff;
|
|
3635
3763
|
}
|
|
3636
|
-
except(keys) {
|
|
3637
|
-
const
|
|
3764
|
+
except(...keys) {
|
|
3765
|
+
const values = keys.length === 1 && Array.isArray(keys[0]) ? keys[0].map(String) : keys.map(String);
|
|
3766
|
+
const dictionary = Arr.except(this.getDictionary(), values);
|
|
3638
3767
|
return new this.constructor(Object.values(dictionary));
|
|
3639
3768
|
}
|
|
3640
3769
|
intersect(items) {
|
|
3641
3770
|
const intersect = new this.constructor();
|
|
3642
|
-
if (isEmpty(items)) return intersect;
|
|
3771
|
+
if (Arr.isEmpty(items)) return intersect;
|
|
3643
3772
|
const dictionary = this.getDictionary(items);
|
|
3644
|
-
for (const item of this.
|
|
3773
|
+
for (const item of this.all()) if (dictionary[item.getKey()] !== void 0) intersect.add(item);
|
|
3645
3774
|
return intersect;
|
|
3646
3775
|
}
|
|
3647
3776
|
unique(key, _strict = false) {
|
|
@@ -3650,20 +3779,21 @@ var Collection$1 = class Collection$1 extends Collection {
|
|
|
3650
3779
|
}
|
|
3651
3780
|
find(key, defaultValue = null) {
|
|
3652
3781
|
if (key instanceof Model) key = key.getKey();
|
|
3653
|
-
if (isArray(key)) {
|
|
3782
|
+
if (Array.isArray(key)) {
|
|
3654
3783
|
if (this.isEmpty()) return new this.constructor();
|
|
3655
3784
|
return this.whereIn(this.first().getKeyName(), key);
|
|
3656
3785
|
}
|
|
3657
|
-
collect
|
|
3786
|
+
collect(this.all()).first((model) => {
|
|
3658
3787
|
return model.getKey() == key;
|
|
3659
3788
|
});
|
|
3660
|
-
return this.
|
|
3789
|
+
return this.all().filter((model) => {
|
|
3661
3790
|
return model.getKey() == key;
|
|
3662
3791
|
})[0] || defaultValue;
|
|
3663
3792
|
}
|
|
3664
3793
|
async fresh(...args) {
|
|
3665
3794
|
if (this.isEmpty()) return new this.constructor();
|
|
3666
3795
|
const model = this.first();
|
|
3796
|
+
if (!model) return new this.constructor();
|
|
3667
3797
|
const freshModels = (await model.newQuery().with(...args).whereIn(model.getKeyName(), this.modelKeys()).get()).getDictionary();
|
|
3668
3798
|
return this.filter((model) => {
|
|
3669
3799
|
return model.exists && freshModels[model.getKey()] !== void 0;
|
|
@@ -3686,15 +3816,15 @@ var Collection$1 = class Collection$1 extends Collection {
|
|
|
3686
3816
|
item.append(attributes);
|
|
3687
3817
|
});
|
|
3688
3818
|
}
|
|
3689
|
-
only(keys) {
|
|
3690
|
-
|
|
3691
|
-
const dictionary =
|
|
3819
|
+
only(...keys) {
|
|
3820
|
+
const values = keys.length === 1 && Array.isArray(keys[0]) ? keys[0].map(String) : keys.map(String);
|
|
3821
|
+
const dictionary = Arr.select(this.getDictionary(), values);
|
|
3692
3822
|
return new this.constructor(Object.values(dictionary));
|
|
3693
3823
|
}
|
|
3694
3824
|
getDictionary(items) {
|
|
3695
|
-
|
|
3825
|
+
const values = !items ? this.all() : items instanceof Collection ? items.all() : items;
|
|
3696
3826
|
const dictionary = {};
|
|
3697
|
-
|
|
3827
|
+
values.map((value) => {
|
|
3698
3828
|
dictionary[value.getKey()] = value;
|
|
3699
3829
|
});
|
|
3700
3830
|
return dictionary;
|
|
@@ -3718,8 +3848,8 @@ var Collection$1 = class Collection$1 extends Collection {
|
|
|
3718
3848
|
return JSON.stringify(this.toData(), ...args);
|
|
3719
3849
|
}
|
|
3720
3850
|
[Symbol.iterator] = () => {
|
|
3721
|
-
const items = this.
|
|
3722
|
-
const length =
|
|
3851
|
+
const items = this.all();
|
|
3852
|
+
const length = items.length;
|
|
3723
3853
|
let n = 0;
|
|
3724
3854
|
return { next() {
|
|
3725
3855
|
return n < length ? {
|
|
@@ -3766,24 +3896,24 @@ const InteractsWithPivotTable = (Relation) => {
|
|
|
3766
3896
|
let records;
|
|
3767
3897
|
const results = await this.getCurrentlyAttachedPivots();
|
|
3768
3898
|
const current = results.length === 0 ? [] : results.map((result) => result.toData()).pluck(this.relatedPivotKey).all().map((i) => String(i));
|
|
3769
|
-
const detach = diff(
|
|
3899
|
+
const detach = collect(current).diff(Object.keys(records = this.formatRecordsList(this.parseIds(ids)))).all();
|
|
3770
3900
|
if (detaching && detach.length > 0) {
|
|
3771
3901
|
await this.detach(detach);
|
|
3772
3902
|
changes.detached = this.castKeys(detach);
|
|
3773
3903
|
}
|
|
3774
|
-
changes =
|
|
3904
|
+
changes = Obj.deepMerge(changes, await this.attachNew(records, current, false));
|
|
3775
3905
|
return changes;
|
|
3776
3906
|
}
|
|
3777
3907
|
syncWithoutDetaching(ids) {
|
|
3778
3908
|
return this.sync(ids, false);
|
|
3779
3909
|
}
|
|
3780
3910
|
syncWithPivotValues(ids, values, detaching = true) {
|
|
3781
|
-
return this.sync(collect
|
|
3782
|
-
return [id, values];
|
|
3911
|
+
return this.sync(collect(this.parseIds(ids)).mapWithKeys((id) => {
|
|
3912
|
+
return [String(id), values];
|
|
3783
3913
|
}), detaching);
|
|
3784
3914
|
}
|
|
3785
3915
|
withPivot(columns) {
|
|
3786
|
-
this.pivotColumns = this.pivotColumns.concat(isArray(columns) ? columns : Array.prototype.slice.call(columns));
|
|
3916
|
+
this.pivotColumns = this.pivotColumns.concat(Array.isArray(columns) ? columns : Array.prototype.slice.call(columns));
|
|
3787
3917
|
return this;
|
|
3788
3918
|
}
|
|
3789
3919
|
async attachNew(records, current, touch = true) {
|
|
@@ -3819,9 +3949,9 @@ const InteractsWithPivotTable = (Relation) => {
|
|
|
3819
3949
|
return parseInt(updated);
|
|
3820
3950
|
}
|
|
3821
3951
|
formatRecordsList(records) {
|
|
3822
|
-
return collect
|
|
3823
|
-
if (!isArray(attributes)) [id, attributes] = [attributes, {}];
|
|
3824
|
-
return [id, attributes];
|
|
3952
|
+
return collect(records).mapWithKeys((attributes, id) => {
|
|
3953
|
+
if (!Array.isArray(attributes)) [id, attributes] = [attributes, {}];
|
|
3954
|
+
return [String(id), attributes];
|
|
3825
3955
|
}).all();
|
|
3826
3956
|
}
|
|
3827
3957
|
async getCurrentlyAttachedPivots() {
|
|
@@ -3891,7 +4021,7 @@ const InteractsWithPivotTable = (Relation) => {
|
|
|
3891
4021
|
}
|
|
3892
4022
|
formatAttachRecord(key, value, attributes, hasTimestamps) {
|
|
3893
4023
|
const [id, newAttributes] = this.extractAttachIdAndAttributes(key, value, attributes);
|
|
3894
|
-
return
|
|
4024
|
+
return Obj.deepMerge(this.baseAttachRecord(id, hasTimestamps), newAttributes);
|
|
3895
4025
|
}
|
|
3896
4026
|
baseAttachRecord(id, timed) {
|
|
3897
4027
|
let record = {};
|
|
@@ -3904,7 +4034,7 @@ const InteractsWithPivotTable = (Relation) => {
|
|
|
3904
4034
|
return record;
|
|
3905
4035
|
}
|
|
3906
4036
|
extractAttachIdAndAttributes(key, value, newAttributes) {
|
|
3907
|
-
return isArray(value) ? [key, {
|
|
4037
|
+
return Array.isArray(value) ? [key, {
|
|
3908
4038
|
...value,
|
|
3909
4039
|
...newAttributes
|
|
3910
4040
|
}] : [value, newAttributes];
|
|
@@ -3915,7 +4045,7 @@ const InteractsWithPivotTable = (Relation) => {
|
|
|
3915
4045
|
parseIds(value) {
|
|
3916
4046
|
if (value instanceof Model) return [value[this.relatedKey]];
|
|
3917
4047
|
if (value instanceof Collection$1) return value.pluck(this.relatedKey).all();
|
|
3918
|
-
return isArray(value) ? value : [value];
|
|
4048
|
+
return Array.isArray(value) ? value : [value];
|
|
3919
4049
|
}
|
|
3920
4050
|
};
|
|
3921
4051
|
};
|
|
@@ -3975,9 +4105,8 @@ var BelongsToMany = class extends compose(Relation, InteractsWithPivotTable) {
|
|
|
3975
4105
|
return this;
|
|
3976
4106
|
}
|
|
3977
4107
|
async get(columns) {
|
|
3978
|
-
var _builder$query;
|
|
3979
4108
|
const builder = this.query.applyScopes();
|
|
3980
|
-
columns =
|
|
4109
|
+
columns = builder.query?._statements?.find((item) => item.grouping == "columns") ? [] : columns;
|
|
3981
4110
|
let models = await builder.select(this.shouldSelect(columns)).getModels();
|
|
3982
4111
|
this.hydratePivotRelation(models);
|
|
3983
4112
|
if (models.length > 0) models = await builder.eagerLoadRelations(models);
|
|
@@ -4026,7 +4155,7 @@ var BelongsToMany = class extends compose(Relation, InteractsWithPivotTable) {
|
|
|
4026
4155
|
const value = model.attributes[key];
|
|
4027
4156
|
if (key.startsWith("pivot_")) {
|
|
4028
4157
|
values[key.substring(6)] = value;
|
|
4029
|
-
model.attributes =
|
|
4158
|
+
model.attributes = Arr.except(model.attributes, [key]);
|
|
4030
4159
|
}
|
|
4031
4160
|
}
|
|
4032
4161
|
return values;
|
|
@@ -4037,11 +4166,11 @@ var BelongsToMany = class extends compose(Relation, InteractsWithPivotTable) {
|
|
|
4037
4166
|
return this.withPivot(this.createdAt(), this.updatedAt());
|
|
4038
4167
|
}
|
|
4039
4168
|
shouldSelect(columns = ["*"]) {
|
|
4040
|
-
if (
|
|
4169
|
+
if (columns.length === 1 && columns[0] === "*") columns = [this.related.getTable() + ".*"];
|
|
4041
4170
|
return columns.concat(this.aliasedPivotColumns());
|
|
4042
4171
|
}
|
|
4043
4172
|
aliasedPivotColumns() {
|
|
4044
|
-
return collect
|
|
4173
|
+
return collect([this.foreignPivotKey, this.relatedPivotKey].concat(this.pivotColumns)).map((column) => {
|
|
4045
4174
|
return this.qualifyPivotColumn(column) + " as pivot_" + column;
|
|
4046
4175
|
}).unique().all();
|
|
4047
4176
|
}
|
|
@@ -4161,9 +4290,8 @@ var Builder = class Builder extends Inference {
|
|
|
4161
4290
|
}
|
|
4162
4291
|
asProxy() {
|
|
4163
4292
|
return new Proxy(this, { get(target, prop) {
|
|
4164
|
-
var _target$query$connect;
|
|
4165
4293
|
if (typeof target[prop] !== "undefined") return target[prop];
|
|
4166
|
-
const skipReturning = !!
|
|
4294
|
+
const skipReturning = !!target.query.connector?.client.config?.client?.includes("mysql") && prop === "returning";
|
|
4167
4295
|
if ([
|
|
4168
4296
|
"select",
|
|
4169
4297
|
"from",
|
|
@@ -4257,7 +4385,7 @@ var Builder = class Builder extends Inference {
|
|
|
4257
4385
|
};
|
|
4258
4386
|
}
|
|
4259
4387
|
if (prop.startsWith("where")) {
|
|
4260
|
-
const column = snake(prop.substring(5));
|
|
4388
|
+
const column = Str.snake(prop.substring(5));
|
|
4261
4389
|
return (...args) => {
|
|
4262
4390
|
target.query.where(column, ...args);
|
|
4263
4391
|
return target.asProxy();
|
|
@@ -4332,7 +4460,8 @@ var Builder = class Builder extends Inference {
|
|
|
4332
4460
|
}
|
|
4333
4461
|
addUpdatedAtColumn(values) {
|
|
4334
4462
|
if (!this.model.usesTimestamps() || this.model.getUpdatedAtColumn() === null) return values;
|
|
4335
|
-
|
|
4463
|
+
const column = this.model.getUpdatedAtColumn();
|
|
4464
|
+
values = Obj.deepMerge({ [column]: this.model.freshTimestampString() }, values);
|
|
4336
4465
|
return values;
|
|
4337
4466
|
}
|
|
4338
4467
|
delete() {
|
|
@@ -4360,9 +4489,8 @@ var Builder = class Builder extends Inference {
|
|
|
4360
4489
|
return this.model;
|
|
4361
4490
|
}
|
|
4362
4491
|
setModel(model) {
|
|
4363
|
-
var _this$query;
|
|
4364
4492
|
this.model = model;
|
|
4365
|
-
if (typeof
|
|
4493
|
+
if (typeof this.query?.client?.table == "function") this.query = this.query.client.table(this.model.getTable());
|
|
4366
4494
|
else this.query = this.query.table(this.model.getTable());
|
|
4367
4495
|
return this;
|
|
4368
4496
|
}
|
|
@@ -4405,7 +4533,7 @@ var Builder = class Builder extends Inference {
|
|
|
4405
4533
|
}
|
|
4406
4534
|
withoutGlobalScope(scope) {
|
|
4407
4535
|
if (typeof scope !== "string") scope = scope.constructor.name;
|
|
4408
|
-
this.globalScopes =
|
|
4536
|
+
this.globalScopes = Arr.except(this.globalScopes, [scope]);
|
|
4409
4537
|
return this;
|
|
4410
4538
|
}
|
|
4411
4539
|
macro(name, callback) {
|
|
@@ -4422,7 +4550,7 @@ var Builder = class Builder extends Inference {
|
|
|
4422
4550
|
let eagerLoads = {};
|
|
4423
4551
|
if (typeof args[1] === "function") {
|
|
4424
4552
|
const eagerLoad = this.parseWithRelations({ [args[0]]: args[1] });
|
|
4425
|
-
this.eagerLoad =
|
|
4553
|
+
this.eagerLoad = Obj.deepMerge(this.eagerLoad, eagerLoad);
|
|
4426
4554
|
return this;
|
|
4427
4555
|
}
|
|
4428
4556
|
const relations = flattenDeep(args);
|
|
@@ -4431,13 +4559,13 @@ var Builder = class Builder extends Inference {
|
|
|
4431
4559
|
let eagerLoad;
|
|
4432
4560
|
if (typeof relation === "string") eagerLoad = { [relation]: (q) => q };
|
|
4433
4561
|
else if (typeof relation === "object") eagerLoad = relation;
|
|
4434
|
-
eagerLoads =
|
|
4562
|
+
eagerLoads = Obj.deepMerge(eagerLoads, eagerLoad);
|
|
4435
4563
|
}
|
|
4436
|
-
this.eagerLoad =
|
|
4564
|
+
this.eagerLoad = Obj.deepMerge(this.eagerLoad, this.parseWithRelations(eagerLoads));
|
|
4437
4565
|
return this;
|
|
4438
4566
|
}
|
|
4439
4567
|
has(relation, operator = ">=", count = 1, boolean = "and", callback = null) {
|
|
4440
|
-
if (
|
|
4568
|
+
if (typeof relation === "string") {
|
|
4441
4569
|
if (relation.includes(".")) return this.hasNested(relation, operator, count, boolean, callback);
|
|
4442
4570
|
relation = this.getRelationWithoutConstraints(getRelationMethod(relation));
|
|
4443
4571
|
}
|
|
@@ -4514,7 +4642,7 @@ var Builder = class Builder extends Inference {
|
|
|
4514
4642
|
let eagerLoad;
|
|
4515
4643
|
if (typeof relation === "string") eagerLoad = { [relation]: (q) => q };
|
|
4516
4644
|
else if (typeof relation === "object") eagerLoad = relation;
|
|
4517
|
-
eagerLoads =
|
|
4645
|
+
eagerLoads = Obj.deepMerge(eagerLoads, eagerLoad);
|
|
4518
4646
|
}
|
|
4519
4647
|
relations = eagerLoads;
|
|
4520
4648
|
const db = this.model.getConnection();
|
|
@@ -4533,7 +4661,7 @@ var Builder = class Builder extends Inference {
|
|
|
4533
4661
|
} else expression = column;
|
|
4534
4662
|
const query = relation.getRelationExistenceQuery(relation.getRelated().newModelQuery(), this, db.raw(expression));
|
|
4535
4663
|
constraints(query);
|
|
4536
|
-
alias = alias || snake(`${name} ${action} ${column}`.replace("/[^[:alnum:][:space:]_]/u", ""));
|
|
4664
|
+
alias = alias || Str.snake(`${name} ${action} ${column}`.replace("/[^[:alnum:][:space:]_]/u", ""));
|
|
4537
4665
|
if (action === "exists") this.select(db.raw(`exists(${query.toSql().sql}) as ${alias}`));
|
|
4538
4666
|
else this.selectSub(action ? query : query.limit(1), alias);
|
|
4539
4667
|
}
|
|
@@ -4557,7 +4685,7 @@ var Builder = class Builder extends Inference {
|
|
|
4557
4685
|
}
|
|
4558
4686
|
parseSub(query) {
|
|
4559
4687
|
if (query instanceof Builder || query instanceof Relation) return [query.toSql().sql, query.toSql().bindings];
|
|
4560
|
-
else if (
|
|
4688
|
+
else if (typeof query === "string") return [query, []];
|
|
4561
4689
|
else throw new Error("A subquery must be a query builder instance, a Closure, or a string.");
|
|
4562
4690
|
}
|
|
4563
4691
|
prependDatabaseNameIfCrossDatabaseQuery(query) {
|
|
@@ -4614,15 +4742,15 @@ var Builder = class Builder extends Inference {
|
|
|
4614
4742
|
if (prefix !== "") prefix += ".";
|
|
4615
4743
|
for (const key in relations) {
|
|
4616
4744
|
const value = relations[key];
|
|
4617
|
-
if (
|
|
4745
|
+
if (typeof value === "string" || Number.isFinite(parseInt(value))) continue;
|
|
4618
4746
|
const [attribute, attributeSelectConstraint] = this.parseNameAndAttributeSelectionConstraint(key, value);
|
|
4619
4747
|
preparedRelationships = Object.assign({}, preparedRelationships, { [`${prefix}${attribute}`]: attributeSelectConstraint }, this.prepareNestedWithRelationships(value, `${prefix}${attribute}`));
|
|
4620
|
-
relations =
|
|
4748
|
+
relations = Arr.except(relations, [key]);
|
|
4621
4749
|
}
|
|
4622
4750
|
for (const key in relations) {
|
|
4623
4751
|
const value = relations[key];
|
|
4624
4752
|
let attribute = key, attributeSelectConstraint = value;
|
|
4625
|
-
if (
|
|
4753
|
+
if (typeof value === "string") [attribute, attributeSelectConstraint] = this.parseNameAndAttributeSelectionConstraint(value);
|
|
4626
4754
|
preparedRelationships[`${prefix}${attribute}`] = this.combineConstraints([attributeSelectConstraint, preparedRelationships[`${prefix}${attribute}`] || (() => {})]);
|
|
4627
4755
|
}
|
|
4628
4756
|
return preparedRelationships;
|
|
@@ -4670,8 +4798,8 @@ var Builder = class Builder extends Inference {
|
|
|
4670
4798
|
}
|
|
4671
4799
|
async findOrFail(...args) {
|
|
4672
4800
|
const data = await this.find(...args);
|
|
4673
|
-
if (isArray(args[0])) {
|
|
4674
|
-
if (data.count() !== args[0].length) throw new ModelNotFoundError().setModel(this.model.constructor.name,
|
|
4801
|
+
if (Array.isArray(args[0])) {
|
|
4802
|
+
if (data.count() !== args[0].length) throw new ModelNotFoundError().setModel(this.model.constructor.name, collect(args[0]).diff(data.modelKeys()).all());
|
|
4675
4803
|
return data;
|
|
4676
4804
|
}
|
|
4677
4805
|
if (data === null) throw new ModelNotFoundError().setModel(this.model.constructor.name, args[0]);
|
|
@@ -4685,12 +4813,12 @@ var Builder = class Builder extends Inference {
|
|
|
4685
4813
|
async firstOrNew(attributes = {}, values = {}) {
|
|
4686
4814
|
const instance = await this.where(attributes).first();
|
|
4687
4815
|
if (instance !== null) return instance;
|
|
4688
|
-
return this.newModelInstance(
|
|
4816
|
+
return this.newModelInstance(Obj.deepMerge(attributes, values));
|
|
4689
4817
|
}
|
|
4690
4818
|
async firstOrCreate(attributes = {}, values = {}) {
|
|
4691
4819
|
const instance = await this.where(attributes).first();
|
|
4692
4820
|
if (instance !== null) return instance;
|
|
4693
|
-
return tap(this.newModelInstance(
|
|
4821
|
+
return tap(this.newModelInstance(Obj.deepMerge(attributes, values)), async (instance) => {
|
|
4694
4822
|
await instance.save({ client: this.query });
|
|
4695
4823
|
});
|
|
4696
4824
|
}
|
|
@@ -4710,14 +4838,13 @@ var Builder = class Builder extends Inference {
|
|
|
4710
4838
|
return this;
|
|
4711
4839
|
}
|
|
4712
4840
|
async find(id, columns) {
|
|
4713
|
-
if (isArray(id) || id instanceof Collection$1) return await this.findMany(id, columns);
|
|
4841
|
+
if (Array.isArray(id) || id instanceof Collection$1) return await this.findMany(id, columns);
|
|
4714
4842
|
return await this.where(this.model.getKeyName(), id).first(columns);
|
|
4715
4843
|
}
|
|
4716
4844
|
async findMany(ids, columns = ["*"]) {
|
|
4717
|
-
|
|
4718
|
-
|
|
4719
|
-
|
|
4720
|
-
return await this.whereIn(this.model.getKeyName(), ids).get(columns);
|
|
4845
|
+
const values = ids instanceof Collection$1 ? ids.modelKeys() : Array.isArray(ids) ? ids : [ids];
|
|
4846
|
+
if (values.length === 0) return new Collection$1([]);
|
|
4847
|
+
return await this.whereIn(this.model.getKeyName(), values).get(columns);
|
|
4721
4848
|
}
|
|
4722
4849
|
async pluck(column) {
|
|
4723
4850
|
return new Collection$1(await this.query.pluck(column));
|
|
@@ -4725,7 +4852,7 @@ var Builder = class Builder extends Inference {
|
|
|
4725
4852
|
async destroy(ids) {
|
|
4726
4853
|
if (ids instanceof Collection$1) ids = ids.modelKeys();
|
|
4727
4854
|
if (ids instanceof Collection) ids = ids.all();
|
|
4728
|
-
ids = isArray(ids) ? ids : Array.prototype.slice.call(ids);
|
|
4855
|
+
ids = Array.isArray(ids) ? ids : Array.prototype.slice.call(ids);
|
|
4729
4856
|
if (ids.length === 0) return 0;
|
|
4730
4857
|
const key = this.model.newInstance().getKeyName();
|
|
4731
4858
|
let count = 0;
|
|
@@ -4743,12 +4870,11 @@ var Builder = class Builder extends Inference {
|
|
|
4743
4870
|
return await this.model.newModelQuery().get(columns);
|
|
4744
4871
|
}
|
|
4745
4872
|
async paginate(page = 1, perPage = 10) {
|
|
4746
|
-
var _this;
|
|
4747
4873
|
page = page || 1;
|
|
4748
|
-
perPage = perPage ||
|
|
4874
|
+
perPage = perPage || this?.model?.perPage || 15;
|
|
4749
4875
|
this.applyScopes();
|
|
4750
4876
|
const total = await this.query.clone().clearOrder().clearSelect().count(this.primaryKey);
|
|
4751
|
-
let results
|
|
4877
|
+
let results;
|
|
4752
4878
|
if (total > 0) {
|
|
4753
4879
|
const skip = (page - 1) * (perPage ?? 10);
|
|
4754
4880
|
this.take(perPage).skip(skip);
|
|
@@ -4758,7 +4884,7 @@ var Builder = class Builder extends Inference {
|
|
|
4758
4884
|
return new Paginator(results, parseInt(total), perPage, page);
|
|
4759
4885
|
}
|
|
4760
4886
|
async getModels(...columns) {
|
|
4761
|
-
columns =
|
|
4887
|
+
columns = flatten(columns);
|
|
4762
4888
|
if (columns.length > 0) {
|
|
4763
4889
|
if (this.query._statements.filter((item) => item.grouping == "columns").length == 0 && columns[0] !== "*") this.query.select(...columns);
|
|
4764
4890
|
}
|
|
@@ -4874,11 +5000,11 @@ var SQLite = class {
|
|
|
4874
5000
|
is_generated: raw.hidden !== 0,
|
|
4875
5001
|
generation_expression: null,
|
|
4876
5002
|
is_nullable: raw.notnull === 0,
|
|
4877
|
-
is_unique: !!
|
|
5003
|
+
is_unique: !!index?.unique && indexInfo?.length === 1,
|
|
4878
5004
|
is_primary_key: raw.pk === 1,
|
|
4879
5005
|
has_auto_increment: raw.pk === 1 && tablesWithAutoIncrementPrimaryKeys.includes(table),
|
|
4880
|
-
foreign_key_column:
|
|
4881
|
-
foreign_key_table:
|
|
5006
|
+
foreign_key_column: foreignKey?.to || null,
|
|
5007
|
+
foreign_key_table: foreignKey?.table || null
|
|
4882
5008
|
};
|
|
4883
5009
|
});
|
|
4884
5010
|
};
|
|
@@ -5100,8 +5226,7 @@ var Migrator = class {
|
|
|
5100
5226
|
else await callback(connection);
|
|
5101
5227
|
}
|
|
5102
5228
|
async runMethod(connection, migration, method) {
|
|
5103
|
-
|
|
5104
|
-
await ((_migration$method = migration[method]) === null || _migration$method === void 0 ? void 0 : _migration$method.call(migration, connection.schema, connection));
|
|
5229
|
+
await migration[method]?.(connection.schema, connection);
|
|
5105
5230
|
}
|
|
5106
5231
|
async resolvePath(filePath) {
|
|
5107
5232
|
try {
|
|
@@ -5130,7 +5255,7 @@ var Migrator = class {
|
|
|
5130
5255
|
return path.basename(filePath).replace(".js", "");
|
|
5131
5256
|
}
|
|
5132
5257
|
path(p) {
|
|
5133
|
-
this.paths = Array.from(new Set([...this.paths, p]));
|
|
5258
|
+
this.paths = Array.from(/* @__PURE__ */ new Set([...this.paths, p]));
|
|
5134
5259
|
}
|
|
5135
5260
|
getPaths() {
|
|
5136
5261
|
return this.paths;
|
|
@@ -5163,6 +5288,40 @@ var Migrator = class {
|
|
|
5163
5288
|
}
|
|
5164
5289
|
};
|
|
5165
5290
|
//#endregion
|
|
5291
|
+
//#region src/cli/utils.ts
|
|
5292
|
+
const join = path.join;
|
|
5293
|
+
var Utils = class {
|
|
5294
|
+
static findModulePkg(moduleId, cwd) {
|
|
5295
|
+
const parts = moduleId.replace(/\\/g, "/").split("/");
|
|
5296
|
+
let packageName = "";
|
|
5297
|
+
if (parts.length > 0 && parts[0][0] === "@") packageName += parts.shift() + "/";
|
|
5298
|
+
packageName += parts.shift();
|
|
5299
|
+
const packageJson = path.join(packageName, "package.json");
|
|
5300
|
+
const resolved = resolveFrom.silent(cwd ?? process.cwd(), packageJson);
|
|
5301
|
+
if (!resolved) return;
|
|
5302
|
+
return path.join(path.dirname(resolved), parts.join("/"));
|
|
5303
|
+
}
|
|
5304
|
+
static async getMigrationPaths(cwd, migrator, defaultPath, path) {
|
|
5305
|
+
if (path) return [join(cwd, path)];
|
|
5306
|
+
return [...migrator.getPaths(), join(cwd, defaultPath)];
|
|
5307
|
+
}
|
|
5308
|
+
};
|
|
5309
|
+
var TableGuesser = class TableGuesser {
|
|
5310
|
+
static CREATE_PATTERNS = [/^create_(\w+)_table$/, /^create_(\w+)$/];
|
|
5311
|
+
static CHANGE_PATTERNS = [/.+_(to|from|in)_(\w+)_table$/, /.+_(to|from|in)_(\w+)$/];
|
|
5312
|
+
static guess(migration) {
|
|
5313
|
+
for (const pattern of TableGuesser.CREATE_PATTERNS) {
|
|
5314
|
+
const matches = migration.match(pattern);
|
|
5315
|
+
if (matches) return [matches[1], true];
|
|
5316
|
+
}
|
|
5317
|
+
for (const pattern of TableGuesser.CHANGE_PATTERNS) {
|
|
5318
|
+
const matches = migration.match(pattern);
|
|
5319
|
+
if (matches) return [matches[2], false];
|
|
5320
|
+
}
|
|
5321
|
+
return [];
|
|
5322
|
+
}
|
|
5323
|
+
};
|
|
5324
|
+
//#endregion
|
|
5166
5325
|
//#region src/migrate.ts
|
|
5167
5326
|
var Migrate = class {
|
|
5168
5327
|
basePath;
|
|
@@ -5299,8 +5458,7 @@ var Migrate = class {
|
|
|
5299
5458
|
* @returns
|
|
5300
5459
|
*/
|
|
5301
5460
|
async setupConnection(config) {
|
|
5302
|
-
|
|
5303
|
-
const table = (config === null || config === void 0 || (_config$migrations = config.migrations) === null || _config$migrations === void 0 ? void 0 : _config$migrations.table) || "migrations";
|
|
5461
|
+
const table = config?.migrations?.table || "migrations";
|
|
5304
5462
|
if (config.skipConnection !== true) {
|
|
5305
5463
|
arquebus.addConnection(config, "default");
|
|
5306
5464
|
Object.entries(config.connections || {}).forEach(([name, connection]) => {
|
|
@@ -5360,7 +5518,6 @@ var MigrationCreator = class {
|
|
|
5360
5518
|
let stub;
|
|
5361
5519
|
if (!table) {
|
|
5362
5520
|
const customPath = path.join(this.customStubPath ?? "", `migration-${this.type}.stub`);
|
|
5363
|
-
console.log("\n", customPath, "---");
|
|
5364
5521
|
stub = await FileSystem.fileExists(customPath) ? customPath : this.stubPath(`/migration-${this.type}.stub`);
|
|
5365
5522
|
} else if (create) {
|
|
5366
5523
|
const customPath = path.join(this.customStubPath ?? "", `migration.create-${this.type}.stub`);
|
|
@@ -5393,7 +5550,9 @@ var MigrationCreator = class {
|
|
|
5393
5550
|
}
|
|
5394
5551
|
stubPath(stub = "") {
|
|
5395
5552
|
const __dirname = this.getDirname(import.meta);
|
|
5396
|
-
|
|
5553
|
+
const resolved = [path.join(__dirname, "stubs", stub), path.join(__dirname, "../stubs", stub)].find((candidate) => existsSync(candidate));
|
|
5554
|
+
if (!resolved) throw new Error(`Migration stub not found: ${stub}`);
|
|
5555
|
+
return resolved;
|
|
5397
5556
|
}
|
|
5398
5557
|
getDirname(meta) {
|
|
5399
5558
|
if (typeof __dirname !== "undefined") return __dirname;
|
|
@@ -5403,20 +5562,27 @@ var MigrationCreator = class {
|
|
|
5403
5562
|
};
|
|
5404
5563
|
//#endregion
|
|
5405
5564
|
//#region package.json
|
|
5406
|
-
var version = "
|
|
5565
|
+
var version = "3.0.0";
|
|
5407
5566
|
//#endregion
|
|
5408
5567
|
//#region src/cli/index.ts
|
|
5409
5568
|
(class Cli {
|
|
5410
5569
|
cwd;
|
|
5411
|
-
output = Logger
|
|
5570
|
+
output = Logger;
|
|
5412
5571
|
config = {};
|
|
5413
5572
|
basePath = "";
|
|
5414
|
-
modulePath;
|
|
5573
|
+
modulePath = "";
|
|
5415
5574
|
configPath;
|
|
5416
|
-
modulePackage;
|
|
5575
|
+
modulePackage = { version: "N/A" };
|
|
5417
5576
|
constructor(basePath) {
|
|
5418
5577
|
this.basePath = basePath ?? (process.env.TEST === "true" ? "test/cli" : "");
|
|
5419
5578
|
}
|
|
5579
|
+
static async init() {
|
|
5580
|
+
config({ quiet: true });
|
|
5581
|
+
const instance = new Cli();
|
|
5582
|
+
await instance.loadPaths();
|
|
5583
|
+
await instance.loadConfig();
|
|
5584
|
+
await instance.run();
|
|
5585
|
+
}
|
|
5420
5586
|
terminateNotFound() {
|
|
5421
5587
|
const cmd = Logger.log([["arquebus init", [
|
|
5422
5588
|
"italic",
|
|
@@ -5425,13 +5591,24 @@ var version = "2.0.0";
|
|
|
5425
5591
|
]]], "", false);
|
|
5426
5592
|
this.output.error(`ERROR: Arquebus config not found. Run ${cmd} first.`);
|
|
5427
5593
|
}
|
|
5428
|
-
|
|
5429
|
-
|
|
5430
|
-
|
|
5431
|
-
|
|
5594
|
+
ensureConfigured() {
|
|
5595
|
+
if (!this.configPath) this.terminateNotFound();
|
|
5596
|
+
}
|
|
5597
|
+
resolveBasePath(requestedPath) {
|
|
5598
|
+
return requestedPath ? path$1.join(this.cwd, requestedPath) : this.cwd;
|
|
5599
|
+
}
|
|
5600
|
+
async resolveStub(name) {
|
|
5601
|
+
const candidates = [path$1.join(this.modulePath, "src/stubs", name), path$1.join(this.modulePath, "dist/stubs", name)];
|
|
5602
|
+
for (const candidate of candidates) if (await FileSystem.fileExists(candidate)) return candidate;
|
|
5603
|
+
throw new Error(`Arquebus stub not found: ${name}`);
|
|
5604
|
+
}
|
|
5605
|
+
migrationReporter() {
|
|
5606
|
+
return (message, status) => {
|
|
5607
|
+
if (status && status !== "quiet") this.output[status](message);
|
|
5608
|
+
};
|
|
5432
5609
|
}
|
|
5433
5610
|
async loadPaths() {
|
|
5434
|
-
this.cwd = path.join(process.cwd(), this.basePath);
|
|
5611
|
+
this.cwd = path$1.join(process.cwd(), this.basePath);
|
|
5435
5612
|
this.configPath = FileSystem.resolveFileUp("arquebus.config", [
|
|
5436
5613
|
"js",
|
|
5437
5614
|
"ts",
|
|
@@ -5439,7 +5616,7 @@ var version = "2.0.0";
|
|
|
5439
5616
|
], this.cwd) ?? void 0;
|
|
5440
5617
|
this.modulePath = Utils.findModulePkg("@h3ravel/arquebus", this.cwd) ?? "";
|
|
5441
5618
|
try {
|
|
5442
|
-
this.modulePackage = await
|
|
5619
|
+
this.modulePackage = JSON.parse(await readFile(path$1.join(this.modulePath, "package.json"), "utf8"));
|
|
5443
5620
|
} catch {
|
|
5444
5621
|
this.modulePackage = { version: "N/A" };
|
|
5445
5622
|
}
|
|
@@ -5447,233 +5624,185 @@ var version = "2.0.0";
|
|
|
5447
5624
|
}
|
|
5448
5625
|
async loadConfig() {
|
|
5449
5626
|
try {
|
|
5450
|
-
|
|
5451
|
-
this.config
|
|
5452
|
-
if ((_this$config$migratio = this.config.migrations) === null || _this$config$migratio === void 0 ? void 0 : _this$config$migratio.path) {
|
|
5453
|
-
var _this$config$migratio2;
|
|
5454
|
-
await mkdir(path.join(this.cwd, (_this$config$migratio2 = this.config.migrations) === null || _this$config$migratio2 === void 0 ? void 0 : _this$config$migratio2.path), { recursive: true });
|
|
5455
|
-
}
|
|
5627
|
+
this.config = (await importFile(this.configPath ?? "----")).default;
|
|
5628
|
+
if (this.config.migrations?.path) await mkdir(path$1.join(this.cwd, this.config.migrations.path), { recursive: true });
|
|
5456
5629
|
} catch {
|
|
5457
5630
|
this.config = {};
|
|
5458
5631
|
}
|
|
5459
5632
|
return this;
|
|
5460
5633
|
}
|
|
5461
5634
|
async run() {
|
|
5462
|
-
const
|
|
5463
|
-
|
|
5464
|
-
|
|
5465
|
-
|
|
5466
|
-
|
|
5467
|
-
|
|
5468
|
-
|
|
5469
|
-
|
|
5470
|
-
|
|
5471
|
-
|
|
5472
|
-
|
|
5473
|
-
|
|
5474
|
-
|
|
5475
|
-
|
|
5476
|
-
}
|
|
5477
|
-
|
|
5478
|
-
|
|
5479
|
-
|
|
5480
|
-
|
|
5481
|
-
|
|
5482
|
-
|
|
5483
|
-
|
|
5484
|
-
|
|
5485
|
-
|
|
5486
|
-
|
|
5487
|
-
|
|
5488
|
-
|
|
5489
|
-
|
|
5490
|
-
|
|
5491
|
-
|
|
5492
|
-
|
|
5493
|
-
|
|
5494
|
-
|
|
5495
|
-
|
|
5496
|
-
|
|
5497
|
-
|
|
5498
|
-
|
|
5499
|
-
|
|
5500
|
-
|
|
5501
|
-
/**
|
|
5502
|
-
* Publish migrations from third party vendors
|
|
5503
|
-
*/
|
|
5504
|
-
program.command("migrate:publish <package>").description("Publish any migration files from packages.").option("-p, --path [path]", "The path to the migrations directory.").action(async (pkg, opts) => {
|
|
5505
|
-
if (!this.configPath) this.terminateNotFound();
|
|
5506
|
-
try {
|
|
5507
|
-
var _this$config$migratio4;
|
|
5508
|
-
const packagePath = Utils.findModulePkg(pkg) ?? "";
|
|
5509
|
-
const basePath = path.join(this.cwd, opts.path ?? ((_this$config$migratio4 = this.config.migrations) === null || _this$config$migratio4 === void 0 ? void 0 : _this$config$migratio4.path) ?? "./migrations");
|
|
5510
|
-
const pkgJson = await import(path.join(packagePath, "package.json"));
|
|
5511
|
-
if (!packagePath) this.output.error(`ERROR: package ${pkg} not found`);
|
|
5512
|
-
const creator = new MigrationCreator(path.join(packagePath, pkgJson.migrations ?? "migrations"));
|
|
5513
|
-
const pkgInf = Logger.log(path.basename(pkgJson.name + "@" + pkgJson.version), ["italic", "gray"], false);
|
|
5514
|
-
this.output.info(`INFO: Publishing migrations from ${pkgInf}`);
|
|
5515
|
-
await creator.publish(basePath, (fileName) => {
|
|
5516
|
-
this.output.split("INFO: Migration Published", fileName, "success");
|
|
5517
|
-
});
|
|
5518
|
-
} catch (e) {
|
|
5519
|
-
this.output.error("ERROR: " + e);
|
|
5520
|
-
}
|
|
5521
|
-
});
|
|
5522
|
-
/**
|
|
5523
|
-
* Run all pending migrations
|
|
5524
|
-
*/
|
|
5525
|
-
program.command("migrate").description("Run all pending migrations.").option("-s, --step [number]", "Force the migrations to be run so they can be rolled back individually.").option("-p, --path [path]", "The path to the migrations directory.").action(async (opts) => {
|
|
5526
|
-
if (!this.configPath) this.terminateNotFound();
|
|
5527
|
-
const basePath = opts.path ? path.join(this.cwd, opts.path) : this.cwd;
|
|
5528
|
-
try {
|
|
5529
|
-
const step = typeof opts.step === "string" ? parseInt(opts.step) : opts.step;
|
|
5530
|
-
await new Migrate(basePath).run(this.config, {
|
|
5531
|
-
...opts,
|
|
5532
|
-
step
|
|
5533
|
-
}, true);
|
|
5534
|
-
} catch (e) {
|
|
5535
|
-
this.output.error("ERROR: " + e);
|
|
5536
|
-
}
|
|
5537
|
-
});
|
|
5538
|
-
/**
|
|
5539
|
-
* Rollaback the last migration
|
|
5540
|
-
*/
|
|
5541
|
-
program.command("migrate:rollback").description("Rollback the last database migration.").option("-s, --step [number]", "The number of migrations to be reverted.").option("-p, --path [path]", "The path to the migrations directory.").action(async (opts) => {
|
|
5542
|
-
if (!this.configPath) this.terminateNotFound();
|
|
5543
|
-
const basePath = opts.path ? path.join(this.cwd, opts.path) : this.cwd;
|
|
5544
|
-
try {
|
|
5545
|
-
await new Migrate(basePath, void 0, (msg, sts) => {
|
|
5546
|
-
if (sts) this.output[sts](msg);
|
|
5547
|
-
}).rollback(this.config, {
|
|
5548
|
-
...opts,
|
|
5549
|
-
step: typeof opts.step === "string" ? parseInt(opts.step) : opts.step
|
|
5550
|
-
}, true);
|
|
5551
|
-
} catch (e) {
|
|
5552
|
-
this.output.error("ERROR: " + e);
|
|
5553
|
-
}
|
|
5554
|
-
});
|
|
5555
|
-
/**
|
|
5556
|
-
* Rollback all database migrations
|
|
5557
|
-
*/
|
|
5558
|
-
program.command("migrate:reset").description("Rollback all database migrations.").option("-p, --path [path]", "The path to the migrations directory.").action(async (opts) => {
|
|
5559
|
-
if (!this.configPath) this.terminateNotFound();
|
|
5560
|
-
const basePath = opts.path ? path.join(this.cwd, opts.path) : this.cwd;
|
|
5561
|
-
try {
|
|
5562
|
-
await new Migrate(basePath, void 0, (msg, sts) => {
|
|
5563
|
-
if (sts) this.output[sts](msg);
|
|
5564
|
-
}).reset(this.config, opts, true);
|
|
5565
|
-
} catch (e) {
|
|
5566
|
-
this.output.error("ERROR: " + e);
|
|
5567
|
-
}
|
|
5568
|
-
});
|
|
5569
|
-
/**
|
|
5570
|
-
* Reset and re-run all migrations
|
|
5571
|
-
*/
|
|
5572
|
-
program.command("migrate:refresh").description("Reset and re-run all migrations.").option("-p, --path [path]", "The path to the migrations directory.").action(async (opts) => {
|
|
5573
|
-
if (!this.configPath) this.terminateNotFound();
|
|
5574
|
-
const basePath = opts.path ? path.join(this.cwd, opts.path) : this.cwd;
|
|
5575
|
-
try {
|
|
5576
|
-
await new Migrate(basePath, void 0, (msg, sts) => {
|
|
5577
|
-
if (sts) this.output[sts](msg);
|
|
5578
|
-
}).refresh(this.config, opts, true);
|
|
5579
|
-
} catch (e) {
|
|
5580
|
-
this.output.error("ERROR: " + e);
|
|
5581
|
-
}
|
|
5582
|
-
});
|
|
5583
|
-
/**
|
|
5584
|
-
* Drop all tables and re-run all migrations
|
|
5585
|
-
*/
|
|
5586
|
-
program.command("migrate:fresh").description("Drop all tables and re-run all migrations.").option("-p, --path [path]", "The path to the migrations directory.").action(async (opts) => {
|
|
5587
|
-
if (!this.configPath) this.terminateNotFound();
|
|
5588
|
-
const basePath = opts.path ? path.join(this.cwd, opts.path) : this.cwd;
|
|
5589
|
-
try {
|
|
5590
|
-
await new Migrate(basePath, void 0, (msg, sts) => {
|
|
5591
|
-
if (sts) this.output[sts](msg);
|
|
5592
|
-
}).fresh(this.config, opts, true);
|
|
5593
|
-
} catch (e) {
|
|
5594
|
-
this.output.error("ERROR: " + e);
|
|
5595
|
-
}
|
|
5596
|
-
});
|
|
5597
|
-
/**
|
|
5598
|
-
* Check the migration status
|
|
5599
|
-
*/
|
|
5600
|
-
program.command("migrate:status").description("Show the status of each migration.").option("-p, --path [path]", "The path to the migrations directory.").action(async (opts) => {
|
|
5601
|
-
if (!this.configPath) this.terminateNotFound();
|
|
5602
|
-
const basePath = opts.path ? path.join(this.cwd, opts.path) : this.cwd;
|
|
5603
|
-
try {
|
|
5604
|
-
const migrations = await new Migrate(basePath, void 0, (msg, sts) => {
|
|
5605
|
-
if (sts) this.output[sts](msg);
|
|
5606
|
-
}).status(this.config, opts, true);
|
|
5607
|
-
if (migrations.length > 0) {
|
|
5608
|
-
Logger.twoColumnDetail(Logger.log("Migration name", "gray", false), Logger.log("Batch / Status", "gray", false));
|
|
5609
|
-
migrations.forEach((migration) => {
|
|
5610
|
-
const status = migration.ran ? `[${migration.batch}] ${Logger.log("Ran", "green", false)}` : Logger.log("Pending", "yellow", false);
|
|
5611
|
-
Logger.twoColumnDetail(migration.name, status);
|
|
5612
|
-
});
|
|
5613
|
-
} else console.log("No migrations found");
|
|
5614
|
-
} catch (e) {
|
|
5615
|
-
this.output.error("ERROR: " + e);
|
|
5616
|
-
}
|
|
5617
|
-
});
|
|
5618
|
-
/**
|
|
5619
|
-
* Run database seeders
|
|
5620
|
-
*/
|
|
5621
|
-
program.command("db:seed").description("Run database seeders.").option("-p, --path [path]", "The path to the seeders directory.").action(async (opts) => {
|
|
5622
|
-
if (!this.configPath) this.terminateNotFound();
|
|
5623
|
-
const basePath = opts.path ? path.join(this.cwd, opts.path) : this.cwd;
|
|
5624
|
-
try {
|
|
5625
|
-
var _this$config$seeders;
|
|
5626
|
-
const { arquebus } = await new Migrate(basePath).setupConnection({
|
|
5627
|
-
...this.config,
|
|
5628
|
-
skipConnection: false
|
|
5629
|
-
});
|
|
5630
|
-
const { SeederRunner } = await Promise.resolve().then(() => seeders_exports);
|
|
5631
|
-
const runner = new SeederRunner(arquebus);
|
|
5632
|
-
const seederPath = path.join(basePath, ((_this$config$seeders = this.config.seeders) === null || _this$config$seeders === void 0 ? void 0 : _this$config$seeders.path) ?? "./seeders");
|
|
5633
|
-
await runner.setConnection(this.config.client).run([seederPath]);
|
|
5634
|
-
this.output.success("Seeders executed successfully.");
|
|
5635
|
-
} catch (e) {
|
|
5636
|
-
this.output.error("ERROR: " + e);
|
|
5635
|
+
const kernel = new Kernel(this).setCwd(this.cwd).setConfig({
|
|
5636
|
+
baseCommands: ArquebusCommands,
|
|
5637
|
+
name: "arquebus",
|
|
5638
|
+
hideMusketInfo: true,
|
|
5639
|
+
versionSeparator: "\n"
|
|
5640
|
+
}).bootstrap();
|
|
5641
|
+
kernel.modules = [{
|
|
5642
|
+
name: "@h3ravel/arquebus",
|
|
5643
|
+
label: "Arquebus CLI version",
|
|
5644
|
+
version
|
|
5645
|
+
}, {
|
|
5646
|
+
name: "@h3ravel/arquebus",
|
|
5647
|
+
label: "Arquebus Local version",
|
|
5648
|
+
version: this.modulePackage.version || "N/A"
|
|
5649
|
+
}];
|
|
5650
|
+
return await kernel.run();
|
|
5651
|
+
}
|
|
5652
|
+
async initialize(type = "js") {
|
|
5653
|
+
if (!this.modulePath) this.output.error(["ERROR: No local arquebus install found", " Try running: pnpm add @h3ravel/arquebus"]);
|
|
5654
|
+
if (this.configPath) this.output.error(`ERROR: ${this.configPath} already exists`);
|
|
5655
|
+
try {
|
|
5656
|
+
const stubPath = `./arquebus.config.${type}`;
|
|
5657
|
+
const code = await readFile(await this.resolveStub(`arquebus.config-${type}.stub`), "utf8");
|
|
5658
|
+
await writeFile(path$1.join(this.cwd, stubPath), code);
|
|
5659
|
+
this.output.success(`Initialized: Arquebus has been initialized as ${stubPath}`);
|
|
5660
|
+
} catch (error) {
|
|
5661
|
+
this.output.error("ERROR: " + error);
|
|
5662
|
+
}
|
|
5663
|
+
}
|
|
5664
|
+
async makeMigration(rawName, options) {
|
|
5665
|
+
this.ensureConfigured();
|
|
5666
|
+
try {
|
|
5667
|
+
const name = Str.snake(rawName);
|
|
5668
|
+
const migrationPath = path$1.join(this.cwd, options.path ?? this.config.migrations?.path ?? "./migrations");
|
|
5669
|
+
let table = options.table;
|
|
5670
|
+
let create = Boolean(options.create) && options.create !== "";
|
|
5671
|
+
if (!table && typeof options.create === "string") {
|
|
5672
|
+
table = options.create;
|
|
5673
|
+
create = true;
|
|
5637
5674
|
}
|
|
5638
|
-
|
|
5639
|
-
|
|
5640
|
-
|
|
5641
|
-
|
|
5642
|
-
program.command("make:seeder <name>").description("Create a new Seeder file.").addOption(new Option("-l, --type [string]", "Type of seeder file to generate.").choices(["js", "ts"]).default("js", "generates a js seeder file")).option("--force", "Force creation if seeder already exists.", false).option("-p, --path [path]", "The path to the seeders directory.").action(async (name, opts) => {
|
|
5643
|
-
var _this$config$seeders2;
|
|
5644
|
-
if (!this.configPath) this.terminateNotFound();
|
|
5645
|
-
const seederPath = path.join(this.cwd, opts.path ?? ((_this$config$seeders2 = this.config.seeders) === null || _this$config$seeders2 === void 0 ? void 0 : _this$config$seeders2.path) ?? "./seeders", Str.of(name).snake("-") + "." + opts.type);
|
|
5646
|
-
try {
|
|
5647
|
-
if (!opts.force && await FileSystem.fileExists(seederPath)) this.output.error("ERROR: Seeder already exists.");
|
|
5648
|
-
await mkdir(path.dirname(seederPath), { recursive: true });
|
|
5649
|
-
let stub = await readFile(path.join(this.modulePath, `src/stubs/seeder-${opts.type}.stub`), "utf-8");
|
|
5650
|
-
stub = stub.replace(/{{ name }}/g, name);
|
|
5651
|
-
await writeFile(seederPath, stub);
|
|
5652
|
-
this.output.split("INFO: Created Seeder", path.relative(this.cwd, seederPath));
|
|
5653
|
-
} catch (e) {
|
|
5654
|
-
this.output.error("ERROR: " + e);
|
|
5675
|
+
if (!table) {
|
|
5676
|
+
const guessed = TableGuesser.guess(name);
|
|
5677
|
+
table = guessed[0];
|
|
5678
|
+
create = Boolean(guessed[1]);
|
|
5655
5679
|
}
|
|
5656
|
-
|
|
5657
|
-
|
|
5658
|
-
|
|
5659
|
-
|
|
5660
|
-
|
|
5661
|
-
|
|
5662
|
-
|
|
5663
|
-
|
|
5664
|
-
|
|
5665
|
-
|
|
5666
|
-
|
|
5667
|
-
|
|
5668
|
-
|
|
5669
|
-
|
|
5670
|
-
|
|
5671
|
-
|
|
5672
|
-
|
|
5680
|
+
this.output.info("INFO: Creating Migration");
|
|
5681
|
+
const fileName = await new MigrationCreator(void 0, options.type ?? "js").create(name, migrationPath, table, create);
|
|
5682
|
+
this.output.success(`INFO: Migration Created \n ${Logger.log(path$1.basename(fileName), "gray", false)}`, true);
|
|
5683
|
+
} catch (error) {
|
|
5684
|
+
this.output.error("ERROR: " + error);
|
|
5685
|
+
}
|
|
5686
|
+
}
|
|
5687
|
+
async publishMigrations(pkg, options) {
|
|
5688
|
+
this.ensureConfigured();
|
|
5689
|
+
try {
|
|
5690
|
+
const packagePath = Utils.findModulePkg(pkg) ?? "";
|
|
5691
|
+
if (!packagePath) this.output.error(`ERROR: package ${pkg} not found`);
|
|
5692
|
+
const basePath = path$1.join(this.cwd, options.path ?? this.config.migrations?.path ?? "./migrations");
|
|
5693
|
+
const pkgJson = JSON.parse(await readFile(path$1.join(packagePath, "package.json"), "utf8"));
|
|
5694
|
+
const creator = new MigrationCreator(path$1.join(packagePath, pkgJson.migrations ?? "migrations"));
|
|
5695
|
+
const pkgInfo = Logger.log(path$1.basename(pkgJson.name + "@" + pkgJson.version), ["italic", "gray"], false);
|
|
5696
|
+
this.output.info(`INFO: Publishing migrations from ${pkgInfo}`);
|
|
5697
|
+
await creator.publish(basePath, (fileName) => {
|
|
5698
|
+
this.output.split("INFO: Migration Published", fileName, "success");
|
|
5699
|
+
});
|
|
5700
|
+
} catch (error) {
|
|
5701
|
+
this.output.error("ERROR: " + error);
|
|
5702
|
+
}
|
|
5703
|
+
}
|
|
5704
|
+
async migrate(options) {
|
|
5705
|
+
this.ensureConfigured();
|
|
5706
|
+
const basePath = this.resolveBasePath(options.path);
|
|
5707
|
+
try {
|
|
5708
|
+
const step = typeof options.step === "string" ? Number.parseInt(options.step) : options.step;
|
|
5709
|
+
await new Migrate(basePath).run(this.config, {
|
|
5710
|
+
...options,
|
|
5711
|
+
step
|
|
5712
|
+
}, true);
|
|
5713
|
+
} catch (error) {
|
|
5714
|
+
this.output.error("ERROR: " + error);
|
|
5715
|
+
}
|
|
5716
|
+
}
|
|
5717
|
+
async rollback(options) {
|
|
5718
|
+
this.ensureConfigured();
|
|
5719
|
+
const basePath = this.resolveBasePath(options.path);
|
|
5720
|
+
try {
|
|
5721
|
+
const step = typeof options.step === "string" ? Number.parseInt(options.step) : options.step;
|
|
5722
|
+
await new Migrate(basePath, void 0, this.migrationReporter()).rollback(this.config, {
|
|
5723
|
+
...options,
|
|
5724
|
+
step
|
|
5725
|
+
}, true);
|
|
5726
|
+
} catch (error) {
|
|
5727
|
+
this.output.error("ERROR: " + error);
|
|
5728
|
+
}
|
|
5729
|
+
}
|
|
5730
|
+
async reset(options) {
|
|
5731
|
+
await this.runMigrationOperation("reset", options);
|
|
5732
|
+
}
|
|
5733
|
+
async refresh(options) {
|
|
5734
|
+
await this.runMigrationOperation("refresh", options);
|
|
5735
|
+
}
|
|
5736
|
+
async fresh(options) {
|
|
5737
|
+
await this.runMigrationOperation("fresh", options);
|
|
5738
|
+
}
|
|
5739
|
+
async runMigrationOperation(operation, options) {
|
|
5740
|
+
this.ensureConfigured();
|
|
5741
|
+
const basePath = this.resolveBasePath(options.path);
|
|
5742
|
+
try {
|
|
5743
|
+
await new Migrate(basePath, void 0, this.migrationReporter())[operation](this.config, options, true);
|
|
5744
|
+
} catch (error) {
|
|
5745
|
+
this.output.error("ERROR: " + error);
|
|
5746
|
+
}
|
|
5747
|
+
}
|
|
5748
|
+
async status(options) {
|
|
5749
|
+
this.ensureConfigured();
|
|
5750
|
+
const basePath = this.resolveBasePath(options.path);
|
|
5751
|
+
try {
|
|
5752
|
+
const migrations = await new Migrate(basePath, void 0, this.migrationReporter()).status(this.config, options, true);
|
|
5753
|
+
if (migrations.length === 0) {
|
|
5754
|
+
this.output.info("No migrations found");
|
|
5755
|
+
return;
|
|
5673
5756
|
}
|
|
5674
|
-
|
|
5675
|
-
|
|
5676
|
-
|
|
5757
|
+
Logger.twoColumnDetail(Logger.log("Migration name", "gray", false), Logger.log("Batch / Status", "gray", false));
|
|
5758
|
+
migrations.forEach((migration) => {
|
|
5759
|
+
const status = migration.ran ? `[${migration.batch}] ${Logger.log("Ran", "green", false)}` : Logger.log("Pending", "yellow", false);
|
|
5760
|
+
Logger.twoColumnDetail(migration.name, status);
|
|
5761
|
+
});
|
|
5762
|
+
} catch (error) {
|
|
5763
|
+
this.output.error("ERROR: " + error);
|
|
5764
|
+
}
|
|
5765
|
+
}
|
|
5766
|
+
async seed(options) {
|
|
5767
|
+
this.ensureConfigured();
|
|
5768
|
+
const basePath = this.resolveBasePath(options.path);
|
|
5769
|
+
try {
|
|
5770
|
+
const { arquebus } = await new Migrate(basePath).setupConnection({
|
|
5771
|
+
...this.config,
|
|
5772
|
+
skipConnection: false
|
|
5773
|
+
});
|
|
5774
|
+
const seederPath = path$1.join(basePath, this.config.seeders?.path ?? "./seeders");
|
|
5775
|
+
await new SeederRunner(arquebus).setConnection(this.config.client).run([seederPath]);
|
|
5776
|
+
this.output.success("Seeders executed successfully.");
|
|
5777
|
+
} catch (error) {
|
|
5778
|
+
this.output.error("ERROR: " + error);
|
|
5779
|
+
}
|
|
5780
|
+
}
|
|
5781
|
+
async makeSeeder(name, options) {
|
|
5782
|
+
this.ensureConfigured();
|
|
5783
|
+
const type = options.type ?? "js";
|
|
5784
|
+
const seederPath = path$1.join(this.cwd, options.path ?? this.config.seeders?.path ?? "./seeders", `${Str.of(name).snake("-")}.${type}`);
|
|
5785
|
+
try {
|
|
5786
|
+
if (!options.force && await FileSystem.fileExists(seederPath)) this.output.error("ERROR: Seeder already exists.");
|
|
5787
|
+
await mkdir(path$1.dirname(seederPath), { recursive: true });
|
|
5788
|
+
await writeFile(seederPath, (await readFile(await this.resolveStub(`seeder-${type}.stub`), "utf8")).replace(/{{ name }}/g, name));
|
|
5789
|
+
this.output.split("INFO: Created Seeder", path$1.relative(this.cwd, seederPath));
|
|
5790
|
+
} catch (error) {
|
|
5791
|
+
this.output.error("ERROR: " + error);
|
|
5792
|
+
}
|
|
5793
|
+
}
|
|
5794
|
+
async makeModel(name, options) {
|
|
5795
|
+
this.ensureConfigured();
|
|
5796
|
+
const type = options.type ?? "js";
|
|
5797
|
+
const modelPath = path$1.join(this.cwd, options.path ?? this.config.models?.path ?? "./models", `${name.toLowerCase()}.${type}`);
|
|
5798
|
+
try {
|
|
5799
|
+
if (!options.force && await FileSystem.fileExists(modelPath)) this.output.error("ERROR: Model already exists.");
|
|
5800
|
+
await mkdir(path$1.dirname(modelPath), { recursive: true });
|
|
5801
|
+
await writeFile(modelPath, (await readFile(await this.resolveStub(`model-${type}.stub`), "utf8")).replace(/{{ name }}/g, name));
|
|
5802
|
+
this.output.success(`Created Model: ${modelPath}`);
|
|
5803
|
+
} catch (error) {
|
|
5804
|
+
this.output.error("ERROR: " + error);
|
|
5805
|
+
}
|
|
5677
5806
|
}
|
|
5678
5807
|
}).init();
|
|
5679
5808
|
//#endregion
|