@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.cjs
CHANGED
|
@@ -30,63 +30,192 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
30
30
|
enumerable: true
|
|
31
31
|
}) : target, mod));
|
|
32
32
|
//#endregion
|
|
33
|
-
let commander = require("commander");
|
|
34
33
|
let _h3ravel_shared = require("@h3ravel/shared");
|
|
35
|
-
let
|
|
36
|
-
|
|
37
|
-
let resolve_from = require("resolve-from");
|
|
38
|
-
resolve_from = __toESM(resolve_from, 1);
|
|
34
|
+
let _h3ravel_musket = require("@h3ravel/musket");
|
|
35
|
+
let _h3ravel_support = require("@h3ravel/support");
|
|
39
36
|
let node_fs_promises = require("node:fs/promises");
|
|
40
37
|
node_fs_promises = __toESM(node_fs_promises, 1);
|
|
38
|
+
let path = require("path");
|
|
39
|
+
path = __toESM(path, 1);
|
|
41
40
|
let node_path = require("node:path");
|
|
41
|
+
node_path = __toESM(node_path, 1);
|
|
42
|
+
let node_fs = require("node:fs");
|
|
42
43
|
let node_url = require("node:url");
|
|
43
|
-
let radashi = require("radashi");
|
|
44
|
-
let dayjs_plugin_advancedFormat_js = require("dayjs/plugin/advancedFormat.js");
|
|
45
|
-
dayjs_plugin_advancedFormat_js = __toESM(dayjs_plugin_advancedFormat_js, 1);
|
|
46
44
|
let dayjs = require("dayjs");
|
|
47
45
|
dayjs = __toESM(dayjs, 1);
|
|
48
|
-
let
|
|
49
|
-
|
|
46
|
+
let dayjs_plugin_advancedFormat_js = require("dayjs/plugin/advancedFormat.js");
|
|
47
|
+
dayjs_plugin_advancedFormat_js = __toESM(dayjs_plugin_advancedFormat_js, 1);
|
|
48
|
+
let _h3ravel_collect_js = require("@h3ravel/collect.js");
|
|
50
49
|
let knex = require("knex");
|
|
51
50
|
knex = __toESM(knex, 1);
|
|
52
51
|
let fs = require("fs");
|
|
53
52
|
let pluralize = require("pluralize");
|
|
54
53
|
pluralize = __toESM(pluralize, 1);
|
|
55
|
-
let
|
|
54
|
+
let resolve_from = require("resolve-from");
|
|
55
|
+
resolve_from = __toESM(resolve_from, 1);
|
|
56
56
|
let dotenv = require("dotenv");
|
|
57
|
-
//#region src/cli/
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
const packageJson = path.default.join(packageName, "package.json");
|
|
66
|
-
const resolved = resolve_from.default.silent(cwd ?? process.cwd(), packageJson);
|
|
67
|
-
if (!resolved) return;
|
|
68
|
-
return path.default.join(path.default.dirname(resolved), parts.join("/"));
|
|
57
|
+
//#region src/cli/commands.ts
|
|
58
|
+
var ArquebusCommand = class extends _h3ravel_musket.Command {
|
|
59
|
+
pathOption(signature) {
|
|
60
|
+
return signature.option("path", {
|
|
61
|
+
short: "p",
|
|
62
|
+
optionalValue: true,
|
|
63
|
+
description: "The path used by the command."
|
|
64
|
+
});
|
|
69
65
|
}
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
66
|
+
};
|
|
67
|
+
var InitCommand = class extends ArquebusCommand {
|
|
68
|
+
buildSignature(signature) {
|
|
69
|
+
return signature.command("init").describe("Create a fresh Arquebus config.").argument("type", {
|
|
70
|
+
required: false,
|
|
71
|
+
default: "js",
|
|
72
|
+
choices: ["js", "ts"],
|
|
73
|
+
description: "Type of config to generate."
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
async handle() {
|
|
77
|
+
await this.app.initialize(this.argument("type", "js"));
|
|
73
78
|
}
|
|
74
79
|
};
|
|
75
|
-
var
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
}
|
|
87
|
-
|
|
80
|
+
var MakeMigrationCommand = class extends ArquebusCommand {
|
|
81
|
+
buildSignature(signature) {
|
|
82
|
+
return this.pathOption(signature.command("make:migration").describe("Create a new migration file.").argument("name", { description: "The migration name." }).option("type", {
|
|
83
|
+
short: "l",
|
|
84
|
+
default: "js",
|
|
85
|
+
choices: ["js", "ts"],
|
|
86
|
+
description: "Type of migration file to generate."
|
|
87
|
+
}).option("table", {
|
|
88
|
+
short: "t",
|
|
89
|
+
optionalValue: true,
|
|
90
|
+
description: "The table to migrate."
|
|
91
|
+
}).option("create", {
|
|
92
|
+
short: "c",
|
|
93
|
+
optionalValue: true,
|
|
94
|
+
description: "The table to create."
|
|
95
|
+
}));
|
|
96
|
+
}
|
|
97
|
+
async handle() {
|
|
98
|
+
await this.app.makeMigration(this.argument("name"), this.options());
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
var PublishMigrationsCommand = class extends ArquebusCommand {
|
|
102
|
+
buildSignature(signature) {
|
|
103
|
+
return this.pathOption(signature.command("migrate:publish").describe("Publish migration files from a package.").argument("package", { description: "The package to publish from." }));
|
|
104
|
+
}
|
|
105
|
+
async handle() {
|
|
106
|
+
await this.app.publishMigrations(this.argument("package"), this.options());
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
var MigrationPathCommand = class extends ArquebusCommand {
|
|
110
|
+
buildSignature(signature) {
|
|
111
|
+
return this.pathOption(signature.command(this.commandName).describe(this.commandDescription));
|
|
112
|
+
}
|
|
113
|
+
async handle() {
|
|
114
|
+
await this.execute(this.options());
|
|
88
115
|
}
|
|
89
116
|
};
|
|
117
|
+
var MigrateCommand = class extends ArquebusCommand {
|
|
118
|
+
buildSignature(signature) {
|
|
119
|
+
return this.pathOption(signature.command("migrate").describe("Run all pending migrations.").option("step", {
|
|
120
|
+
short: "s",
|
|
121
|
+
optionalValue: true,
|
|
122
|
+
description: "Run migrations in individual batches."
|
|
123
|
+
}));
|
|
124
|
+
}
|
|
125
|
+
async handle() {
|
|
126
|
+
await this.app.migrate(this.options());
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
var RollbackCommand = class extends ArquebusCommand {
|
|
130
|
+
buildSignature(signature) {
|
|
131
|
+
return this.pathOption(signature.command("migrate:rollback").describe("Rollback the last database migration.").option("step", {
|
|
132
|
+
short: "s",
|
|
133
|
+
optionalValue: true,
|
|
134
|
+
description: "The number of migrations to revert."
|
|
135
|
+
}));
|
|
136
|
+
}
|
|
137
|
+
async handle() {
|
|
138
|
+
await this.app.rollback(this.options());
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
var ResetCommand = class extends MigrationPathCommand {
|
|
142
|
+
commandName = "migrate:reset";
|
|
143
|
+
commandDescription = "Rollback all database migrations.";
|
|
144
|
+
execute(options) {
|
|
145
|
+
return this.app.reset(options);
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
var RefreshCommand = class extends MigrationPathCommand {
|
|
149
|
+
commandName = "migrate:refresh";
|
|
150
|
+
commandDescription = "Reset and re-run all migrations.";
|
|
151
|
+
execute(options) {
|
|
152
|
+
return this.app.refresh(options);
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
var FreshCommand = class extends MigrationPathCommand {
|
|
156
|
+
commandName = "migrate:fresh";
|
|
157
|
+
commandDescription = "Drop all tables and re-run all migrations.";
|
|
158
|
+
execute(options) {
|
|
159
|
+
return this.app.fresh(options);
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
var MigrationStatusCommand = class extends MigrationPathCommand {
|
|
163
|
+
commandName = "migrate:status";
|
|
164
|
+
commandDescription = "Show the status of each migration.";
|
|
165
|
+
execute(options) {
|
|
166
|
+
return this.app.status(options);
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
var SeedCommand = class extends MigrationPathCommand {
|
|
170
|
+
commandName = "db:seed";
|
|
171
|
+
commandDescription = "Run database seeders.";
|
|
172
|
+
execute(options) {
|
|
173
|
+
return this.app.seed(options);
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
var MakeFileCommand = class extends ArquebusCommand {
|
|
177
|
+
buildSignature(signature) {
|
|
178
|
+
return this.pathOption(signature.command(this.commandName).describe(this.commandDescription).argument("name", { description: `The ${this.fileDescription} name.` }).option("type", {
|
|
179
|
+
short: "l",
|
|
180
|
+
default: "js",
|
|
181
|
+
choices: ["js", "ts"],
|
|
182
|
+
description: `Type of ${this.fileDescription} file to generate.`
|
|
183
|
+
}).option("force", { description: `Overwrite an existing ${this.fileDescription} file.` }));
|
|
184
|
+
}
|
|
185
|
+
async handle() {
|
|
186
|
+
await this.execute(this.argument("name"), this.options());
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
var MakeSeederCommand = class extends MakeFileCommand {
|
|
190
|
+
commandName = "make:seeder";
|
|
191
|
+
commandDescription = "Create a new seeder file.";
|
|
192
|
+
fileDescription = "seeder";
|
|
193
|
+
execute(name, options) {
|
|
194
|
+
return this.app.makeSeeder(name, options);
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
var MakeModelCommand = class extends MakeFileCommand {
|
|
198
|
+
commandName = "make:model";
|
|
199
|
+
commandDescription = "Create a new model file.";
|
|
200
|
+
fileDescription = "model";
|
|
201
|
+
execute(name, options) {
|
|
202
|
+
return this.app.makeModel(name, options);
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
const ArquebusCommands = [
|
|
206
|
+
InitCommand,
|
|
207
|
+
MakeMigrationCommand,
|
|
208
|
+
PublishMigrationsCommand,
|
|
209
|
+
MigrateCommand,
|
|
210
|
+
RollbackCommand,
|
|
211
|
+
ResetCommand,
|
|
212
|
+
RefreshCommand,
|
|
213
|
+
FreshCommand,
|
|
214
|
+
MigrationStatusCommand,
|
|
215
|
+
SeedCommand,
|
|
216
|
+
MakeSeederCommand,
|
|
217
|
+
MakeModelCommand
|
|
218
|
+
];
|
|
90
219
|
//#endregion
|
|
91
220
|
//#region src/migrations/migration-repository.ts
|
|
92
221
|
var MigrationRepository = class {
|
|
@@ -233,8 +362,7 @@ var CockroachDB = class {
|
|
|
233
362
|
*/
|
|
234
363
|
async hasTable(table) {
|
|
235
364
|
const subquery = this.knex.select().from("information_schema.tables").whereIn("table_schema", this.explodedSchema).andWhere({ table_name: table });
|
|
236
|
-
|
|
237
|
-
return (record === null || record === void 0 ? void 0 : record.exists) || false;
|
|
365
|
+
return (await this.knex.select(this.knex.raw("exists (?)", [subquery])).first())?.exists || false;
|
|
238
366
|
}
|
|
239
367
|
/**
|
|
240
368
|
* Get all the available columns in the current schema/database. Can be filtered to a specific table
|
|
@@ -334,18 +462,17 @@ var CockroachDB = class {
|
|
|
334
462
|
${column ? "AND att.attname = ?" : ""}
|
|
335
463
|
`, bindings)]);
|
|
336
464
|
const parsedColumms = columns.rows.map((col) => {
|
|
337
|
-
var _col$default_value;
|
|
338
465
|
const constraintsForColumn = constraints.rows.filter((constraint) => constraint.table === col.table && constraint.column === col.name);
|
|
339
466
|
const foreignKeyConstraint = constraintsForColumn.find((constraint) => constraint.type === "f");
|
|
340
467
|
return {
|
|
341
468
|
...col,
|
|
342
469
|
is_unique: constraintsForColumn.some((constraint) => ["u", "p"].includes(constraint.type)),
|
|
343
470
|
is_primary_key: constraintsForColumn.some((constraint) => constraint.type === "p"),
|
|
344
|
-
has_auto_increment: ["integer", "bigint"].includes(col.data_type) && (
|
|
471
|
+
has_auto_increment: ["integer", "bigint"].includes(col.data_type) && (col.default_value?.startsWith("nextval(") ?? false),
|
|
345
472
|
default_value: parseDefaultValue$5(col.default_value),
|
|
346
|
-
foreign_key_schema:
|
|
347
|
-
foreign_key_table:
|
|
348
|
-
foreign_key_column:
|
|
473
|
+
foreign_key_schema: foreignKeyConstraint?.foreign_key_schema ?? null,
|
|
474
|
+
foreign_key_table: foreignKeyConstraint?.foreign_key_table ?? null,
|
|
475
|
+
foreign_key_column: foreignKeyConstraint?.foreign_key_column ?? null
|
|
349
476
|
};
|
|
350
477
|
});
|
|
351
478
|
if (table && column) return parsedColumms[0];
|
|
@@ -359,8 +486,7 @@ var CockroachDB = class {
|
|
|
359
486
|
table_name: table,
|
|
360
487
|
column_name: column
|
|
361
488
|
});
|
|
362
|
-
|
|
363
|
-
return (record === null || record === void 0 ? void 0 : record.exists) || false;
|
|
489
|
+
return (await this.knex.select(this.knex.raw("exists (?)", [subquery])).first())?.exists || false;
|
|
364
490
|
}
|
|
365
491
|
/**
|
|
366
492
|
* Get the primary key column for the given table
|
|
@@ -672,14 +798,13 @@ var MSSQL = class {
|
|
|
672
798
|
WHERE
|
|
673
799
|
OBJECT_SCHEMA_NAME (f.parent_object_id) = ?;
|
|
674
800
|
`, [this.schema]);
|
|
675
|
-
if (table) return result
|
|
801
|
+
if (table) return result?.filter((row) => row.table === table);
|
|
676
802
|
return result;
|
|
677
803
|
}
|
|
678
804
|
};
|
|
679
805
|
//#endregion
|
|
680
806
|
//#region src/inspector/dialects/mysql.ts
|
|
681
807
|
function rawColumnToColumn$1(rawColumn) {
|
|
682
|
-
var _rawColumn$EXTRA;
|
|
683
808
|
let dataType = rawColumn.COLUMN_TYPE.replace(/\(.*?\)/, "");
|
|
684
809
|
if (rawColumn.COLUMN_TYPE.startsWith("tinyint(1)")) dataType = "boolean";
|
|
685
810
|
return {
|
|
@@ -692,7 +817,7 @@ function rawColumnToColumn$1(rawColumn) {
|
|
|
692
817
|
max_length: rawColumn.CHARACTER_MAXIMUM_LENGTH,
|
|
693
818
|
numeric_precision: rawColumn.NUMERIC_PRECISION,
|
|
694
819
|
numeric_scale: rawColumn.NUMERIC_SCALE,
|
|
695
|
-
is_generated: !!
|
|
820
|
+
is_generated: !!rawColumn.EXTRA?.endsWith("GENERATED"),
|
|
696
821
|
is_nullable: rawColumn.IS_NULLABLE === "YES",
|
|
697
822
|
is_unique: rawColumn.COLUMN_KEY === "UNI",
|
|
698
823
|
is_primary_key: rawColumn.CONSTRAINT_NAME === "PRIMARY" || rawColumn.COLUMN_KEY === "PRI",
|
|
@@ -885,11 +1010,10 @@ var oracleDB = class {
|
|
|
885
1010
|
* Check if a table exists in the current schema/database
|
|
886
1011
|
*/
|
|
887
1012
|
async hasTable(table) {
|
|
888
|
-
|
|
1013
|
+
return !!(await this.knex.select(this.knex.raw(`
|
|
889
1014
|
/*+ OPTIMIZER_FEATURES_ENABLE('${OPTIMIZER_FEATURES}') */
|
|
890
1015
|
COUNT(*) "count"
|
|
891
|
-
`)).from("USER_TABLES").where({ TABLE_NAME: table }).first();
|
|
892
|
-
return !!(result === null || result === void 0 ? void 0 : result.count);
|
|
1016
|
+
`)).from("USER_TABLES").where({ TABLE_NAME: table }).first())?.count;
|
|
893
1017
|
}
|
|
894
1018
|
/**
|
|
895
1019
|
* Get all the available columns in the current schema/database. Can be filtered to a specific table
|
|
@@ -965,15 +1089,14 @@ var oracleDB = class {
|
|
|
965
1089
|
* Check if a table exists in the current schema/database
|
|
966
1090
|
*/
|
|
967
1091
|
async hasColumn(table, column) {
|
|
968
|
-
|
|
1092
|
+
return !!(await this.knex.select(this.knex.raw(`
|
|
969
1093
|
/*+ OPTIMIZER_FEATURES_ENABLE('${OPTIMIZER_FEATURES}') NO_QUERY_TRANSFORMATION */
|
|
970
1094
|
COUNT(*) "count"
|
|
971
1095
|
`)).from("USER_TAB_COLS").where({
|
|
972
1096
|
TABLE_NAME: table,
|
|
973
1097
|
COLUMN_NAME: column,
|
|
974
1098
|
HIDDEN_COLUMN: "NO"
|
|
975
|
-
}).first();
|
|
976
|
-
return !!(result === null || result === void 0 ? void 0 : result.count);
|
|
1099
|
+
}).first())?.count;
|
|
977
1100
|
}
|
|
978
1101
|
/**
|
|
979
1102
|
* Get the primary key column for the given table
|
|
@@ -1139,13 +1262,12 @@ var Postgres = class {
|
|
|
1139
1262
|
`, bindings)).rows;
|
|
1140
1263
|
}
|
|
1141
1264
|
async columnInfo(table, column) {
|
|
1142
|
-
var _versionResponse$rows;
|
|
1143
1265
|
const { knex } = this;
|
|
1144
1266
|
const bindings = [];
|
|
1145
1267
|
if (table) bindings.push(table);
|
|
1146
1268
|
if (column) bindings.push(column);
|
|
1147
1269
|
const schemaIn = this.explodedSchema.map((schemaName) => `${this.knex.raw("?", [schemaName])}::regnamespace`);
|
|
1148
|
-
const majorVersion = (
|
|
1270
|
+
const majorVersion = (await this.knex.raw("SHOW server_version")).rows?.[0]?.server_version?.split(".")?.[0] ?? 10;
|
|
1149
1271
|
let generationSelect = `
|
|
1150
1272
|
NULL AS generation_expression,
|
|
1151
1273
|
pg_get_expr(ad.adbin, ad.adrelid) AS default_value,
|
|
@@ -1237,9 +1359,9 @@ var Postgres = class {
|
|
|
1237
1359
|
is_primary_key: constraintsForColumn.some((constraint) => constraint.type === "p"),
|
|
1238
1360
|
has_auto_increment: constraintsForColumn.some((constraint) => constraint.has_auto_increment),
|
|
1239
1361
|
default_value: parseDefaultValue$1(col.default_value),
|
|
1240
|
-
foreign_key_schema:
|
|
1241
|
-
foreign_key_table:
|
|
1242
|
-
foreign_key_column:
|
|
1362
|
+
foreign_key_schema: foreignKeyConstraint?.foreign_key_schema ?? null,
|
|
1363
|
+
foreign_key_table: foreignKeyConstraint?.foreign_key_table ?? null,
|
|
1364
|
+
foreign_key_column: foreignKeyConstraint?.foreign_key_column ?? null
|
|
1243
1365
|
};
|
|
1244
1366
|
});
|
|
1245
1367
|
if (table && column) return parsedColumms[0];
|
|
@@ -1411,16 +1533,14 @@ var SeederRunner = class {
|
|
|
1411
1533
|
this.resolver = resolver;
|
|
1412
1534
|
}
|
|
1413
1535
|
path(p) {
|
|
1414
|
-
this.paths = Array.from(new Set([...this.paths, p]));
|
|
1536
|
+
this.paths = Array.from(/* @__PURE__ */ new Set([...this.paths, p]));
|
|
1415
1537
|
}
|
|
1416
1538
|
getPaths() {
|
|
1417
1539
|
return this.paths;
|
|
1418
1540
|
}
|
|
1419
1541
|
resolveConnection(connection) {
|
|
1420
|
-
var _getInstance, _ref, _instance$connections;
|
|
1421
1542
|
const name = connection || this.connection || "default";
|
|
1422
|
-
|
|
1423
|
-
if (!!!(instance === null || instance === void 0 || (_instance$connections = instance.connections) === null || _instance$connections === void 0 ? void 0 : _instance$connections[name])) this.resolver.autoLoad().catch(() => {
|
|
1543
|
+
if (!!!(this.resolver.getInstance?.() ?? null)?.connections?.[name]) this.resolver.autoLoad().catch(() => {
|
|
1424
1544
|
/** noop */
|
|
1425
1545
|
});
|
|
1426
1546
|
return this.resolver.fire(name);
|
|
@@ -1458,9 +1578,6 @@ var SeederRunner = class {
|
|
|
1458
1578
|
}
|
|
1459
1579
|
};
|
|
1460
1580
|
//#endregion
|
|
1461
|
-
//#region src/seeders/index.ts
|
|
1462
|
-
var seeders_exports = /* @__PURE__ */ __exportAll({ SeederRunner: () => SeederRunner });
|
|
1463
|
-
//#endregion
|
|
1464
1581
|
//#region src/casts/attribute.ts
|
|
1465
1582
|
var Attribute = class Attribute {
|
|
1466
1583
|
get;
|
|
@@ -1510,7 +1627,7 @@ var ModelNotFoundError = class extends BaseError {
|
|
|
1510
1627
|
}
|
|
1511
1628
|
setModel(model, ids = []) {
|
|
1512
1629
|
this.model = model;
|
|
1513
|
-
this.ids =
|
|
1630
|
+
this.ids = Array.isArray(ids) ? ids : [ids];
|
|
1514
1631
|
this.message = `No query results for model [${model}]`;
|
|
1515
1632
|
if (this.ids.length > 0) this.message += " " + this.ids.join(", ");
|
|
1516
1633
|
else this.message += ".";
|
|
@@ -1601,25 +1718,29 @@ function compose$1(Base, ...mixins) {
|
|
|
1601
1718
|
}, Base);
|
|
1602
1719
|
}
|
|
1603
1720
|
//#endregion
|
|
1721
|
+
//#region src/dayjs.ts
|
|
1722
|
+
const dayjs$1 = dayjs.default ?? dayjs;
|
|
1723
|
+
const advancedFormat = dayjs_plugin_advancedFormat_js.default ?? dayjs_plugin_advancedFormat_js;
|
|
1724
|
+
dayjs$1.extend(advancedFormat);
|
|
1725
|
+
//#endregion
|
|
1604
1726
|
//#region src/utils.ts
|
|
1605
|
-
dayjs.default.extend(dayjs_plugin_advancedFormat_js.default);
|
|
1606
1727
|
const getRelationName = (relationMethod) => {
|
|
1607
|
-
return
|
|
1728
|
+
return _h3ravel_support.Str.snake(relationMethod.substring(8));
|
|
1608
1729
|
};
|
|
1609
1730
|
const getRelationMethod = (relation) => {
|
|
1610
|
-
return
|
|
1731
|
+
return _h3ravel_support.Str.camel(`relation_${relation}`);
|
|
1611
1732
|
};
|
|
1612
1733
|
const getScopeMethod = (scope) => {
|
|
1613
|
-
return
|
|
1734
|
+
return _h3ravel_support.Str.camel(`scope_${scope}`);
|
|
1614
1735
|
};
|
|
1615
1736
|
const getAttrMethod = (attr) => {
|
|
1616
|
-
return
|
|
1737
|
+
return _h3ravel_support.Str.camel(`attribute_${attr}`);
|
|
1617
1738
|
};
|
|
1618
1739
|
const getGetterMethod = (attr) => {
|
|
1619
|
-
return
|
|
1740
|
+
return _h3ravel_support.Str.camel(`get_${attr}_attribute`);
|
|
1620
1741
|
};
|
|
1621
1742
|
const getSetterMethod = (attr) => {
|
|
1622
|
-
return
|
|
1743
|
+
return _h3ravel_support.Str.camel(`set_${attr}_attribute`);
|
|
1623
1744
|
};
|
|
1624
1745
|
/**
|
|
1625
1746
|
* Tap into a model a collection instance
|
|
@@ -1633,9 +1754,9 @@ const tap = (instance, callback) => {
|
|
|
1633
1754
|
return result instanceof Promise ? result.then(() => instance) : instance;
|
|
1634
1755
|
};
|
|
1635
1756
|
const { compose } = mixin_exports;
|
|
1636
|
-
const flatten
|
|
1757
|
+
const flatten = (arr) => arr.flat();
|
|
1637
1758
|
const flattenDeep = (arr) => Array.isArray(arr) ? arr.reduce((a, b) => a.concat(flattenDeep(b)), []) : [arr];
|
|
1638
|
-
const snakeCase = (str) =>
|
|
1759
|
+
const snakeCase = (str) => _h3ravel_support.Str.trim(_h3ravel_support.Str.snake(str.replace(/[^a-zA-Z0-9_-]/g, "-")), "_-").replace(/_+/g, "_");
|
|
1639
1760
|
//#endregion
|
|
1640
1761
|
//#region src/relations/relation.ts
|
|
1641
1762
|
var Relation = class {
|
|
@@ -1722,8 +1843,7 @@ var Relation = class {
|
|
|
1722
1843
|
return this.parent.getQualifiedKeyName();
|
|
1723
1844
|
}
|
|
1724
1845
|
getExistenceCompareKey() {
|
|
1725
|
-
|
|
1726
|
-
return (_this$getQualifiedFor = this.getQualifiedForeignKeyName) === null || _this$getQualifiedFor === void 0 ? void 0 : _this$getQualifiedFor.call(this);
|
|
1846
|
+
return this.getQualifiedForeignKeyName?.();
|
|
1727
1847
|
}
|
|
1728
1848
|
};
|
|
1729
1849
|
//#endregion
|
|
@@ -1864,8 +1984,7 @@ const HasAttributes = (Model) => {
|
|
|
1864
1984
|
return this;
|
|
1865
1985
|
}
|
|
1866
1986
|
normalizeCastClassResponse(key, value) {
|
|
1867
|
-
|
|
1868
|
-
return (value === null || value === void 0 || (_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor.name) === "Object" ? value : { [key]: value };
|
|
1987
|
+
return value?.constructor?.name === "Object" ? value : { [key]: value };
|
|
1869
1988
|
}
|
|
1870
1989
|
syncOriginal() {
|
|
1871
1990
|
this.original = this.getAttributes();
|
|
@@ -1975,9 +2094,9 @@ const HasAttributes = (Model) => {
|
|
|
1975
2094
|
return null;
|
|
1976
2095
|
}
|
|
1977
2096
|
case "collection": try {
|
|
1978
|
-
return (0,
|
|
2097
|
+
return (0, _h3ravel_collect_js.collect)(JSON.parse(value));
|
|
1979
2098
|
} catch {
|
|
1980
|
-
return (0,
|
|
2099
|
+
return (0, _h3ravel_collect_js.collect)([]);
|
|
1981
2100
|
}
|
|
1982
2101
|
case "date": return this.asDate(value);
|
|
1983
2102
|
case "datetime":
|
|
@@ -1990,8 +2109,8 @@ const HasAttributes = (Model) => {
|
|
|
1990
2109
|
attributesToData() {
|
|
1991
2110
|
let attributes = { ...this.attributes };
|
|
1992
2111
|
for (const key in attributes) {
|
|
1993
|
-
if (this.hidden.includes(key)) attributes =
|
|
1994
|
-
if (this.visible.length > 0 && this.visible.includes(key) === false) attributes =
|
|
2112
|
+
if (this.hidden.includes(key)) attributes = _h3ravel_support.Arr.except(attributes, [key]);
|
|
2113
|
+
if (this.visible.length > 0 && this.visible.includes(key) === false) attributes = _h3ravel_support.Arr.except(attributes, [key]);
|
|
1995
2114
|
}
|
|
1996
2115
|
for (const key of this.getDates()) {
|
|
1997
2116
|
if (attributes[key] === void 0) continue;
|
|
@@ -2003,7 +2122,7 @@ const HasAttributes = (Model) => {
|
|
|
2003
2122
|
if (key in attributes === false) continue;
|
|
2004
2123
|
attributes[key] = this.castAttribute(key, attributes[key]);
|
|
2005
2124
|
if (key in attributes && ["date", "datetime"].includes(String(value))) attributes[key] = this.serializeDate(attributes[key]);
|
|
2006
|
-
if (key in attributes && this.isCustomDateTimeCast(value)) attributes[key] =
|
|
2125
|
+
if (key in attributes && this.isCustomDateTimeCast(value)) attributes[key] = dayjs$1(attributes[key]).format(String(value).split(":")[1]);
|
|
2007
2126
|
}
|
|
2008
2127
|
for (const key of this.appends) attributes[key] = this.mutateAttribute(key, null);
|
|
2009
2128
|
return attributes;
|
|
@@ -2019,7 +2138,7 @@ const HasAttributes = (Model) => {
|
|
|
2019
2138
|
return this.getDates().includes(key) || this.isDateCastable(key);
|
|
2020
2139
|
}
|
|
2021
2140
|
serializeDate(date) {
|
|
2022
|
-
return date ?
|
|
2141
|
+
return date ? dayjs$1(date).toISOString() : null;
|
|
2023
2142
|
}
|
|
2024
2143
|
getDates() {
|
|
2025
2144
|
return this.usesTimestamps() ? [this.getCreatedAtColumn(), this.getUpdatedAtColumn()] : [];
|
|
@@ -2046,13 +2165,13 @@ const HasAttributes = (Model) => {
|
|
|
2046
2165
|
}
|
|
2047
2166
|
hasCast(key, types = []) {
|
|
2048
2167
|
if (key in this.casts) {
|
|
2049
|
-
types = (
|
|
2168
|
+
types = flatten(types);
|
|
2050
2169
|
return types.length > 0 ? types.includes(this.getCastType(key)) : true;
|
|
2051
2170
|
}
|
|
2052
2171
|
return false;
|
|
2053
2172
|
}
|
|
2054
2173
|
withDayjs(date) {
|
|
2055
|
-
return
|
|
2174
|
+
return dayjs$1(date);
|
|
2056
2175
|
}
|
|
2057
2176
|
isCustomCast(cast) {
|
|
2058
2177
|
return typeof cast === "function" && new cast() instanceof CastsAttributes;
|
|
@@ -2069,7 +2188,7 @@ const HasAttributes = (Model) => {
|
|
|
2069
2188
|
return this.hasCast(key, ["date", "datetime"]);
|
|
2070
2189
|
}
|
|
2071
2190
|
fromDateTime(value) {
|
|
2072
|
-
return
|
|
2191
|
+
return dayjs$1(this.asDateTime(value)).format(this.getDateFormat());
|
|
2073
2192
|
}
|
|
2074
2193
|
getDateFormat() {
|
|
2075
2194
|
return this.dateFormat || "YYYY-MM-DD HH:mm:ss";
|
|
@@ -2084,7 +2203,7 @@ const HasAttributes = (Model) => {
|
|
|
2084
2203
|
return new Date(value);
|
|
2085
2204
|
}
|
|
2086
2205
|
asDate(value) {
|
|
2087
|
-
return
|
|
2206
|
+
return dayjs$1(this.asDateTime(value)).startOf("day").toDate();
|
|
2088
2207
|
}
|
|
2089
2208
|
};
|
|
2090
2209
|
};
|
|
@@ -2105,10 +2224,14 @@ const HasGlobalScopes = (Model) => {
|
|
|
2105
2224
|
static globalScopes;
|
|
2106
2225
|
static addGlobalScope(scope, implementation = null) {
|
|
2107
2226
|
if (typeof scope === "string" && implementation instanceof Scope) {
|
|
2108
|
-
|
|
2227
|
+
const scopes = this.globalScopes ?? {};
|
|
2228
|
+
(0, _h3ravel_support.data_set)(scopes, this.name + "." + scope, implementation);
|
|
2229
|
+
this.globalScopes = scopes;
|
|
2109
2230
|
return implementation;
|
|
2110
2231
|
} else if (scope instanceof Scope) {
|
|
2111
|
-
|
|
2232
|
+
const scopes = this.globalScopes ?? {};
|
|
2233
|
+
(0, _h3ravel_support.data_set)(scopes, this.name + "." + scope.constructor.name, scope);
|
|
2234
|
+
this.globalScopes = scopes;
|
|
2112
2235
|
return scope;
|
|
2113
2236
|
}
|
|
2114
2237
|
throw new InvalidArgumentError("Global scope must be an instance of Scope.");
|
|
@@ -2117,8 +2240,8 @@ const HasGlobalScopes = (Model) => {
|
|
|
2117
2240
|
return this.getGlobalScope(scope) !== null;
|
|
2118
2241
|
}
|
|
2119
2242
|
static getGlobalScope(scope) {
|
|
2120
|
-
if (typeof scope === "string") return (0,
|
|
2121
|
-
return (0,
|
|
2243
|
+
if (typeof scope === "string") return (0, _h3ravel_support.data_get)(this.globalScopes ?? {}, this.name + "." + scope);
|
|
2244
|
+
return (0, _h3ravel_support.data_get)(this.globalScopes ?? {}, this.name + "." + scope.constructor.name);
|
|
2122
2245
|
}
|
|
2123
2246
|
static getAllGlobalScopes() {
|
|
2124
2247
|
return this.globalScopes;
|
|
@@ -2127,7 +2250,7 @@ const HasGlobalScopes = (Model) => {
|
|
|
2127
2250
|
this.globalScopes = scopes;
|
|
2128
2251
|
}
|
|
2129
2252
|
getGlobalScopes() {
|
|
2130
|
-
return (0,
|
|
2253
|
+
return (0, _h3ravel_support.data_get)(this.constructor.globalScopes ?? {}, this.constructor.name, {});
|
|
2131
2254
|
}
|
|
2132
2255
|
};
|
|
2133
2256
|
};
|
|
@@ -2227,7 +2350,7 @@ const HasOneOrMany = (Relation) => {
|
|
|
2227
2350
|
}
|
|
2228
2351
|
buildDictionary(results) {
|
|
2229
2352
|
const foreign = this.getForeignKeyName();
|
|
2230
|
-
return (0,
|
|
2353
|
+
return (0, _h3ravel_collect_js.collect)(results).mapToDictionary((result) => [result[foreign], result]).all();
|
|
2231
2354
|
}
|
|
2232
2355
|
async save(model) {
|
|
2233
2356
|
this.setForeignAttributesForCreate(model);
|
|
@@ -2298,13 +2421,11 @@ var HasMany = class extends compose(Relation, HasOneOrMany) {
|
|
|
2298
2421
|
return this.getParentKey() !== null ? await this.query.get() : new Collection([]);
|
|
2299
2422
|
}
|
|
2300
2423
|
getForeignKeyName() {
|
|
2301
|
-
|
|
2302
|
-
const segments = (_this$foreignKey = this.foreignKey) === null || _this$foreignKey === void 0 ? void 0 : _this$foreignKey.split(".");
|
|
2303
|
-
return segments === null || segments === void 0 ? void 0 : segments.pop();
|
|
2424
|
+
return (this.foreignKey?.split("."))?.pop();
|
|
2304
2425
|
}
|
|
2305
2426
|
buildDictionary(results) {
|
|
2306
2427
|
const foreign = this.getForeignKeyName();
|
|
2307
|
-
return (0,
|
|
2428
|
+
return (0, _h3ravel_collect_js.collect)(results).mapToDictionary((result) => [result[foreign], result]).all();
|
|
2308
2429
|
}
|
|
2309
2430
|
match(models, results, relation) {
|
|
2310
2431
|
return this.matchOneOrMany(models, results, relation, "many");
|
|
@@ -2335,9 +2456,7 @@ var HasOne = class extends compose(Relation, HasOneOrMany, SupportsDefaultModels
|
|
|
2335
2456
|
return this.matchOneOrMany(models, results, relation, "one");
|
|
2336
2457
|
}
|
|
2337
2458
|
getForeignKeyName() {
|
|
2338
|
-
|
|
2339
|
-
const segments = (_this$foreignKey = this.foreignKey) === null || _this$foreignKey === void 0 ? void 0 : _this$foreignKey.split(".");
|
|
2340
|
-
return segments === null || segments === void 0 ? void 0 : segments.pop();
|
|
2459
|
+
return (this.foreignKey?.split("."))?.pop();
|
|
2341
2460
|
}
|
|
2342
2461
|
async getResults() {
|
|
2343
2462
|
if (this.getParentKey() === null) return this.getDefaultFor(this.parent);
|
|
@@ -2446,10 +2565,10 @@ var HasManyThrough = class extends Relation {
|
|
|
2446
2565
|
}
|
|
2447
2566
|
const model = await this.first(columns);
|
|
2448
2567
|
if (model) return model;
|
|
2449
|
-
return callback
|
|
2568
|
+
return callback?.();
|
|
2450
2569
|
}
|
|
2451
2570
|
async find(id, columns = ["*"]) {
|
|
2452
|
-
if (
|
|
2571
|
+
if (Array.isArray(id)) return await this.findMany(id, columns);
|
|
2453
2572
|
return await this.where(this.getRelated().getQualifiedKeyName(), "=", id).first(columns);
|
|
2454
2573
|
}
|
|
2455
2574
|
async findMany(ids, columns = ["*"]) {
|
|
@@ -2477,7 +2596,7 @@ var HasManyThrough = class extends Relation {
|
|
|
2477
2596
|
return await this.query.paginate(perPage ?? 15, columns, pageName, page);
|
|
2478
2597
|
}
|
|
2479
2598
|
shouldSelect(columns = ["*"]) {
|
|
2480
|
-
if (
|
|
2599
|
+
if (columns?.at(0) == "*") columns = [this.related.getTable() + ".*"];
|
|
2481
2600
|
return [...columns, this.getQualifiedFirstKeyName() + " as laravel_through_key"];
|
|
2482
2601
|
}
|
|
2483
2602
|
async chunk(count, callback) {
|
|
@@ -2571,7 +2690,7 @@ const HasRelations = (Model) => {
|
|
|
2571
2690
|
return this;
|
|
2572
2691
|
}
|
|
2573
2692
|
unsetRelation(relation) {
|
|
2574
|
-
this.relations =
|
|
2693
|
+
this.relations = _h3ravel_support.Arr.except(this.relations, [relation]);
|
|
2575
2694
|
return this;
|
|
2576
2695
|
}
|
|
2577
2696
|
relationLoaded(relation) {
|
|
@@ -2594,8 +2713,7 @@ const HasRelations = (Model) => {
|
|
|
2594
2713
|
return data;
|
|
2595
2714
|
}
|
|
2596
2715
|
guessBelongsToRelation() {
|
|
2597
|
-
|
|
2598
|
-
const functionName = (((_e$stack = (/* @__PURE__ */ new Error()).stack) === null || _e$stack === void 0 ? void 0 : _e$stack.split("\n")[2]) ?? "").split(" ")[5];
|
|
2716
|
+
const functionName = ((/* @__PURE__ */ new Error()).stack?.split("\n")[2] ?? "").split(" ")[5];
|
|
2599
2717
|
return getRelationName(functionName);
|
|
2600
2718
|
}
|
|
2601
2719
|
joiningTable(related, instance = null) {
|
|
@@ -2705,7 +2823,7 @@ const HidesAttributes = (Model) => {
|
|
|
2705
2823
|
makeVisible(...keys) {
|
|
2706
2824
|
const visible = flattenDeep(keys);
|
|
2707
2825
|
if (this.visible.length > 0) this.visible = [...this.visible, ...visible];
|
|
2708
|
-
this.hidden = (0,
|
|
2826
|
+
this.hidden = (0, _h3ravel_collect_js.collect)(this.hidden).diff(visible).all();
|
|
2709
2827
|
return this;
|
|
2710
2828
|
}
|
|
2711
2829
|
makeHidden(key, ...keys) {
|
|
@@ -2849,10 +2967,9 @@ var QueryBuilder = class QueryBuilder extends Inference$1 {
|
|
|
2849
2967
|
asProxy() {
|
|
2850
2968
|
return new Proxy(this, {
|
|
2851
2969
|
get: function(target, prop) {
|
|
2852
|
-
var _target$connector$cli;
|
|
2853
2970
|
if (typeof target[prop] !== "undefined") return target[prop];
|
|
2854
2971
|
if (["destroy", "schema"].includes(prop)) return target.connector.schema;
|
|
2855
|
-
const skipReturning = !!
|
|
2972
|
+
const skipReturning = !!target.connector.client.config?.client?.includes("mysql") && prop === "returning";
|
|
2856
2973
|
if ([
|
|
2857
2974
|
"select",
|
|
2858
2975
|
"from",
|
|
@@ -3055,6 +3172,9 @@ var arquebus = class arquebus {
|
|
|
3055
3172
|
if (this.instance === null) this.instance = new arquebus();
|
|
3056
3173
|
return this.instance;
|
|
3057
3174
|
}
|
|
3175
|
+
static withSchema() {
|
|
3176
|
+
return this;
|
|
3177
|
+
}
|
|
3058
3178
|
/**
|
|
3059
3179
|
* Initialize a new database connection
|
|
3060
3180
|
*
|
|
@@ -3144,12 +3264,12 @@ var arquebus = class arquebus {
|
|
|
3144
3264
|
const tsPath = path.default.resolve("arquebus.config.ts");
|
|
3145
3265
|
const instance = this.getInstance();
|
|
3146
3266
|
if ((0, fs.existsSync)(jsPath)) {
|
|
3147
|
-
config = (await
|
|
3267
|
+
config = (await (0, _h3ravel_shared.importFile)(jsPath)).default;
|
|
3148
3268
|
if (addConnection) instance.addConnection(config, config.client);
|
|
3149
3269
|
return config;
|
|
3150
3270
|
}
|
|
3151
3271
|
if ((0, fs.existsSync)(tsPath)) if (process.env.NODE_ENV !== "production") {
|
|
3152
|
-
config = (await
|
|
3272
|
+
config = (await (0, _h3ravel_shared.importFile)(tsPath)).default;
|
|
3153
3273
|
if (addConnection) instance.addConnection(config, config.client);
|
|
3154
3274
|
return config;
|
|
3155
3275
|
} else throw new Error("arquebus.config.ts found in production without build step");
|
|
@@ -3165,7 +3285,7 @@ var arquebus = class arquebus {
|
|
|
3165
3285
|
"cjs"
|
|
3166
3286
|
], dir);
|
|
3167
3287
|
if (found) if (!found.endsWith(".ts") || process.env.NODE_ENV !== "production") {
|
|
3168
|
-
config = (await
|
|
3288
|
+
config = (await (0, _h3ravel_shared.importFile)(found)).default;
|
|
3169
3289
|
if (addConnection) instance.addConnection(config, config.client);
|
|
3170
3290
|
return config;
|
|
3171
3291
|
} else throw new Error("arquebus.config.ts found in production without build step");
|
|
@@ -3186,7 +3306,7 @@ var arquebus = class arquebus {
|
|
|
3186
3306
|
}
|
|
3187
3307
|
async destroyAll() {
|
|
3188
3308
|
await Promise.all(Object.values(this.manager).map((connection) => {
|
|
3189
|
-
return connection
|
|
3309
|
+
return connection?.destroy();
|
|
3190
3310
|
}));
|
|
3191
3311
|
}
|
|
3192
3312
|
createModel(name, options = {}) {
|
|
@@ -3195,29 +3315,25 @@ var arquebus = class arquebus {
|
|
|
3195
3315
|
this.models = {
|
|
3196
3316
|
...this.models,
|
|
3197
3317
|
[name]: class extends BaseModel {
|
|
3198
|
-
table =
|
|
3199
|
-
connection =
|
|
3200
|
-
timestamps =
|
|
3201
|
-
primaryKey =
|
|
3202
|
-
keyType =
|
|
3203
|
-
incrementing =
|
|
3204
|
-
with =
|
|
3205
|
-
casts =
|
|
3206
|
-
static CREATED_AT =
|
|
3207
|
-
static UPDATED_AT =
|
|
3208
|
-
static DELETED_AT =
|
|
3318
|
+
table = options?.table ?? null;
|
|
3319
|
+
connection = options?.connection ?? null;
|
|
3320
|
+
timestamps = options?.timestamps ?? true;
|
|
3321
|
+
primaryKey = options?.primaryKey ?? "id";
|
|
3322
|
+
keyType = options?.keyType ?? "int";
|
|
3323
|
+
incrementing = options?.incrementing ?? true;
|
|
3324
|
+
with = options?.with ?? [];
|
|
3325
|
+
casts = options?.casts ?? {};
|
|
3326
|
+
static CREATED_AT = options?.CREATED_AT ?? "created_at";
|
|
3327
|
+
static UPDATED_AT = options?.UPDATED_AT ?? "updated_at";
|
|
3328
|
+
static DELETED_AT = options?.DELETED_AT ?? "deleted_at";
|
|
3209
3329
|
}
|
|
3210
3330
|
};
|
|
3211
3331
|
if ("attributes" in options) for (const attribute in options.attributes) {
|
|
3212
3332
|
if (options.attributes[attribute] instanceof Attribute === false) throw new Error("Attribute must be an instance of \"Attribute\"");
|
|
3213
|
-
this.models[name].prototype[getAttrMethod(attribute)] = () =>
|
|
3214
|
-
var _options$attributes;
|
|
3215
|
-
return (_options$attributes = options.attributes) === null || _options$attributes === void 0 ? void 0 : _options$attributes[attribute];
|
|
3216
|
-
};
|
|
3333
|
+
this.models[name].prototype[getAttrMethod(attribute)] = () => options.attributes?.[attribute];
|
|
3217
3334
|
}
|
|
3218
3335
|
if ("relations" in options) for (const relation in options.relations) this.models[name].prototype[getRelationMethod(relation)] = function() {
|
|
3219
|
-
|
|
3220
|
-
return (_options$relations = options.relations) === null || _options$relations === void 0 ? void 0 : _options$relations[relation](this);
|
|
3336
|
+
return options.relations?.[relation](this);
|
|
3221
3337
|
};
|
|
3222
3338
|
if ("scopes" in options) for (const scope in options.scopes) this.models[name].prototype[getScopeMethod(scope)] = options.scopes[scope];
|
|
3223
3339
|
this.models[name].setConnectionResolver(this);
|
|
@@ -3255,6 +3371,9 @@ var Model = class Model extends BaseModel {
|
|
|
3255
3371
|
this.buildRelationships(attributes);
|
|
3256
3372
|
return this.asProxy();
|
|
3257
3373
|
}
|
|
3374
|
+
static define() {
|
|
3375
|
+
return this;
|
|
3376
|
+
}
|
|
3258
3377
|
static query(trx = null) {
|
|
3259
3378
|
return new this().newQuery(trx);
|
|
3260
3379
|
}
|
|
@@ -3438,7 +3557,7 @@ var Model = class Model extends BaseModel {
|
|
|
3438
3557
|
});
|
|
3439
3558
|
}
|
|
3440
3559
|
toData() {
|
|
3441
|
-
return
|
|
3560
|
+
return _h3ravel_support.Obj.deepMerge(this.attributesToData(), this.relationsToData());
|
|
3442
3561
|
}
|
|
3443
3562
|
toJSON() {
|
|
3444
3563
|
return this.toData();
|
|
@@ -3449,6 +3568,15 @@ var Model = class Model extends BaseModel {
|
|
|
3449
3568
|
toString() {
|
|
3450
3569
|
return this.toJson();
|
|
3451
3570
|
}
|
|
3571
|
+
getAttributes() {
|
|
3572
|
+
return super.getAttributes();
|
|
3573
|
+
}
|
|
3574
|
+
getAttribute(key) {
|
|
3575
|
+
return super.getAttribute(key);
|
|
3576
|
+
}
|
|
3577
|
+
setAttribute(key, value) {
|
|
3578
|
+
return super.setAttribute(key, value);
|
|
3579
|
+
}
|
|
3452
3580
|
fill(attributes) {
|
|
3453
3581
|
for (const key in attributes) this.setAttribute(key, attributes[key]);
|
|
3454
3582
|
return this;
|
|
@@ -3489,10 +3617,9 @@ var Model = class Model extends BaseModel {
|
|
|
3489
3617
|
if (this.usesTimestamps()) this.updateTimestamps();
|
|
3490
3618
|
const attributes = this.getAttributes();
|
|
3491
3619
|
if (this.getIncrementing()) {
|
|
3492
|
-
var _data$;
|
|
3493
3620
|
const keyName = this.getKeyName();
|
|
3494
3621
|
const data = await query.insert([attributes], [keyName]);
|
|
3495
|
-
this.setAttribute(keyName,
|
|
3622
|
+
this.setAttribute(keyName, data[0]?.[keyName] || data[0]);
|
|
3496
3623
|
} else if (Object.keys(attributes).length > 0) await query.insert(attributes);
|
|
3497
3624
|
this.exists = true;
|
|
3498
3625
|
await this.execHooks("created", options);
|
|
@@ -3534,7 +3661,7 @@ var Model = class Model extends BaseModel {
|
|
|
3534
3661
|
if (!this.exists) return Promise.resolve(void 0);
|
|
3535
3662
|
const model = await this.constructor.query().where(this.getKeyName(), this.getKey()).first();
|
|
3536
3663
|
this.attributes = { ...model.attributes };
|
|
3537
|
-
await this.load((0,
|
|
3664
|
+
await this.load((0, _h3ravel_collect_js.collect)(this.relations).reject((relation) => {
|
|
3538
3665
|
return relation instanceof Pivot;
|
|
3539
3666
|
}).keys().all());
|
|
3540
3667
|
this.syncOriginal();
|
|
@@ -3598,7 +3725,7 @@ var Pivot = class extends Model {
|
|
|
3598
3725
|
};
|
|
3599
3726
|
//#endregion
|
|
3600
3727
|
//#region src/collection.ts
|
|
3601
|
-
var Collection = class
|
|
3728
|
+
var Collection = class extends _h3ravel_collect_js.Collection {
|
|
3602
3729
|
newConstructor(...args) {
|
|
3603
3730
|
return new (this.getConstructor())(...args);
|
|
3604
3731
|
}
|
|
@@ -3607,17 +3734,18 @@ var Collection = class Collection extends collect_js.Collection {
|
|
|
3607
3734
|
}
|
|
3608
3735
|
async load(...relations) {
|
|
3609
3736
|
if (this.isNotEmpty()) {
|
|
3610
|
-
const items = await this.first().constructor.query().with(...relations).eagerLoadRelations(this.
|
|
3737
|
+
const items = await this.first().constructor.query().with(...relations).eagerLoadRelations(this.all());
|
|
3611
3738
|
return this.newConstructor(items);
|
|
3612
3739
|
}
|
|
3613
3740
|
return this;
|
|
3614
3741
|
}
|
|
3615
3742
|
async loadAggregate(relations, column, action = null) {
|
|
3616
3743
|
if (this.isEmpty()) return this;
|
|
3617
|
-
const
|
|
3618
|
-
const
|
|
3744
|
+
const first = this.first();
|
|
3745
|
+
const models = (await first.newModelQuery().whereIn(first.getKeyName(), this.modelKeys()).select(first.getKeyName()).withAggregate(relations, column, action).get()).keyBy(first.getKeyName());
|
|
3746
|
+
const attributes = (0, _h3ravel_collect_js.collect)(Object.keys(models.first().getAttributes())).diff([models.first().getKeyName()]).all();
|
|
3619
3747
|
this.each((model) => {
|
|
3620
|
-
const extraAttributes =
|
|
3748
|
+
const extraAttributes = _h3ravel_support.Arr.select(models.get(model.getKey()).getAttributes(), attributes);
|
|
3621
3749
|
model.fill(extraAttributes).syncOriginalAttributes(...attributes);
|
|
3622
3750
|
});
|
|
3623
3751
|
return this;
|
|
@@ -3655,20 +3783,21 @@ var Collection = class Collection extends collect_js.Collection {
|
|
|
3655
3783
|
diff(items) {
|
|
3656
3784
|
const diff = new this.constructor();
|
|
3657
3785
|
const dictionary = this.getDictionary(items);
|
|
3658
|
-
this.
|
|
3786
|
+
this.all().map((item) => {
|
|
3659
3787
|
if (dictionary[item.getKey()] === void 0) diff.add(item);
|
|
3660
3788
|
});
|
|
3661
3789
|
return diff;
|
|
3662
3790
|
}
|
|
3663
|
-
except(keys) {
|
|
3664
|
-
const
|
|
3791
|
+
except(...keys) {
|
|
3792
|
+
const values = keys.length === 1 && Array.isArray(keys[0]) ? keys[0].map(String) : keys.map(String);
|
|
3793
|
+
const dictionary = _h3ravel_support.Arr.except(this.getDictionary(), values);
|
|
3665
3794
|
return new this.constructor(Object.values(dictionary));
|
|
3666
3795
|
}
|
|
3667
3796
|
intersect(items) {
|
|
3668
3797
|
const intersect = new this.constructor();
|
|
3669
|
-
if (
|
|
3798
|
+
if (_h3ravel_support.Arr.isEmpty(items)) return intersect;
|
|
3670
3799
|
const dictionary = this.getDictionary(items);
|
|
3671
|
-
for (const item of this.
|
|
3800
|
+
for (const item of this.all()) if (dictionary[item.getKey()] !== void 0) intersect.add(item);
|
|
3672
3801
|
return intersect;
|
|
3673
3802
|
}
|
|
3674
3803
|
unique(key, _strict = false) {
|
|
@@ -3677,20 +3806,21 @@ var Collection = class Collection extends collect_js.Collection {
|
|
|
3677
3806
|
}
|
|
3678
3807
|
find(key, defaultValue = null) {
|
|
3679
3808
|
if (key instanceof Model) key = key.getKey();
|
|
3680
|
-
if (
|
|
3809
|
+
if (Array.isArray(key)) {
|
|
3681
3810
|
if (this.isEmpty()) return new this.constructor();
|
|
3682
3811
|
return this.whereIn(this.first().getKeyName(), key);
|
|
3683
3812
|
}
|
|
3684
|
-
(0,
|
|
3813
|
+
(0, _h3ravel_collect_js.collect)(this.all()).first((model) => {
|
|
3685
3814
|
return model.getKey() == key;
|
|
3686
3815
|
});
|
|
3687
|
-
return this.
|
|
3816
|
+
return this.all().filter((model) => {
|
|
3688
3817
|
return model.getKey() == key;
|
|
3689
3818
|
})[0] || defaultValue;
|
|
3690
3819
|
}
|
|
3691
3820
|
async fresh(...args) {
|
|
3692
3821
|
if (this.isEmpty()) return new this.constructor();
|
|
3693
3822
|
const model = this.first();
|
|
3823
|
+
if (!model) return new this.constructor();
|
|
3694
3824
|
const freshModels = (await model.newQuery().with(...args).whereIn(model.getKeyName(), this.modelKeys()).get()).getDictionary();
|
|
3695
3825
|
return this.filter((model) => {
|
|
3696
3826
|
return model.exists && freshModels[model.getKey()] !== void 0;
|
|
@@ -3713,15 +3843,15 @@ var Collection = class Collection extends collect_js.Collection {
|
|
|
3713
3843
|
item.append(attributes);
|
|
3714
3844
|
});
|
|
3715
3845
|
}
|
|
3716
|
-
only(keys) {
|
|
3717
|
-
|
|
3718
|
-
const dictionary =
|
|
3846
|
+
only(...keys) {
|
|
3847
|
+
const values = keys.length === 1 && Array.isArray(keys[0]) ? keys[0].map(String) : keys.map(String);
|
|
3848
|
+
const dictionary = _h3ravel_support.Arr.select(this.getDictionary(), values);
|
|
3719
3849
|
return new this.constructor(Object.values(dictionary));
|
|
3720
3850
|
}
|
|
3721
3851
|
getDictionary(items) {
|
|
3722
|
-
|
|
3852
|
+
const values = !items ? this.all() : items instanceof _h3ravel_collect_js.Collection ? items.all() : items;
|
|
3723
3853
|
const dictionary = {};
|
|
3724
|
-
|
|
3854
|
+
values.map((value) => {
|
|
3725
3855
|
dictionary[value.getKey()] = value;
|
|
3726
3856
|
});
|
|
3727
3857
|
return dictionary;
|
|
@@ -3745,8 +3875,8 @@ var Collection = class Collection extends collect_js.Collection {
|
|
|
3745
3875
|
return JSON.stringify(this.toData(), ...args);
|
|
3746
3876
|
}
|
|
3747
3877
|
[Symbol.iterator] = () => {
|
|
3748
|
-
const items = this.
|
|
3749
|
-
const length =
|
|
3878
|
+
const items = this.all();
|
|
3879
|
+
const length = items.length;
|
|
3750
3880
|
let n = 0;
|
|
3751
3881
|
return { next() {
|
|
3752
3882
|
return n < length ? {
|
|
@@ -3793,24 +3923,24 @@ const InteractsWithPivotTable = (Relation) => {
|
|
|
3793
3923
|
let records;
|
|
3794
3924
|
const results = await this.getCurrentlyAttachedPivots();
|
|
3795
3925
|
const current = results.length === 0 ? [] : results.map((result) => result.toData()).pluck(this.relatedPivotKey).all().map((i) => String(i));
|
|
3796
|
-
const detach = (0,
|
|
3926
|
+
const detach = (0, _h3ravel_collect_js.collect)(current).diff(Object.keys(records = this.formatRecordsList(this.parseIds(ids)))).all();
|
|
3797
3927
|
if (detaching && detach.length > 0) {
|
|
3798
3928
|
await this.detach(detach);
|
|
3799
3929
|
changes.detached = this.castKeys(detach);
|
|
3800
3930
|
}
|
|
3801
|
-
changes =
|
|
3931
|
+
changes = _h3ravel_support.Obj.deepMerge(changes, await this.attachNew(records, current, false));
|
|
3802
3932
|
return changes;
|
|
3803
3933
|
}
|
|
3804
3934
|
syncWithoutDetaching(ids) {
|
|
3805
3935
|
return this.sync(ids, false);
|
|
3806
3936
|
}
|
|
3807
3937
|
syncWithPivotValues(ids, values, detaching = true) {
|
|
3808
|
-
return this.sync((0,
|
|
3809
|
-
return [id, values];
|
|
3938
|
+
return this.sync((0, _h3ravel_collect_js.collect)(this.parseIds(ids)).mapWithKeys((id) => {
|
|
3939
|
+
return [String(id), values];
|
|
3810
3940
|
}), detaching);
|
|
3811
3941
|
}
|
|
3812
3942
|
withPivot(columns) {
|
|
3813
|
-
this.pivotColumns = this.pivotColumns.concat(
|
|
3943
|
+
this.pivotColumns = this.pivotColumns.concat(Array.isArray(columns) ? columns : Array.prototype.slice.call(columns));
|
|
3814
3944
|
return this;
|
|
3815
3945
|
}
|
|
3816
3946
|
async attachNew(records, current, touch = true) {
|
|
@@ -3846,9 +3976,9 @@ const InteractsWithPivotTable = (Relation) => {
|
|
|
3846
3976
|
return parseInt(updated);
|
|
3847
3977
|
}
|
|
3848
3978
|
formatRecordsList(records) {
|
|
3849
|
-
return (0,
|
|
3850
|
-
if (!
|
|
3851
|
-
return [id, attributes];
|
|
3979
|
+
return (0, _h3ravel_collect_js.collect)(records).mapWithKeys((attributes, id) => {
|
|
3980
|
+
if (!Array.isArray(attributes)) [id, attributes] = [attributes, {}];
|
|
3981
|
+
return [String(id), attributes];
|
|
3852
3982
|
}).all();
|
|
3853
3983
|
}
|
|
3854
3984
|
async getCurrentlyAttachedPivots() {
|
|
@@ -3918,7 +4048,7 @@ const InteractsWithPivotTable = (Relation) => {
|
|
|
3918
4048
|
}
|
|
3919
4049
|
formatAttachRecord(key, value, attributes, hasTimestamps) {
|
|
3920
4050
|
const [id, newAttributes] = this.extractAttachIdAndAttributes(key, value, attributes);
|
|
3921
|
-
return
|
|
4051
|
+
return _h3ravel_support.Obj.deepMerge(this.baseAttachRecord(id, hasTimestamps), newAttributes);
|
|
3922
4052
|
}
|
|
3923
4053
|
baseAttachRecord(id, timed) {
|
|
3924
4054
|
let record = {};
|
|
@@ -3931,7 +4061,7 @@ const InteractsWithPivotTable = (Relation) => {
|
|
|
3931
4061
|
return record;
|
|
3932
4062
|
}
|
|
3933
4063
|
extractAttachIdAndAttributes(key, value, newAttributes) {
|
|
3934
|
-
return
|
|
4064
|
+
return Array.isArray(value) ? [key, {
|
|
3935
4065
|
...value,
|
|
3936
4066
|
...newAttributes
|
|
3937
4067
|
}] : [value, newAttributes];
|
|
@@ -3942,7 +4072,7 @@ const InteractsWithPivotTable = (Relation) => {
|
|
|
3942
4072
|
parseIds(value) {
|
|
3943
4073
|
if (value instanceof Model) return [value[this.relatedKey]];
|
|
3944
4074
|
if (value instanceof Collection) return value.pluck(this.relatedKey).all();
|
|
3945
|
-
return
|
|
4075
|
+
return Array.isArray(value) ? value : [value];
|
|
3946
4076
|
}
|
|
3947
4077
|
};
|
|
3948
4078
|
};
|
|
@@ -4002,9 +4132,8 @@ var BelongsToMany = class extends compose(Relation, InteractsWithPivotTable) {
|
|
|
4002
4132
|
return this;
|
|
4003
4133
|
}
|
|
4004
4134
|
async get(columns) {
|
|
4005
|
-
var _builder$query;
|
|
4006
4135
|
const builder = this.query.applyScopes();
|
|
4007
|
-
columns =
|
|
4136
|
+
columns = builder.query?._statements?.find((item) => item.grouping == "columns") ? [] : columns;
|
|
4008
4137
|
let models = await builder.select(this.shouldSelect(columns)).getModels();
|
|
4009
4138
|
this.hydratePivotRelation(models);
|
|
4010
4139
|
if (models.length > 0) models = await builder.eagerLoadRelations(models);
|
|
@@ -4053,7 +4182,7 @@ var BelongsToMany = class extends compose(Relation, InteractsWithPivotTable) {
|
|
|
4053
4182
|
const value = model.attributes[key];
|
|
4054
4183
|
if (key.startsWith("pivot_")) {
|
|
4055
4184
|
values[key.substring(6)] = value;
|
|
4056
|
-
model.attributes =
|
|
4185
|
+
model.attributes = _h3ravel_support.Arr.except(model.attributes, [key]);
|
|
4057
4186
|
}
|
|
4058
4187
|
}
|
|
4059
4188
|
return values;
|
|
@@ -4064,11 +4193,11 @@ var BelongsToMany = class extends compose(Relation, InteractsWithPivotTable) {
|
|
|
4064
4193
|
return this.withPivot(this.createdAt(), this.updatedAt());
|
|
4065
4194
|
}
|
|
4066
4195
|
shouldSelect(columns = ["*"]) {
|
|
4067
|
-
if (
|
|
4196
|
+
if (columns.length === 1 && columns[0] === "*") columns = [this.related.getTable() + ".*"];
|
|
4068
4197
|
return columns.concat(this.aliasedPivotColumns());
|
|
4069
4198
|
}
|
|
4070
4199
|
aliasedPivotColumns() {
|
|
4071
|
-
return (0,
|
|
4200
|
+
return (0, _h3ravel_collect_js.collect)([this.foreignPivotKey, this.relatedPivotKey].concat(this.pivotColumns)).map((column) => {
|
|
4072
4201
|
return this.qualifyPivotColumn(column) + " as pivot_" + column;
|
|
4073
4202
|
}).unique().all();
|
|
4074
4203
|
}
|
|
@@ -4188,9 +4317,8 @@ var Builder = class Builder extends Inference {
|
|
|
4188
4317
|
}
|
|
4189
4318
|
asProxy() {
|
|
4190
4319
|
return new Proxy(this, { get(target, prop) {
|
|
4191
|
-
var _target$query$connect;
|
|
4192
4320
|
if (typeof target[prop] !== "undefined") return target[prop];
|
|
4193
|
-
const skipReturning = !!
|
|
4321
|
+
const skipReturning = !!target.query.connector?.client.config?.client?.includes("mysql") && prop === "returning";
|
|
4194
4322
|
if ([
|
|
4195
4323
|
"select",
|
|
4196
4324
|
"from",
|
|
@@ -4284,7 +4412,7 @@ var Builder = class Builder extends Inference {
|
|
|
4284
4412
|
};
|
|
4285
4413
|
}
|
|
4286
4414
|
if (prop.startsWith("where")) {
|
|
4287
|
-
const column =
|
|
4415
|
+
const column = _h3ravel_support.Str.snake(prop.substring(5));
|
|
4288
4416
|
return (...args) => {
|
|
4289
4417
|
target.query.where(column, ...args);
|
|
4290
4418
|
return target.asProxy();
|
|
@@ -4359,7 +4487,8 @@ var Builder = class Builder extends Inference {
|
|
|
4359
4487
|
}
|
|
4360
4488
|
addUpdatedAtColumn(values) {
|
|
4361
4489
|
if (!this.model.usesTimestamps() || this.model.getUpdatedAtColumn() === null) return values;
|
|
4362
|
-
|
|
4490
|
+
const column = this.model.getUpdatedAtColumn();
|
|
4491
|
+
values = _h3ravel_support.Obj.deepMerge({ [column]: this.model.freshTimestampString() }, values);
|
|
4363
4492
|
return values;
|
|
4364
4493
|
}
|
|
4365
4494
|
delete() {
|
|
@@ -4387,9 +4516,8 @@ var Builder = class Builder extends Inference {
|
|
|
4387
4516
|
return this.model;
|
|
4388
4517
|
}
|
|
4389
4518
|
setModel(model) {
|
|
4390
|
-
var _this$query;
|
|
4391
4519
|
this.model = model;
|
|
4392
|
-
if (typeof
|
|
4520
|
+
if (typeof this.query?.client?.table == "function") this.query = this.query.client.table(this.model.getTable());
|
|
4393
4521
|
else this.query = this.query.table(this.model.getTable());
|
|
4394
4522
|
return this;
|
|
4395
4523
|
}
|
|
@@ -4432,7 +4560,7 @@ var Builder = class Builder extends Inference {
|
|
|
4432
4560
|
}
|
|
4433
4561
|
withoutGlobalScope(scope) {
|
|
4434
4562
|
if (typeof scope !== "string") scope = scope.constructor.name;
|
|
4435
|
-
this.globalScopes =
|
|
4563
|
+
this.globalScopes = _h3ravel_support.Arr.except(this.globalScopes, [scope]);
|
|
4436
4564
|
return this;
|
|
4437
4565
|
}
|
|
4438
4566
|
macro(name, callback) {
|
|
@@ -4449,7 +4577,7 @@ var Builder = class Builder extends Inference {
|
|
|
4449
4577
|
let eagerLoads = {};
|
|
4450
4578
|
if (typeof args[1] === "function") {
|
|
4451
4579
|
const eagerLoad = this.parseWithRelations({ [args[0]]: args[1] });
|
|
4452
|
-
this.eagerLoad =
|
|
4580
|
+
this.eagerLoad = _h3ravel_support.Obj.deepMerge(this.eagerLoad, eagerLoad);
|
|
4453
4581
|
return this;
|
|
4454
4582
|
}
|
|
4455
4583
|
const relations = flattenDeep(args);
|
|
@@ -4458,13 +4586,13 @@ var Builder = class Builder extends Inference {
|
|
|
4458
4586
|
let eagerLoad;
|
|
4459
4587
|
if (typeof relation === "string") eagerLoad = { [relation]: (q) => q };
|
|
4460
4588
|
else if (typeof relation === "object") eagerLoad = relation;
|
|
4461
|
-
eagerLoads =
|
|
4589
|
+
eagerLoads = _h3ravel_support.Obj.deepMerge(eagerLoads, eagerLoad);
|
|
4462
4590
|
}
|
|
4463
|
-
this.eagerLoad =
|
|
4591
|
+
this.eagerLoad = _h3ravel_support.Obj.deepMerge(this.eagerLoad, this.parseWithRelations(eagerLoads));
|
|
4464
4592
|
return this;
|
|
4465
4593
|
}
|
|
4466
4594
|
has(relation, operator = ">=", count = 1, boolean = "and", callback = null) {
|
|
4467
|
-
if (
|
|
4595
|
+
if (typeof relation === "string") {
|
|
4468
4596
|
if (relation.includes(".")) return this.hasNested(relation, operator, count, boolean, callback);
|
|
4469
4597
|
relation = this.getRelationWithoutConstraints(getRelationMethod(relation));
|
|
4470
4598
|
}
|
|
@@ -4541,7 +4669,7 @@ var Builder = class Builder extends Inference {
|
|
|
4541
4669
|
let eagerLoad;
|
|
4542
4670
|
if (typeof relation === "string") eagerLoad = { [relation]: (q) => q };
|
|
4543
4671
|
else if (typeof relation === "object") eagerLoad = relation;
|
|
4544
|
-
eagerLoads =
|
|
4672
|
+
eagerLoads = _h3ravel_support.Obj.deepMerge(eagerLoads, eagerLoad);
|
|
4545
4673
|
}
|
|
4546
4674
|
relations = eagerLoads;
|
|
4547
4675
|
const db = this.model.getConnection();
|
|
@@ -4560,7 +4688,7 @@ var Builder = class Builder extends Inference {
|
|
|
4560
4688
|
} else expression = column;
|
|
4561
4689
|
const query = relation.getRelationExistenceQuery(relation.getRelated().newModelQuery(), this, db.raw(expression));
|
|
4562
4690
|
constraints(query);
|
|
4563
|
-
alias = alias ||
|
|
4691
|
+
alias = alias || _h3ravel_support.Str.snake(`${name} ${action} ${column}`.replace("/[^[:alnum:][:space:]_]/u", ""));
|
|
4564
4692
|
if (action === "exists") this.select(db.raw(`exists(${query.toSql().sql}) as ${alias}`));
|
|
4565
4693
|
else this.selectSub(action ? query : query.limit(1), alias);
|
|
4566
4694
|
}
|
|
@@ -4584,7 +4712,7 @@ var Builder = class Builder extends Inference {
|
|
|
4584
4712
|
}
|
|
4585
4713
|
parseSub(query) {
|
|
4586
4714
|
if (query instanceof Builder || query instanceof Relation) return [query.toSql().sql, query.toSql().bindings];
|
|
4587
|
-
else if (
|
|
4715
|
+
else if (typeof query === "string") return [query, []];
|
|
4588
4716
|
else throw new Error("A subquery must be a query builder instance, a Closure, or a string.");
|
|
4589
4717
|
}
|
|
4590
4718
|
prependDatabaseNameIfCrossDatabaseQuery(query) {
|
|
@@ -4641,15 +4769,15 @@ var Builder = class Builder extends Inference {
|
|
|
4641
4769
|
if (prefix !== "") prefix += ".";
|
|
4642
4770
|
for (const key in relations) {
|
|
4643
4771
|
const value = relations[key];
|
|
4644
|
-
if (
|
|
4772
|
+
if (typeof value === "string" || Number.isFinite(parseInt(value))) continue;
|
|
4645
4773
|
const [attribute, attributeSelectConstraint] = this.parseNameAndAttributeSelectionConstraint(key, value);
|
|
4646
4774
|
preparedRelationships = Object.assign({}, preparedRelationships, { [`${prefix}${attribute}`]: attributeSelectConstraint }, this.prepareNestedWithRelationships(value, `${prefix}${attribute}`));
|
|
4647
|
-
relations =
|
|
4775
|
+
relations = _h3ravel_support.Arr.except(relations, [key]);
|
|
4648
4776
|
}
|
|
4649
4777
|
for (const key in relations) {
|
|
4650
4778
|
const value = relations[key];
|
|
4651
4779
|
let attribute = key, attributeSelectConstraint = value;
|
|
4652
|
-
if (
|
|
4780
|
+
if (typeof value === "string") [attribute, attributeSelectConstraint] = this.parseNameAndAttributeSelectionConstraint(value);
|
|
4653
4781
|
preparedRelationships[`${prefix}${attribute}`] = this.combineConstraints([attributeSelectConstraint, preparedRelationships[`${prefix}${attribute}`] || (() => {})]);
|
|
4654
4782
|
}
|
|
4655
4783
|
return preparedRelationships;
|
|
@@ -4697,8 +4825,8 @@ var Builder = class Builder extends Inference {
|
|
|
4697
4825
|
}
|
|
4698
4826
|
async findOrFail(...args) {
|
|
4699
4827
|
const data = await this.find(...args);
|
|
4700
|
-
if (
|
|
4701
|
-
if (data.count() !== args[0].length) throw new ModelNotFoundError().setModel(this.model.constructor.name, (0,
|
|
4828
|
+
if (Array.isArray(args[0])) {
|
|
4829
|
+
if (data.count() !== args[0].length) throw new ModelNotFoundError().setModel(this.model.constructor.name, (0, _h3ravel_collect_js.collect)(args[0]).diff(data.modelKeys()).all());
|
|
4702
4830
|
return data;
|
|
4703
4831
|
}
|
|
4704
4832
|
if (data === null) throw new ModelNotFoundError().setModel(this.model.constructor.name, args[0]);
|
|
@@ -4712,12 +4840,12 @@ var Builder = class Builder extends Inference {
|
|
|
4712
4840
|
async firstOrNew(attributes = {}, values = {}) {
|
|
4713
4841
|
const instance = await this.where(attributes).first();
|
|
4714
4842
|
if (instance !== null) return instance;
|
|
4715
|
-
return this.newModelInstance(
|
|
4843
|
+
return this.newModelInstance(_h3ravel_support.Obj.deepMerge(attributes, values));
|
|
4716
4844
|
}
|
|
4717
4845
|
async firstOrCreate(attributes = {}, values = {}) {
|
|
4718
4846
|
const instance = await this.where(attributes).first();
|
|
4719
4847
|
if (instance !== null) return instance;
|
|
4720
|
-
return tap(this.newModelInstance(
|
|
4848
|
+
return tap(this.newModelInstance(_h3ravel_support.Obj.deepMerge(attributes, values)), async (instance) => {
|
|
4721
4849
|
await instance.save({ client: this.query });
|
|
4722
4850
|
});
|
|
4723
4851
|
}
|
|
@@ -4737,22 +4865,21 @@ var Builder = class Builder extends Inference {
|
|
|
4737
4865
|
return this;
|
|
4738
4866
|
}
|
|
4739
4867
|
async find(id, columns) {
|
|
4740
|
-
if (
|
|
4868
|
+
if (Array.isArray(id) || id instanceof Collection) return await this.findMany(id, columns);
|
|
4741
4869
|
return await this.where(this.model.getKeyName(), id).first(columns);
|
|
4742
4870
|
}
|
|
4743
4871
|
async findMany(ids, columns = ["*"]) {
|
|
4744
|
-
|
|
4745
|
-
|
|
4746
|
-
|
|
4747
|
-
return await this.whereIn(this.model.getKeyName(), ids).get(columns);
|
|
4872
|
+
const values = ids instanceof Collection ? ids.modelKeys() : Array.isArray(ids) ? ids : [ids];
|
|
4873
|
+
if (values.length === 0) return new Collection([]);
|
|
4874
|
+
return await this.whereIn(this.model.getKeyName(), values).get(columns);
|
|
4748
4875
|
}
|
|
4749
4876
|
async pluck(column) {
|
|
4750
4877
|
return new Collection(await this.query.pluck(column));
|
|
4751
4878
|
}
|
|
4752
4879
|
async destroy(ids) {
|
|
4753
4880
|
if (ids instanceof Collection) ids = ids.modelKeys();
|
|
4754
|
-
if (ids instanceof
|
|
4755
|
-
ids =
|
|
4881
|
+
if (ids instanceof _h3ravel_collect_js.Collection) ids = ids.all();
|
|
4882
|
+
ids = Array.isArray(ids) ? ids : Array.prototype.slice.call(ids);
|
|
4756
4883
|
if (ids.length === 0) return 0;
|
|
4757
4884
|
const key = this.model.newInstance().getKeyName();
|
|
4758
4885
|
let count = 0;
|
|
@@ -4770,12 +4897,11 @@ var Builder = class Builder extends Inference {
|
|
|
4770
4897
|
return await this.model.newModelQuery().get(columns);
|
|
4771
4898
|
}
|
|
4772
4899
|
async paginate(page = 1, perPage = 10) {
|
|
4773
|
-
var _this;
|
|
4774
4900
|
page = page || 1;
|
|
4775
|
-
perPage = perPage ||
|
|
4901
|
+
perPage = perPage || this?.model?.perPage || 15;
|
|
4776
4902
|
this.applyScopes();
|
|
4777
4903
|
const total = await this.query.clone().clearOrder().clearSelect().count(this.primaryKey);
|
|
4778
|
-
let results
|
|
4904
|
+
let results;
|
|
4779
4905
|
if (total > 0) {
|
|
4780
4906
|
const skip = (page - 1) * (perPage ?? 10);
|
|
4781
4907
|
this.take(perPage).skip(skip);
|
|
@@ -4785,7 +4911,7 @@ var Builder = class Builder extends Inference {
|
|
|
4785
4911
|
return new Paginator(results, parseInt(total), perPage, page);
|
|
4786
4912
|
}
|
|
4787
4913
|
async getModels(...columns) {
|
|
4788
|
-
columns = (
|
|
4914
|
+
columns = flatten(columns);
|
|
4789
4915
|
if (columns.length > 0) {
|
|
4790
4916
|
if (this.query._statements.filter((item) => item.grouping == "columns").length == 0 && columns[0] !== "*") this.query.select(...columns);
|
|
4791
4917
|
}
|
|
@@ -4875,7 +5001,7 @@ var SQLite = class {
|
|
|
4875
5001
|
column: column.name
|
|
4876
5002
|
}));
|
|
4877
5003
|
const tables = await this.tables();
|
|
4878
|
-
return flatten
|
|
5004
|
+
return flatten(await Promise.all(tables.map(async (table) => await this.columns(table))));
|
|
4879
5005
|
}
|
|
4880
5006
|
async columnInfo(table, column) {
|
|
4881
5007
|
const getColumnsForTable = async (table) => {
|
|
@@ -4901,17 +5027,17 @@ var SQLite = class {
|
|
|
4901
5027
|
is_generated: raw.hidden !== 0,
|
|
4902
5028
|
generation_expression: null,
|
|
4903
5029
|
is_nullable: raw.notnull === 0,
|
|
4904
|
-
is_unique: !!
|
|
5030
|
+
is_unique: !!index?.unique && indexInfo?.length === 1,
|
|
4905
5031
|
is_primary_key: raw.pk === 1,
|
|
4906
5032
|
has_auto_increment: raw.pk === 1 && tablesWithAutoIncrementPrimaryKeys.includes(table),
|
|
4907
|
-
foreign_key_column:
|
|
4908
|
-
foreign_key_table:
|
|
5033
|
+
foreign_key_column: foreignKey?.to || null,
|
|
5034
|
+
foreign_key_table: foreignKey?.table || null
|
|
4909
5035
|
};
|
|
4910
5036
|
});
|
|
4911
5037
|
};
|
|
4912
5038
|
if (!table) {
|
|
4913
5039
|
const tables = await this.tables();
|
|
4914
|
-
return flatten
|
|
5040
|
+
return flatten(await Promise.all(tables.map(async (table) => await getColumnsForTable(table))));
|
|
4915
5041
|
}
|
|
4916
5042
|
if (table && !column) return await getColumnsForTable(table);
|
|
4917
5043
|
return (await getColumnsForTable(table)).find((columnInfo) => columnInfo.name === column);
|
|
@@ -4942,7 +5068,7 @@ var SQLite = class {
|
|
|
4942
5068
|
constraint_name: null
|
|
4943
5069
|
}));
|
|
4944
5070
|
const tables = await this.tables();
|
|
4945
|
-
return flatten
|
|
5071
|
+
return flatten(await Promise.all(tables.map(async (table) => await this.foreignKeys(table))));
|
|
4946
5072
|
}
|
|
4947
5073
|
async uniqueConstraints(table) {
|
|
4948
5074
|
if (table) {
|
|
@@ -4958,7 +5084,7 @@ var SQLite = class {
|
|
|
4958
5084
|
});
|
|
4959
5085
|
}
|
|
4960
5086
|
const tables = await this.tables();
|
|
4961
|
-
return flatten
|
|
5087
|
+
return flatten(await Promise.all(tables.map(async (table) => await this.uniqueConstraints(table))));
|
|
4962
5088
|
}
|
|
4963
5089
|
};
|
|
4964
5090
|
//#endregion
|
|
@@ -5127,8 +5253,7 @@ var Migrator = class {
|
|
|
5127
5253
|
else await callback(connection);
|
|
5128
5254
|
}
|
|
5129
5255
|
async runMethod(connection, migration, method) {
|
|
5130
|
-
|
|
5131
|
-
await ((_migration$method = migration[method]) === null || _migration$method === void 0 ? void 0 : _migration$method.call(migration, connection.schema, connection));
|
|
5256
|
+
await migration[method]?.(connection.schema, connection);
|
|
5132
5257
|
}
|
|
5133
5258
|
async resolvePath(filePath) {
|
|
5134
5259
|
try {
|
|
@@ -5157,7 +5282,7 @@ var Migrator = class {
|
|
|
5157
5282
|
return path.default.basename(filePath).replace(".js", "");
|
|
5158
5283
|
}
|
|
5159
5284
|
path(p) {
|
|
5160
|
-
this.paths = Array.from(new Set([...this.paths, p]));
|
|
5285
|
+
this.paths = Array.from(/* @__PURE__ */ new Set([...this.paths, p]));
|
|
5161
5286
|
}
|
|
5162
5287
|
getPaths() {
|
|
5163
5288
|
return this.paths;
|
|
@@ -5190,6 +5315,40 @@ var Migrator = class {
|
|
|
5190
5315
|
}
|
|
5191
5316
|
};
|
|
5192
5317
|
//#endregion
|
|
5318
|
+
//#region src/cli/utils.ts
|
|
5319
|
+
const join = path.default.join;
|
|
5320
|
+
var Utils = class {
|
|
5321
|
+
static findModulePkg(moduleId, cwd) {
|
|
5322
|
+
const parts = moduleId.replace(/\\/g, "/").split("/");
|
|
5323
|
+
let packageName = "";
|
|
5324
|
+
if (parts.length > 0 && parts[0][0] === "@") packageName += parts.shift() + "/";
|
|
5325
|
+
packageName += parts.shift();
|
|
5326
|
+
const packageJson = path.default.join(packageName, "package.json");
|
|
5327
|
+
const resolved = resolve_from.default.silent(cwd ?? process.cwd(), packageJson);
|
|
5328
|
+
if (!resolved) return;
|
|
5329
|
+
return path.default.join(path.default.dirname(resolved), parts.join("/"));
|
|
5330
|
+
}
|
|
5331
|
+
static async getMigrationPaths(cwd, migrator, defaultPath, path$7) {
|
|
5332
|
+
if (path$7) return [join(cwd, path$7)];
|
|
5333
|
+
return [...migrator.getPaths(), join(cwd, defaultPath)];
|
|
5334
|
+
}
|
|
5335
|
+
};
|
|
5336
|
+
var TableGuesser = class TableGuesser {
|
|
5337
|
+
static CREATE_PATTERNS = [/^create_(\w+)_table$/, /^create_(\w+)$/];
|
|
5338
|
+
static CHANGE_PATTERNS = [/.+_(to|from|in)_(\w+)_table$/, /.+_(to|from|in)_(\w+)$/];
|
|
5339
|
+
static guess(migration) {
|
|
5340
|
+
for (const pattern of TableGuesser.CREATE_PATTERNS) {
|
|
5341
|
+
const matches = migration.match(pattern);
|
|
5342
|
+
if (matches) return [matches[1], true];
|
|
5343
|
+
}
|
|
5344
|
+
for (const pattern of TableGuesser.CHANGE_PATTERNS) {
|
|
5345
|
+
const matches = migration.match(pattern);
|
|
5346
|
+
if (matches) return [matches[2], false];
|
|
5347
|
+
}
|
|
5348
|
+
return [];
|
|
5349
|
+
}
|
|
5350
|
+
};
|
|
5351
|
+
//#endregion
|
|
5193
5352
|
//#region src/migrate.ts
|
|
5194
5353
|
var Migrate = class {
|
|
5195
5354
|
basePath;
|
|
@@ -5326,8 +5485,7 @@ var Migrate = class {
|
|
|
5326
5485
|
* @returns
|
|
5327
5486
|
*/
|
|
5328
5487
|
async setupConnection(config) {
|
|
5329
|
-
|
|
5330
|
-
const table = (config === null || config === void 0 || (_config$migrations = config.migrations) === null || _config$migrations === void 0 ? void 0 : _config$migrations.table) || "migrations";
|
|
5488
|
+
const table = config?.migrations?.table || "migrations";
|
|
5331
5489
|
if (config.skipConnection !== true) {
|
|
5332
5490
|
arquebus.addConnection(config, "default");
|
|
5333
5491
|
Object.entries(config.connections || {}).forEach(([name, connection]) => {
|
|
@@ -5387,7 +5545,6 @@ var MigrationCreator = class {
|
|
|
5387
5545
|
let stub;
|
|
5388
5546
|
if (!table) {
|
|
5389
5547
|
const customPath = path.default.join(this.customStubPath ?? "", `migration-${this.type}.stub`);
|
|
5390
|
-
console.log("\n", customPath, "---");
|
|
5391
5548
|
stub = await _h3ravel_shared.FileSystem.fileExists(customPath) ? customPath : this.stubPath(`/migration-${this.type}.stub`);
|
|
5392
5549
|
} else if (create) {
|
|
5393
5550
|
const customPath = path.default.join(this.customStubPath ?? "", `migration.create-${this.type}.stub`);
|
|
@@ -5406,7 +5563,7 @@ var MigrationCreator = class {
|
|
|
5406
5563
|
return name.replace(/_+([a-z])/g, (match, char) => char.toUpperCase());
|
|
5407
5564
|
}
|
|
5408
5565
|
getPath(name, dir) {
|
|
5409
|
-
const datePrefix =
|
|
5566
|
+
const datePrefix = dayjs$1().format("YYYY_MM_DD_HHmmss");
|
|
5410
5567
|
return path.default.join(dir, `${datePrefix}_${name}.${this.type}`);
|
|
5411
5568
|
}
|
|
5412
5569
|
async firePostCreateHooks(table, filePath) {
|
|
@@ -5420,7 +5577,9 @@ var MigrationCreator = class {
|
|
|
5420
5577
|
}
|
|
5421
5578
|
stubPath(stub = "") {
|
|
5422
5579
|
const __dirname = this.getDirname({});
|
|
5423
|
-
|
|
5580
|
+
const resolved = [path.default.join(__dirname, "stubs", stub), path.default.join(__dirname, "../stubs", stub)].find((candidate) => (0, node_fs.existsSync)(candidate));
|
|
5581
|
+
if (!resolved) throw new Error(`Migration stub not found: ${stub}`);
|
|
5582
|
+
return resolved;
|
|
5424
5583
|
}
|
|
5425
5584
|
getDirname(meta) {
|
|
5426
5585
|
if (typeof __dirname !== "undefined") return __dirname;
|
|
@@ -5430,20 +5589,27 @@ var MigrationCreator = class {
|
|
|
5430
5589
|
};
|
|
5431
5590
|
//#endregion
|
|
5432
5591
|
//#region package.json
|
|
5433
|
-
var version = "
|
|
5592
|
+
var version = "3.0.0";
|
|
5434
5593
|
//#endregion
|
|
5435
5594
|
//#region src/cli/index.ts
|
|
5436
5595
|
(class Cli {
|
|
5437
5596
|
cwd;
|
|
5438
|
-
output = _h3ravel_shared.Logger
|
|
5597
|
+
output = _h3ravel_shared.Logger;
|
|
5439
5598
|
config = {};
|
|
5440
5599
|
basePath = "";
|
|
5441
|
-
modulePath;
|
|
5600
|
+
modulePath = "";
|
|
5442
5601
|
configPath;
|
|
5443
|
-
modulePackage;
|
|
5602
|
+
modulePackage = { version: "N/A" };
|
|
5444
5603
|
constructor(basePath) {
|
|
5445
5604
|
this.basePath = basePath ?? (process.env.TEST === "true" ? "test/cli" : "");
|
|
5446
5605
|
}
|
|
5606
|
+
static async init() {
|
|
5607
|
+
(0, dotenv.config)({ quiet: true });
|
|
5608
|
+
const instance = new Cli();
|
|
5609
|
+
await instance.loadPaths();
|
|
5610
|
+
await instance.loadConfig();
|
|
5611
|
+
await instance.run();
|
|
5612
|
+
}
|
|
5447
5613
|
terminateNotFound() {
|
|
5448
5614
|
const cmd = _h3ravel_shared.Logger.log([["arquebus init", [
|
|
5449
5615
|
"italic",
|
|
@@ -5452,13 +5618,24 @@ var version = "2.0.0";
|
|
|
5452
5618
|
]]], "", false);
|
|
5453
5619
|
this.output.error(`ERROR: Arquebus config not found. Run ${cmd} first.`);
|
|
5454
5620
|
}
|
|
5455
|
-
|
|
5456
|
-
(
|
|
5457
|
-
|
|
5458
|
-
|
|
5621
|
+
ensureConfigured() {
|
|
5622
|
+
if (!this.configPath) this.terminateNotFound();
|
|
5623
|
+
}
|
|
5624
|
+
resolveBasePath(requestedPath) {
|
|
5625
|
+
return requestedPath ? node_path.default.join(this.cwd, requestedPath) : this.cwd;
|
|
5626
|
+
}
|
|
5627
|
+
async resolveStub(name) {
|
|
5628
|
+
const candidates = [node_path.default.join(this.modulePath, "src/stubs", name), node_path.default.join(this.modulePath, "dist/stubs", name)];
|
|
5629
|
+
for (const candidate of candidates) if (await _h3ravel_shared.FileSystem.fileExists(candidate)) return candidate;
|
|
5630
|
+
throw new Error(`Arquebus stub not found: ${name}`);
|
|
5631
|
+
}
|
|
5632
|
+
migrationReporter() {
|
|
5633
|
+
return (message, status) => {
|
|
5634
|
+
if (status && status !== "quiet") this.output[status](message);
|
|
5635
|
+
};
|
|
5459
5636
|
}
|
|
5460
5637
|
async loadPaths() {
|
|
5461
|
-
this.cwd =
|
|
5638
|
+
this.cwd = node_path.default.join(process.cwd(), this.basePath);
|
|
5462
5639
|
this.configPath = _h3ravel_shared.FileSystem.resolveFileUp("arquebus.config", [
|
|
5463
5640
|
"js",
|
|
5464
5641
|
"ts",
|
|
@@ -5466,7 +5643,7 @@ var version = "2.0.0";
|
|
|
5466
5643
|
], this.cwd) ?? void 0;
|
|
5467
5644
|
this.modulePath = Utils.findModulePkg("@h3ravel/arquebus", this.cwd) ?? "";
|
|
5468
5645
|
try {
|
|
5469
|
-
this.modulePackage = await
|
|
5646
|
+
this.modulePackage = JSON.parse(await (0, node_fs_promises.readFile)(node_path.default.join(this.modulePath, "package.json"), "utf8"));
|
|
5470
5647
|
} catch {
|
|
5471
5648
|
this.modulePackage = { version: "N/A" };
|
|
5472
5649
|
}
|
|
@@ -5474,233 +5651,185 @@ var version = "2.0.0";
|
|
|
5474
5651
|
}
|
|
5475
5652
|
async loadConfig() {
|
|
5476
5653
|
try {
|
|
5477
|
-
|
|
5478
|
-
this.config
|
|
5479
|
-
if ((_this$config$migratio = this.config.migrations) === null || _this$config$migratio === void 0 ? void 0 : _this$config$migratio.path) {
|
|
5480
|
-
var _this$config$migratio2;
|
|
5481
|
-
await (0, node_fs_promises.mkdir)(path.default.join(this.cwd, (_this$config$migratio2 = this.config.migrations) === null || _this$config$migratio2 === void 0 ? void 0 : _this$config$migratio2.path), { recursive: true });
|
|
5482
|
-
}
|
|
5654
|
+
this.config = (await (0, _h3ravel_shared.importFile)(this.configPath ?? "----")).default;
|
|
5655
|
+
if (this.config.migrations?.path) await (0, node_fs_promises.mkdir)(node_path.default.join(this.cwd, this.config.migrations.path), { recursive: true });
|
|
5483
5656
|
} catch {
|
|
5484
5657
|
this.config = {};
|
|
5485
5658
|
}
|
|
5486
5659
|
return this;
|
|
5487
5660
|
}
|
|
5488
5661
|
async run() {
|
|
5489
|
-
const
|
|
5490
|
-
|
|
5491
|
-
|
|
5492
|
-
|
|
5493
|
-
|
|
5494
|
-
|
|
5495
|
-
|
|
5496
|
-
|
|
5497
|
-
|
|
5498
|
-
|
|
5499
|
-
|
|
5500
|
-
|
|
5501
|
-
|
|
5502
|
-
|
|
5503
|
-
}
|
|
5504
|
-
|
|
5505
|
-
|
|
5506
|
-
|
|
5507
|
-
|
|
5508
|
-
|
|
5509
|
-
|
|
5510
|
-
|
|
5511
|
-
|
|
5512
|
-
|
|
5513
|
-
|
|
5514
|
-
|
|
5515
|
-
|
|
5516
|
-
|
|
5517
|
-
|
|
5518
|
-
|
|
5519
|
-
|
|
5520
|
-
|
|
5521
|
-
|
|
5522
|
-
|
|
5523
|
-
|
|
5524
|
-
|
|
5525
|
-
|
|
5526
|
-
|
|
5527
|
-
|
|
5528
|
-
/**
|
|
5529
|
-
* Publish migrations from third party vendors
|
|
5530
|
-
*/
|
|
5531
|
-
commander.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) => {
|
|
5532
|
-
if (!this.configPath) this.terminateNotFound();
|
|
5533
|
-
try {
|
|
5534
|
-
var _this$config$migratio4;
|
|
5535
|
-
const packagePath = Utils.findModulePkg(pkg) ?? "";
|
|
5536
|
-
const basePath = path.default.join(this.cwd, opts.path ?? ((_this$config$migratio4 = this.config.migrations) === null || _this$config$migratio4 === void 0 ? void 0 : _this$config$migratio4.path) ?? "./migrations");
|
|
5537
|
-
const pkgJson = await import(path.default.join(packagePath, "package.json"));
|
|
5538
|
-
if (!packagePath) this.output.error(`ERROR: package ${pkg} not found`);
|
|
5539
|
-
const creator = new MigrationCreator(path.default.join(packagePath, pkgJson.migrations ?? "migrations"));
|
|
5540
|
-
const pkgInf = _h3ravel_shared.Logger.log(path.default.basename(pkgJson.name + "@" + pkgJson.version), ["italic", "gray"], false);
|
|
5541
|
-
this.output.info(`INFO: Publishing migrations from ${pkgInf}`);
|
|
5542
|
-
await creator.publish(basePath, (fileName) => {
|
|
5543
|
-
this.output.split("INFO: Migration Published", fileName, "success");
|
|
5544
|
-
});
|
|
5545
|
-
} catch (e) {
|
|
5546
|
-
this.output.error("ERROR: " + e);
|
|
5547
|
-
}
|
|
5548
|
-
});
|
|
5549
|
-
/**
|
|
5550
|
-
* Run all pending migrations
|
|
5551
|
-
*/
|
|
5552
|
-
commander.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) => {
|
|
5553
|
-
if (!this.configPath) this.terminateNotFound();
|
|
5554
|
-
const basePath = opts.path ? path.default.join(this.cwd, opts.path) : this.cwd;
|
|
5555
|
-
try {
|
|
5556
|
-
const step = typeof opts.step === "string" ? parseInt(opts.step) : opts.step;
|
|
5557
|
-
await new Migrate(basePath).run(this.config, {
|
|
5558
|
-
...opts,
|
|
5559
|
-
step
|
|
5560
|
-
}, true);
|
|
5561
|
-
} catch (e) {
|
|
5562
|
-
this.output.error("ERROR: " + e);
|
|
5563
|
-
}
|
|
5564
|
-
});
|
|
5565
|
-
/**
|
|
5566
|
-
* Rollaback the last migration
|
|
5567
|
-
*/
|
|
5568
|
-
commander.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) => {
|
|
5569
|
-
if (!this.configPath) this.terminateNotFound();
|
|
5570
|
-
const basePath = opts.path ? path.default.join(this.cwd, opts.path) : this.cwd;
|
|
5571
|
-
try {
|
|
5572
|
-
await new Migrate(basePath, void 0, (msg, sts) => {
|
|
5573
|
-
if (sts) this.output[sts](msg);
|
|
5574
|
-
}).rollback(this.config, {
|
|
5575
|
-
...opts,
|
|
5576
|
-
step: typeof opts.step === "string" ? parseInt(opts.step) : opts.step
|
|
5577
|
-
}, true);
|
|
5578
|
-
} catch (e) {
|
|
5579
|
-
this.output.error("ERROR: " + e);
|
|
5580
|
-
}
|
|
5581
|
-
});
|
|
5582
|
-
/**
|
|
5583
|
-
* Rollback all database migrations
|
|
5584
|
-
*/
|
|
5585
|
-
commander.program.command("migrate:reset").description("Rollback all database migrations.").option("-p, --path [path]", "The path to the migrations directory.").action(async (opts) => {
|
|
5586
|
-
if (!this.configPath) this.terminateNotFound();
|
|
5587
|
-
const basePath = opts.path ? path.default.join(this.cwd, opts.path) : this.cwd;
|
|
5588
|
-
try {
|
|
5589
|
-
await new Migrate(basePath, void 0, (msg, sts) => {
|
|
5590
|
-
if (sts) this.output[sts](msg);
|
|
5591
|
-
}).reset(this.config, opts, true);
|
|
5592
|
-
} catch (e) {
|
|
5593
|
-
this.output.error("ERROR: " + e);
|
|
5594
|
-
}
|
|
5595
|
-
});
|
|
5596
|
-
/**
|
|
5597
|
-
* Reset and re-run all migrations
|
|
5598
|
-
*/
|
|
5599
|
-
commander.program.command("migrate:refresh").description("Reset and re-run all migrations.").option("-p, --path [path]", "The path to the migrations directory.").action(async (opts) => {
|
|
5600
|
-
if (!this.configPath) this.terminateNotFound();
|
|
5601
|
-
const basePath = opts.path ? path.default.join(this.cwd, opts.path) : this.cwd;
|
|
5602
|
-
try {
|
|
5603
|
-
await new Migrate(basePath, void 0, (msg, sts) => {
|
|
5604
|
-
if (sts) this.output[sts](msg);
|
|
5605
|
-
}).refresh(this.config, opts, true);
|
|
5606
|
-
} catch (e) {
|
|
5607
|
-
this.output.error("ERROR: " + e);
|
|
5608
|
-
}
|
|
5609
|
-
});
|
|
5610
|
-
/**
|
|
5611
|
-
* Drop all tables and re-run all migrations
|
|
5612
|
-
*/
|
|
5613
|
-
commander.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) => {
|
|
5614
|
-
if (!this.configPath) this.terminateNotFound();
|
|
5615
|
-
const basePath = opts.path ? path.default.join(this.cwd, opts.path) : this.cwd;
|
|
5616
|
-
try {
|
|
5617
|
-
await new Migrate(basePath, void 0, (msg, sts) => {
|
|
5618
|
-
if (sts) this.output[sts](msg);
|
|
5619
|
-
}).fresh(this.config, opts, true);
|
|
5620
|
-
} catch (e) {
|
|
5621
|
-
this.output.error("ERROR: " + e);
|
|
5622
|
-
}
|
|
5623
|
-
});
|
|
5624
|
-
/**
|
|
5625
|
-
* Check the migration status
|
|
5626
|
-
*/
|
|
5627
|
-
commander.program.command("migrate:status").description("Show the status of each migration.").option("-p, --path [path]", "The path to the migrations directory.").action(async (opts) => {
|
|
5628
|
-
if (!this.configPath) this.terminateNotFound();
|
|
5629
|
-
const basePath = opts.path ? path.default.join(this.cwd, opts.path) : this.cwd;
|
|
5630
|
-
try {
|
|
5631
|
-
const migrations = await new Migrate(basePath, void 0, (msg, sts) => {
|
|
5632
|
-
if (sts) this.output[sts](msg);
|
|
5633
|
-
}).status(this.config, opts, true);
|
|
5634
|
-
if (migrations.length > 0) {
|
|
5635
|
-
_h3ravel_shared.Logger.twoColumnDetail(_h3ravel_shared.Logger.log("Migration name", "gray", false), _h3ravel_shared.Logger.log("Batch / Status", "gray", false));
|
|
5636
|
-
migrations.forEach((migration) => {
|
|
5637
|
-
const status = migration.ran ? `[${migration.batch}] ${_h3ravel_shared.Logger.log("Ran", "green", false)}` : _h3ravel_shared.Logger.log("Pending", "yellow", false);
|
|
5638
|
-
_h3ravel_shared.Logger.twoColumnDetail(migration.name, status);
|
|
5639
|
-
});
|
|
5640
|
-
} else console.log("No migrations found");
|
|
5641
|
-
} catch (e) {
|
|
5642
|
-
this.output.error("ERROR: " + e);
|
|
5643
|
-
}
|
|
5644
|
-
});
|
|
5645
|
-
/**
|
|
5646
|
-
* Run database seeders
|
|
5647
|
-
*/
|
|
5648
|
-
commander.program.command("db:seed").description("Run database seeders.").option("-p, --path [path]", "The path to the seeders directory.").action(async (opts) => {
|
|
5649
|
-
if (!this.configPath) this.terminateNotFound();
|
|
5650
|
-
const basePath = opts.path ? path.default.join(this.cwd, opts.path) : this.cwd;
|
|
5651
|
-
try {
|
|
5652
|
-
var _this$config$seeders;
|
|
5653
|
-
const { arquebus } = await new Migrate(basePath).setupConnection({
|
|
5654
|
-
...this.config,
|
|
5655
|
-
skipConnection: false
|
|
5656
|
-
});
|
|
5657
|
-
const { SeederRunner } = await Promise.resolve().then(() => seeders_exports);
|
|
5658
|
-
const runner = new SeederRunner(arquebus);
|
|
5659
|
-
const seederPath = path.default.join(basePath, ((_this$config$seeders = this.config.seeders) === null || _this$config$seeders === void 0 ? void 0 : _this$config$seeders.path) ?? "./seeders");
|
|
5660
|
-
await runner.setConnection(this.config.client).run([seederPath]);
|
|
5661
|
-
this.output.success("Seeders executed successfully.");
|
|
5662
|
-
} catch (e) {
|
|
5663
|
-
this.output.error("ERROR: " + e);
|
|
5662
|
+
const kernel = new _h3ravel_musket.Kernel(this).setCwd(this.cwd).setConfig({
|
|
5663
|
+
baseCommands: ArquebusCommands,
|
|
5664
|
+
name: "arquebus",
|
|
5665
|
+
hideMusketInfo: true,
|
|
5666
|
+
versionSeparator: "\n"
|
|
5667
|
+
}).bootstrap();
|
|
5668
|
+
kernel.modules = [{
|
|
5669
|
+
name: "@h3ravel/arquebus",
|
|
5670
|
+
label: "Arquebus CLI version",
|
|
5671
|
+
version
|
|
5672
|
+
}, {
|
|
5673
|
+
name: "@h3ravel/arquebus",
|
|
5674
|
+
label: "Arquebus Local version",
|
|
5675
|
+
version: this.modulePackage.version || "N/A"
|
|
5676
|
+
}];
|
|
5677
|
+
return await kernel.run();
|
|
5678
|
+
}
|
|
5679
|
+
async initialize(type = "js") {
|
|
5680
|
+
if (!this.modulePath) this.output.error(["ERROR: No local arquebus install found", " Try running: pnpm add @h3ravel/arquebus"]);
|
|
5681
|
+
if (this.configPath) this.output.error(`ERROR: ${this.configPath} already exists`);
|
|
5682
|
+
try {
|
|
5683
|
+
const stubPath = `./arquebus.config.${type}`;
|
|
5684
|
+
const code = await (0, node_fs_promises.readFile)(await this.resolveStub(`arquebus.config-${type}.stub`), "utf8");
|
|
5685
|
+
await (0, node_fs_promises.writeFile)(node_path.default.join(this.cwd, stubPath), code);
|
|
5686
|
+
this.output.success(`Initialized: Arquebus has been initialized as ${stubPath}`);
|
|
5687
|
+
} catch (error) {
|
|
5688
|
+
this.output.error("ERROR: " + error);
|
|
5689
|
+
}
|
|
5690
|
+
}
|
|
5691
|
+
async makeMigration(rawName, options) {
|
|
5692
|
+
this.ensureConfigured();
|
|
5693
|
+
try {
|
|
5694
|
+
const name = _h3ravel_support.Str.snake(rawName);
|
|
5695
|
+
const migrationPath = node_path.default.join(this.cwd, options.path ?? this.config.migrations?.path ?? "./migrations");
|
|
5696
|
+
let table = options.table;
|
|
5697
|
+
let create = Boolean(options.create) && options.create !== "";
|
|
5698
|
+
if (!table && typeof options.create === "string") {
|
|
5699
|
+
table = options.create;
|
|
5700
|
+
create = true;
|
|
5664
5701
|
}
|
|
5665
|
-
|
|
5666
|
-
|
|
5667
|
-
|
|
5668
|
-
|
|
5669
|
-
commander.program.command("make:seeder <name>").description("Create a new Seeder file.").addOption(new commander.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) => {
|
|
5670
|
-
var _this$config$seeders2;
|
|
5671
|
-
if (!this.configPath) this.terminateNotFound();
|
|
5672
|
-
const seederPath = path.default.join(this.cwd, opts.path ?? ((_this$config$seeders2 = this.config.seeders) === null || _this$config$seeders2 === void 0 ? void 0 : _this$config$seeders2.path) ?? "./seeders", _h3ravel_support.Str.of(name).snake("-") + "." + opts.type);
|
|
5673
|
-
try {
|
|
5674
|
-
if (!opts.force && await _h3ravel_shared.FileSystem.fileExists(seederPath)) this.output.error("ERROR: Seeder already exists.");
|
|
5675
|
-
await (0, node_fs_promises.mkdir)(path.default.dirname(seederPath), { recursive: true });
|
|
5676
|
-
let stub = await (0, node_fs_promises.readFile)(path.default.join(this.modulePath, `src/stubs/seeder-${opts.type}.stub`), "utf-8");
|
|
5677
|
-
stub = stub.replace(/{{ name }}/g, name);
|
|
5678
|
-
await (0, node_fs_promises.writeFile)(seederPath, stub);
|
|
5679
|
-
this.output.split("INFO: Created Seeder", path.default.relative(this.cwd, seederPath));
|
|
5680
|
-
} catch (e) {
|
|
5681
|
-
this.output.error("ERROR: " + e);
|
|
5702
|
+
if (!table) {
|
|
5703
|
+
const guessed = TableGuesser.guess(name);
|
|
5704
|
+
table = guessed[0];
|
|
5705
|
+
create = Boolean(guessed[1]);
|
|
5682
5706
|
}
|
|
5683
|
-
|
|
5684
|
-
|
|
5685
|
-
|
|
5686
|
-
|
|
5687
|
-
|
|
5688
|
-
|
|
5689
|
-
|
|
5690
|
-
|
|
5691
|
-
|
|
5692
|
-
|
|
5693
|
-
|
|
5694
|
-
|
|
5695
|
-
|
|
5696
|
-
|
|
5697
|
-
|
|
5698
|
-
|
|
5699
|
-
|
|
5707
|
+
this.output.info("INFO: Creating Migration");
|
|
5708
|
+
const fileName = await new MigrationCreator(void 0, options.type ?? "js").create(name, migrationPath, table, create);
|
|
5709
|
+
this.output.success(`INFO: Migration Created \n ${_h3ravel_shared.Logger.log(node_path.default.basename(fileName), "gray", false)}`, true);
|
|
5710
|
+
} catch (error) {
|
|
5711
|
+
this.output.error("ERROR: " + error);
|
|
5712
|
+
}
|
|
5713
|
+
}
|
|
5714
|
+
async publishMigrations(pkg, options) {
|
|
5715
|
+
this.ensureConfigured();
|
|
5716
|
+
try {
|
|
5717
|
+
const packagePath = Utils.findModulePkg(pkg) ?? "";
|
|
5718
|
+
if (!packagePath) this.output.error(`ERROR: package ${pkg} not found`);
|
|
5719
|
+
const basePath = node_path.default.join(this.cwd, options.path ?? this.config.migrations?.path ?? "./migrations");
|
|
5720
|
+
const pkgJson = JSON.parse(await (0, node_fs_promises.readFile)(node_path.default.join(packagePath, "package.json"), "utf8"));
|
|
5721
|
+
const creator = new MigrationCreator(node_path.default.join(packagePath, pkgJson.migrations ?? "migrations"));
|
|
5722
|
+
const pkgInfo = _h3ravel_shared.Logger.log(node_path.default.basename(pkgJson.name + "@" + pkgJson.version), ["italic", "gray"], false);
|
|
5723
|
+
this.output.info(`INFO: Publishing migrations from ${pkgInfo}`);
|
|
5724
|
+
await creator.publish(basePath, (fileName) => {
|
|
5725
|
+
this.output.split("INFO: Migration Published", fileName, "success");
|
|
5726
|
+
});
|
|
5727
|
+
} catch (error) {
|
|
5728
|
+
this.output.error("ERROR: " + error);
|
|
5729
|
+
}
|
|
5730
|
+
}
|
|
5731
|
+
async migrate(options) {
|
|
5732
|
+
this.ensureConfigured();
|
|
5733
|
+
const basePath = this.resolveBasePath(options.path);
|
|
5734
|
+
try {
|
|
5735
|
+
const step = typeof options.step === "string" ? Number.parseInt(options.step) : options.step;
|
|
5736
|
+
await new Migrate(basePath).run(this.config, {
|
|
5737
|
+
...options,
|
|
5738
|
+
step
|
|
5739
|
+
}, true);
|
|
5740
|
+
} catch (error) {
|
|
5741
|
+
this.output.error("ERROR: " + error);
|
|
5742
|
+
}
|
|
5743
|
+
}
|
|
5744
|
+
async rollback(options) {
|
|
5745
|
+
this.ensureConfigured();
|
|
5746
|
+
const basePath = this.resolveBasePath(options.path);
|
|
5747
|
+
try {
|
|
5748
|
+
const step = typeof options.step === "string" ? Number.parseInt(options.step) : options.step;
|
|
5749
|
+
await new Migrate(basePath, void 0, this.migrationReporter()).rollback(this.config, {
|
|
5750
|
+
...options,
|
|
5751
|
+
step
|
|
5752
|
+
}, true);
|
|
5753
|
+
} catch (error) {
|
|
5754
|
+
this.output.error("ERROR: " + error);
|
|
5755
|
+
}
|
|
5756
|
+
}
|
|
5757
|
+
async reset(options) {
|
|
5758
|
+
await this.runMigrationOperation("reset", options);
|
|
5759
|
+
}
|
|
5760
|
+
async refresh(options) {
|
|
5761
|
+
await this.runMigrationOperation("refresh", options);
|
|
5762
|
+
}
|
|
5763
|
+
async fresh(options) {
|
|
5764
|
+
await this.runMigrationOperation("fresh", options);
|
|
5765
|
+
}
|
|
5766
|
+
async runMigrationOperation(operation, options) {
|
|
5767
|
+
this.ensureConfigured();
|
|
5768
|
+
const basePath = this.resolveBasePath(options.path);
|
|
5769
|
+
try {
|
|
5770
|
+
await new Migrate(basePath, void 0, this.migrationReporter())[operation](this.config, options, true);
|
|
5771
|
+
} catch (error) {
|
|
5772
|
+
this.output.error("ERROR: " + error);
|
|
5773
|
+
}
|
|
5774
|
+
}
|
|
5775
|
+
async status(options) {
|
|
5776
|
+
this.ensureConfigured();
|
|
5777
|
+
const basePath = this.resolveBasePath(options.path);
|
|
5778
|
+
try {
|
|
5779
|
+
const migrations = await new Migrate(basePath, void 0, this.migrationReporter()).status(this.config, options, true);
|
|
5780
|
+
if (migrations.length === 0) {
|
|
5781
|
+
this.output.info("No migrations found");
|
|
5782
|
+
return;
|
|
5700
5783
|
}
|
|
5701
|
-
|
|
5702
|
-
|
|
5703
|
-
|
|
5784
|
+
_h3ravel_shared.Logger.twoColumnDetail(_h3ravel_shared.Logger.log("Migration name", "gray", false), _h3ravel_shared.Logger.log("Batch / Status", "gray", false));
|
|
5785
|
+
migrations.forEach((migration) => {
|
|
5786
|
+
const status = migration.ran ? `[${migration.batch}] ${_h3ravel_shared.Logger.log("Ran", "green", false)}` : _h3ravel_shared.Logger.log("Pending", "yellow", false);
|
|
5787
|
+
_h3ravel_shared.Logger.twoColumnDetail(migration.name, status);
|
|
5788
|
+
});
|
|
5789
|
+
} catch (error) {
|
|
5790
|
+
this.output.error("ERROR: " + error);
|
|
5791
|
+
}
|
|
5792
|
+
}
|
|
5793
|
+
async seed(options) {
|
|
5794
|
+
this.ensureConfigured();
|
|
5795
|
+
const basePath = this.resolveBasePath(options.path);
|
|
5796
|
+
try {
|
|
5797
|
+
const { arquebus } = await new Migrate(basePath).setupConnection({
|
|
5798
|
+
...this.config,
|
|
5799
|
+
skipConnection: false
|
|
5800
|
+
});
|
|
5801
|
+
const seederPath = node_path.default.join(basePath, this.config.seeders?.path ?? "./seeders");
|
|
5802
|
+
await new SeederRunner(arquebus).setConnection(this.config.client).run([seederPath]);
|
|
5803
|
+
this.output.success("Seeders executed successfully.");
|
|
5804
|
+
} catch (error) {
|
|
5805
|
+
this.output.error("ERROR: " + error);
|
|
5806
|
+
}
|
|
5807
|
+
}
|
|
5808
|
+
async makeSeeder(name, options) {
|
|
5809
|
+
this.ensureConfigured();
|
|
5810
|
+
const type = options.type ?? "js";
|
|
5811
|
+
const seederPath = node_path.default.join(this.cwd, options.path ?? this.config.seeders?.path ?? "./seeders", `${_h3ravel_support.Str.of(name).snake("-")}.${type}`);
|
|
5812
|
+
try {
|
|
5813
|
+
if (!options.force && await _h3ravel_shared.FileSystem.fileExists(seederPath)) this.output.error("ERROR: Seeder already exists.");
|
|
5814
|
+
await (0, node_fs_promises.mkdir)(node_path.default.dirname(seederPath), { recursive: true });
|
|
5815
|
+
await (0, node_fs_promises.writeFile)(seederPath, (await (0, node_fs_promises.readFile)(await this.resolveStub(`seeder-${type}.stub`), "utf8")).replace(/{{ name }}/g, name));
|
|
5816
|
+
this.output.split("INFO: Created Seeder", node_path.default.relative(this.cwd, seederPath));
|
|
5817
|
+
} catch (error) {
|
|
5818
|
+
this.output.error("ERROR: " + error);
|
|
5819
|
+
}
|
|
5820
|
+
}
|
|
5821
|
+
async makeModel(name, options) {
|
|
5822
|
+
this.ensureConfigured();
|
|
5823
|
+
const type = options.type ?? "js";
|
|
5824
|
+
const modelPath = node_path.default.join(this.cwd, options.path ?? this.config.models?.path ?? "./models", `${name.toLowerCase()}.${type}`);
|
|
5825
|
+
try {
|
|
5826
|
+
if (!options.force && await _h3ravel_shared.FileSystem.fileExists(modelPath)) this.output.error("ERROR: Model already exists.");
|
|
5827
|
+
await (0, node_fs_promises.mkdir)(node_path.default.dirname(modelPath), { recursive: true });
|
|
5828
|
+
await (0, node_fs_promises.writeFile)(modelPath, (await (0, node_fs_promises.readFile)(await this.resolveStub(`model-${type}.stub`), "utf8")).replace(/{{ name }}/g, name));
|
|
5829
|
+
this.output.success(`Created Model: ${modelPath}`);
|
|
5830
|
+
} catch (error) {
|
|
5831
|
+
this.output.error("ERROR: " + error);
|
|
5832
|
+
}
|
|
5704
5833
|
}
|
|
5705
5834
|
}).init();
|
|
5706
5835
|
//#endregion
|