@orieljs/database 0.1.0-alpha.6 → 0.1.0-alpha.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +4 -0
- package/README.md +33 -0
- package/TRADEMARKS.md +33 -0
- package/dist/index.d.ts +381 -54
- package/dist/index.js +1125 -139
- package/dist/index.js.map +1 -1
- package/package.json +7 -6
package/dist/index.js
CHANGED
|
@@ -16,10 +16,10 @@ var DatabaseError = class extends Error {
|
|
|
16
16
|
status = 500;
|
|
17
17
|
};
|
|
18
18
|
var QueryError = class extends DatabaseError {
|
|
19
|
-
constructor(connectionName,
|
|
20
|
-
super(`${cause instanceof Error ? cause.message : String(cause)} (Connection: ${connectionName}, SQL: ${
|
|
19
|
+
constructor(connectionName, sql8, bindings, cause) {
|
|
20
|
+
super(`${cause instanceof Error ? cause.message : String(cause)} (Connection: ${connectionName}, SQL: ${sql8})`, { cause });
|
|
21
21
|
this.connectionName = connectionName;
|
|
22
|
-
this.sql =
|
|
22
|
+
this.sql = sql8;
|
|
23
23
|
this.bindings = bindings;
|
|
24
24
|
}
|
|
25
25
|
connectionName;
|
|
@@ -90,8 +90,8 @@ var BunSqliteDatabase = class {
|
|
|
90
90
|
close() {
|
|
91
91
|
this.database.close();
|
|
92
92
|
}
|
|
93
|
-
prepare(
|
|
94
|
-
const statement = this.database.prepare(
|
|
93
|
+
prepare(sql8) {
|
|
94
|
+
const statement = this.database.prepare(sql8);
|
|
95
95
|
return {
|
|
96
96
|
// A statement that returns columns (SELECT, or anything with RETURNING) is a reader.
|
|
97
97
|
reader: statement.columnNames.length > 0,
|
|
@@ -695,6 +695,7 @@ var clauses = (parts) => join(parts.filter((part) => part !== void 0), " ");
|
|
|
695
695
|
function likeToGlob(pattern) {
|
|
696
696
|
return pattern.replaceAll("*", "[*]").replaceAll("?", "[?]").replaceAll("%", "*").replaceAll("_", "?");
|
|
697
697
|
}
|
|
698
|
+
var SQLITE_DATE_FORMATS = { date: "%Y-%m-%d", time: "%H:%M:%S", day: "%d", month: "%m", year: "%Y" };
|
|
698
699
|
var Grammar = class {
|
|
699
700
|
constructor(driver) {
|
|
700
701
|
this.driver = driver;
|
|
@@ -736,7 +737,7 @@ var Grammar = class {
|
|
|
736
737
|
return join(columns.map((column) => this.wrap(column)));
|
|
737
738
|
}
|
|
738
739
|
compileSelect(query) {
|
|
739
|
-
const columns = query.columns.length ? join(query.columns.map((column) => typeof column === "object" && "query" in column ? sql2
|
|
740
|
+
const columns = query.columns.length ? join(query.columns.map((column) => typeof column === "object" && "query" in column ? sql2`${sql2.raw(column.exists ? "exists " : "")}(${this.compileSelect(column.query)}) as ${sql2.id(column.as)}` : this.wrap(column))) : sql2.raw("*");
|
|
740
741
|
return clauses([query.distinctRows ? sql2`select distinct ${columns}` : sql2`select ${columns}`, this.compileComponents(query)]);
|
|
741
742
|
}
|
|
742
743
|
/** Everything after the select list: from, joins, where, group by, having, order by, limit/offset, lock. */
|
|
@@ -787,8 +788,25 @@ var Grammar = class {
|
|
|
787
788
|
return sql2`${sql2.raw(where.not ? "not exists" : "exists")} (${this.compileSelect(where.query)})`;
|
|
788
789
|
case "raw":
|
|
789
790
|
return rawWithBindings(where.sql, where.bindings.map((value) => this.prepare(value)));
|
|
791
|
+
case "date":
|
|
792
|
+
return this.compileWhereDate(where);
|
|
790
793
|
}
|
|
791
794
|
}
|
|
795
|
+
/**
|
|
796
|
+
* whereDate(), whereTime(), whereDay(), whereMonth() and whereYear() per driver, as Laravel 12's grammars: MySQL's
|
|
797
|
+
* date()/time()/day()/month()/year(), Postgres' ::date, ::time and extract(), SQLite's strftime() compared as text.
|
|
798
|
+
*/
|
|
799
|
+
compileWhereDate(where) {
|
|
800
|
+
const column = this.wrap(where.column);
|
|
801
|
+
const operator = sql2.raw(this.operator(where.operator));
|
|
802
|
+
const value = this.parameter(where.value);
|
|
803
|
+
if (this.driver === "sqlite") return sql2`strftime(${sql2.lit(SQLITE_DATE_FORMATS[where.part])}, ${column}) ${operator} cast(${value} as text)`;
|
|
804
|
+
if (this.driver === "pgsql") {
|
|
805
|
+
if (where.part === "date" || where.part === "time") return sql2`${column}::${sql2.raw(where.part)} ${operator} ${value}`;
|
|
806
|
+
return sql2`extract(${sql2.raw(where.part)} from ${column}) ${operator} ${value}`;
|
|
807
|
+
}
|
|
808
|
+
return sql2`${sql2.raw(where.part)}(${column}) ${operator} ${value}`;
|
|
809
|
+
}
|
|
792
810
|
/**
|
|
793
811
|
* whereLike() per driver, as Laravel 12's grammars: Postgres compares the column as text with ilike (like when
|
|
794
812
|
* case-sensitive); MySQL uses like (like binary); SQLite uses like, or glob with the pattern translated.
|
|
@@ -946,6 +964,19 @@ function keyOf(item, alias) {
|
|
|
946
964
|
}
|
|
947
965
|
return value;
|
|
948
966
|
}
|
|
967
|
+
var pad2 = (value, width = 2) => String(value).padStart(width, "0");
|
|
968
|
+
function dateWhereValue(part, value) {
|
|
969
|
+
if (value instanceof Expression) return value;
|
|
970
|
+
if (value instanceof Date) {
|
|
971
|
+
if (part === "date") return `${pad2(value.getUTCFullYear(), 4)}-${pad2(value.getUTCMonth() + 1)}-${pad2(value.getUTCDate())}`;
|
|
972
|
+
if (part === "time") return `${pad2(value.getUTCHours())}:${pad2(value.getUTCMinutes())}:${pad2(value.getUTCSeconds())}`;
|
|
973
|
+
if (part === "day") return pad2(value.getUTCDate());
|
|
974
|
+
if (part === "month") return pad2(value.getUTCMonth() + 1);
|
|
975
|
+
return String(value.getUTCFullYear());
|
|
976
|
+
}
|
|
977
|
+
if (part === "day" || part === "month") return pad2(Math.trunc(Number(value)) || 0);
|
|
978
|
+
return typeof value === "number" ? String(value) : value;
|
|
979
|
+
}
|
|
949
980
|
var isRow = (value) => typeof value === "object" && value !== null && !(value instanceof Expression) && !(value instanceof Builder) && !Array.isArray(value);
|
|
950
981
|
function columnKey(column) {
|
|
951
982
|
const alias = /\s+as\s+/i.exec(column);
|
|
@@ -1055,6 +1086,41 @@ var Builder = class _Builder {
|
|
|
1055
1086
|
this.wheres.push({ type: "between", column, values, not: true, boolean: "and" });
|
|
1056
1087
|
return this;
|
|
1057
1088
|
}
|
|
1089
|
+
/** Compares the date part of a column: whereDate('published_at', '2026-01-05'), whereDate('published_at', '<', new Date()). */
|
|
1090
|
+
whereDate(column, ...args) {
|
|
1091
|
+
return this.addDateBasedWhere("date", column, args, "and");
|
|
1092
|
+
}
|
|
1093
|
+
orWhereDate(column, ...args) {
|
|
1094
|
+
return this.addDateBasedWhere("date", column, args, "or");
|
|
1095
|
+
}
|
|
1096
|
+
/** Compares the time of day: whereTime('published_at', '>=', '09:00:00'). */
|
|
1097
|
+
whereTime(column, ...args) {
|
|
1098
|
+
return this.addDateBasedWhere("time", column, args, "and");
|
|
1099
|
+
}
|
|
1100
|
+
orWhereTime(column, ...args) {
|
|
1101
|
+
return this.addDateBasedWhere("time", column, args, "or");
|
|
1102
|
+
}
|
|
1103
|
+
/** Compares the day of the month: whereDay('published_at', 5). */
|
|
1104
|
+
whereDay(column, ...args) {
|
|
1105
|
+
return this.addDateBasedWhere("day", column, args, "and");
|
|
1106
|
+
}
|
|
1107
|
+
orWhereDay(column, ...args) {
|
|
1108
|
+
return this.addDateBasedWhere("day", column, args, "or");
|
|
1109
|
+
}
|
|
1110
|
+
/** Compares the month: whereMonth('published_at', 12). */
|
|
1111
|
+
whereMonth(column, ...args) {
|
|
1112
|
+
return this.addDateBasedWhere("month", column, args, "and");
|
|
1113
|
+
}
|
|
1114
|
+
orWhereMonth(column, ...args) {
|
|
1115
|
+
return this.addDateBasedWhere("month", column, args, "or");
|
|
1116
|
+
}
|
|
1117
|
+
/** Compares the year: whereYear('published_at', '>=', 2026). */
|
|
1118
|
+
whereYear(column, ...args) {
|
|
1119
|
+
return this.addDateBasedWhere("year", column, args, "and");
|
|
1120
|
+
}
|
|
1121
|
+
orWhereYear(column, ...args) {
|
|
1122
|
+
return this.addDateBasedWhere("year", column, args, "or");
|
|
1123
|
+
}
|
|
1058
1124
|
/**
|
|
1059
1125
|
* Laravel's whereLike(): the value is the pattern, `%` and `_` included (`whereLike('title', `%${term}%`)`).
|
|
1060
1126
|
* Case-insensitive unless caseSensitive: ilike on Postgres, like on MySQL and SQLite (their like already ignores
|
|
@@ -1084,12 +1150,12 @@ var Builder = class _Builder {
|
|
|
1084
1150
|
orWhereColumn(first, operatorOrSecond, second) {
|
|
1085
1151
|
return this.whereColumn(first, operatorOrSecond, second, "or");
|
|
1086
1152
|
}
|
|
1087
|
-
whereRaw(
|
|
1088
|
-
this.wheres.push({ type: "raw", sql:
|
|
1153
|
+
whereRaw(sql8, bindings = [], boolean = "and") {
|
|
1154
|
+
this.wheres.push({ type: "raw", sql: sql8, bindings, boolean });
|
|
1089
1155
|
return this;
|
|
1090
1156
|
}
|
|
1091
|
-
orWhereRaw(
|
|
1092
|
-
return this.whereRaw(
|
|
1157
|
+
orWhereRaw(sql8, bindings = []) {
|
|
1158
|
+
return this.whereRaw(sql8, bindings, "or");
|
|
1093
1159
|
}
|
|
1094
1160
|
whereExists(query, boolean = "and", not = false) {
|
|
1095
1161
|
const sub = query instanceof _Builder ? query : this.subQuery(query);
|
|
@@ -1140,8 +1206,8 @@ var Builder = class _Builder {
|
|
|
1140
1206
|
this.havings.push({ column, operator, value: operand, boolean });
|
|
1141
1207
|
return this;
|
|
1142
1208
|
}
|
|
1143
|
-
havingRaw(
|
|
1144
|
-
this.havings.push({ raw: new Expression(
|
|
1209
|
+
havingRaw(sql8, bindings = [], boolean = "and") {
|
|
1210
|
+
this.havings.push({ raw: new Expression(sql8, bindings), boolean });
|
|
1145
1211
|
return this;
|
|
1146
1212
|
}
|
|
1147
1213
|
orderBy(column, direction = "asc") {
|
|
@@ -1163,8 +1229,8 @@ var Builder = class _Builder {
|
|
|
1163
1229
|
this.orders.push({ raw: this.grammar.compileRandom() });
|
|
1164
1230
|
return this;
|
|
1165
1231
|
}
|
|
1166
|
-
orderByRaw(
|
|
1167
|
-
this.orders.push({ raw: new Expression(
|
|
1232
|
+
orderByRaw(sql8, bindings = []) {
|
|
1233
|
+
this.orders.push({ raw: new Expression(sql8, bindings) });
|
|
1168
1234
|
return this;
|
|
1169
1235
|
}
|
|
1170
1236
|
/** Removes existing orders, optionally adding a new one. */
|
|
@@ -1215,7 +1281,11 @@ var Builder = class _Builder {
|
|
|
1215
1281
|
}
|
|
1216
1282
|
// ---------------------------------------------------------------- reading
|
|
1217
1283
|
async get() {
|
|
1218
|
-
return
|
|
1284
|
+
return this.newCollection(await this.runSelect());
|
|
1285
|
+
}
|
|
1286
|
+
/** The collection get() and chunk() hand out (Eloquent's builder makes the model's collection). */
|
|
1287
|
+
newCollection(items) {
|
|
1288
|
+
return new Collection3(items);
|
|
1219
1289
|
}
|
|
1220
1290
|
/** The raw rows, without a Collection around them. */
|
|
1221
1291
|
async runSelect() {
|
|
@@ -1370,7 +1440,7 @@ var Builder = class _Builder {
|
|
|
1370
1440
|
for (let page = 1; ; page++) {
|
|
1371
1441
|
const results = await this.clone().forPage(page, count).runSelect();
|
|
1372
1442
|
if (!results.length) return true;
|
|
1373
|
-
if (await callback(
|
|
1443
|
+
if (await callback(this.newCollection(results), page) === false) return false;
|
|
1374
1444
|
if (results.length < count) return true;
|
|
1375
1445
|
}
|
|
1376
1446
|
}
|
|
@@ -1382,7 +1452,7 @@ var Builder = class _Builder {
|
|
|
1382
1452
|
for (let page = 1; ; page++) {
|
|
1383
1453
|
const results = await this.clone().forPageAfterId(count, lastId, key).runSelect();
|
|
1384
1454
|
if (!results.length) return true;
|
|
1385
|
-
if (await callback(
|
|
1455
|
+
if (await callback(this.newCollection(results), page) === false) return false;
|
|
1386
1456
|
if (results.length < count) return true;
|
|
1387
1457
|
lastId = keyOf(results.at(-1), aliasName);
|
|
1388
1458
|
}
|
|
@@ -1513,6 +1583,13 @@ var Builder = class _Builder {
|
|
|
1513
1583
|
this.wheres.push({ type: "basic", column: ref, operator, value, boolean });
|
|
1514
1584
|
return this;
|
|
1515
1585
|
}
|
|
1586
|
+
/** Laravel's addDateBasedWhere(): one value means '='; the operator is checked against the whitelist. */
|
|
1587
|
+
addDateBasedWhere(part, column, args, boolean) {
|
|
1588
|
+
const [operator, value] = args.length === 1 ? ["=", args[0]] : [args[0].toLowerCase(), args[1]];
|
|
1589
|
+
this.grammar.operator(operator);
|
|
1590
|
+
this.wheres.push({ type: "date", part, column, operator, value: dateWhereValue(part, value), boolean });
|
|
1591
|
+
return this;
|
|
1592
|
+
}
|
|
1516
1593
|
pushNull(column, not, boolean) {
|
|
1517
1594
|
this.wheres.push({ type: "null", column, not, boolean });
|
|
1518
1595
|
return this;
|
|
@@ -1536,10 +1613,10 @@ var JoinClause = class extends Builder {
|
|
|
1536
1613
|
|
|
1537
1614
|
// Connection.ts
|
|
1538
1615
|
import { AsyncLocalStorage } from "async_hooks";
|
|
1539
|
-
import { Kysely, sql as
|
|
1616
|
+
import { Kysely, sql as sql7 } from "kysely";
|
|
1540
1617
|
|
|
1541
1618
|
// Schema/Builder.ts
|
|
1542
|
-
import { sql as
|
|
1619
|
+
import { sql as sql6 } from "kysely";
|
|
1543
1620
|
|
|
1544
1621
|
// Schema/ColumnDefinition.ts
|
|
1545
1622
|
var ColumnDefinition = class {
|
|
@@ -1602,6 +1679,15 @@ var ColumnDefinition = class {
|
|
|
1602
1679
|
this.attributes.default = new Expression("CURRENT_TIMESTAMP");
|
|
1603
1680
|
return this;
|
|
1604
1681
|
}
|
|
1682
|
+
/**
|
|
1683
|
+
* Redefines an existing column (Laravel's change()): t.string('title', 500).nullable().change(). As in Laravel 11+,
|
|
1684
|
+
* the column becomes exactly this definition: a modifier it had and that isn't given again (nullable, default,
|
|
1685
|
+
* comment, …) is dropped. On SQLite the table is rebuilt.
|
|
1686
|
+
*/
|
|
1687
|
+
change() {
|
|
1688
|
+
this.attributes.change = true;
|
|
1689
|
+
return this;
|
|
1690
|
+
}
|
|
1605
1691
|
/** MySQL only: on update CURRENT_TIMESTAMP. */
|
|
1606
1692
|
useCurrentOnUpdate() {
|
|
1607
1693
|
this.attributes.onUpdate = new Expression("CURRENT_TIMESTAMP");
|
|
@@ -1845,8 +1931,8 @@ var Blueprint = class {
|
|
|
1845
1931
|
}
|
|
1846
1932
|
/** t.foreign('user_id').references('id').on('users') */
|
|
1847
1933
|
foreign(columns, name) {
|
|
1848
|
-
const
|
|
1849
|
-
const foreign = new ForeignKeyDefinition(
|
|
1934
|
+
const list3 = [columns].flat();
|
|
1935
|
+
const foreign = new ForeignKeyDefinition(list3, name ?? this.createIndexName("foreign", list3));
|
|
1850
1936
|
this.commands.push({ name: "foreign", foreign });
|
|
1851
1937
|
return foreign;
|
|
1852
1938
|
}
|
|
@@ -1867,8 +1953,10 @@ var Blueprint = class {
|
|
|
1867
1953
|
dropIndex(index) {
|
|
1868
1954
|
this.commands.push({ name: "dropIndex", index: this.indexNameFor("index", index) });
|
|
1869
1955
|
}
|
|
1956
|
+
/** By name, or by columns (the conventional name; SQLite needs the columns, it doesn't keep foreign key names). */
|
|
1870
1957
|
dropForeign(index) {
|
|
1871
|
-
|
|
1958
|
+
const columns = Array.isArray(index) ? [...index] : void 0;
|
|
1959
|
+
this.commands.push({ name: "dropForeign", index: this.indexNameFor("foreign", index), ...columns ? { columns } : {} });
|
|
1872
1960
|
}
|
|
1873
1961
|
/** Drops the foreign key on the column, then the column. */
|
|
1874
1962
|
dropConstrainedForeignId(column) {
|
|
@@ -1898,6 +1986,14 @@ var Blueprint = class {
|
|
|
1898
1986
|
this.commands.push({ name: "dropIfExists" });
|
|
1899
1987
|
}
|
|
1900
1988
|
// ---------------------------------------------------------------- helpers
|
|
1989
|
+
/** The columns this blueprint adds (not the ones change() redefines). */
|
|
1990
|
+
addedColumns() {
|
|
1991
|
+
return this.columns.filter((column) => !column.attributes.change);
|
|
1992
|
+
}
|
|
1993
|
+
/** The existing columns change() redefines (on a table being created, every column is added instead). */
|
|
1994
|
+
changedColumns() {
|
|
1995
|
+
return this.creating ? [] : this.columns.filter((column) => column.attributes.change === true);
|
|
1996
|
+
}
|
|
1901
1997
|
/** Laravel's default index name: {table}_{columns}_{type}, lowercased, with - and . replaced by _. */
|
|
1902
1998
|
createIndexName(type, columns) {
|
|
1903
1999
|
return `${this.table}_${columns.join("_")}_${type}`.toLowerCase().replace(/[-.]/g, "_");
|
|
@@ -1916,8 +2012,8 @@ var Blueprint = class {
|
|
|
1916
2012
|
return commands;
|
|
1917
2013
|
}
|
|
1918
2014
|
indexCommand(type, columns, name) {
|
|
1919
|
-
const
|
|
1920
|
-
this.commands.push({ name: type, columns:
|
|
2015
|
+
const list3 = [columns].flat();
|
|
2016
|
+
this.commands.push({ name: type, columns: list3, index: name ?? this.createIndexName(type, list3) });
|
|
1921
2017
|
}
|
|
1922
2018
|
indexNameFor(type, index) {
|
|
1923
2019
|
return Array.isArray(index) ? this.createIndexName(type, index) : index;
|
|
@@ -1926,6 +2022,8 @@ var Blueprint = class {
|
|
|
1926
2022
|
|
|
1927
2023
|
// Schema/Grammar.ts
|
|
1928
2024
|
import { sql as sql4 } from "kysely";
|
|
2025
|
+
var list = (value) => value === null || value === void 0 || value === "" ? [] : String(value).split(",");
|
|
2026
|
+
var isTableRebuild = (step) => step.kind === "rebuild";
|
|
1929
2027
|
var join2 = (parts, separator = ", ") => sql4.join(parts, sql4.raw(separator));
|
|
1930
2028
|
var columnList = (columns) => join2(columns.map((column) => sql4.id(column)));
|
|
1931
2029
|
var SchemaGrammar = class {
|
|
@@ -1938,28 +2036,40 @@ var SchemaGrammar = class {
|
|
|
1938
2036
|
if (driver === "mysql") return new MySqlSchemaGrammar(config);
|
|
1939
2037
|
return new SqliteSchemaGrammar(config);
|
|
1940
2038
|
}
|
|
1941
|
-
/**
|
|
2039
|
+
/**
|
|
2040
|
+
* Every statement for the blueprint: create/add first, then commands in order, then indexes from column modifiers.
|
|
2041
|
+
* A blueprint that can only run against the live table (a SQLite rebuild) throws: run it with Schema.table().
|
|
2042
|
+
*/
|
|
1942
2043
|
compile(blueprint) {
|
|
2044
|
+
const steps = this.compileSteps(blueprint);
|
|
2045
|
+
if (steps.some(isTableRebuild)) {
|
|
2046
|
+
throw new LogicError(`On SQLite, changing [${blueprint.table}] rebuilds the table from its live definition: run the blueprint with Schema.table().`);
|
|
2047
|
+
}
|
|
2048
|
+
return steps;
|
|
2049
|
+
}
|
|
2050
|
+
/** compile() with table rebuilds as steps of their own; consecutive rebuilds of one run are merged into one. */
|
|
2051
|
+
compileSteps(blueprint) {
|
|
1943
2052
|
const statements = [];
|
|
1944
2053
|
const commands = [...blueprint.commands, ...blueprint.fluentIndexCommands()];
|
|
1945
2054
|
const handled = /* @__PURE__ */ new Set();
|
|
1946
2055
|
if (blueprint.creating) {
|
|
1947
2056
|
statements.push(this.compileCreate(blueprint, commands, handled));
|
|
1948
|
-
} else
|
|
1949
|
-
statements.push(...this.compileAdd(blueprint, commands, handled));
|
|
2057
|
+
} else {
|
|
2058
|
+
if (blueprint.addedColumns().length) statements.push(...this.compileAdd(blueprint, commands, handled));
|
|
2059
|
+
for (const column of blueprint.changedColumns()) statements.push(...this.compileChange(blueprint, column));
|
|
1950
2060
|
}
|
|
1951
2061
|
for (const command of commands) {
|
|
1952
2062
|
if (command.name === "create" || handled.has(command)) continue;
|
|
1953
2063
|
statements.push(...this.compileCommand(blueprint, command));
|
|
1954
2064
|
}
|
|
1955
2065
|
if (blueprint.creating || blueprint.columns.length) statements.push(...this.compileComments(blueprint));
|
|
1956
|
-
return statements;
|
|
2066
|
+
return mergeRebuilds(statements);
|
|
1957
2067
|
}
|
|
1958
2068
|
compileCreate(blueprint, _commands, _handled) {
|
|
1959
2069
|
return sql4`create table ${sql4.id(blueprint.table)} (${join2(blueprint.columns.map((column) => this.columnDefinition(column)))})`;
|
|
1960
2070
|
}
|
|
1961
2071
|
compileAdd(blueprint, _commands, _handled) {
|
|
1962
|
-
return blueprint.
|
|
2072
|
+
return blueprint.addedColumns().map((column) => sql4`alter table ${sql4.id(blueprint.table)} add column ${this.columnDefinition(column)}`);
|
|
1963
2073
|
}
|
|
1964
2074
|
compileCommand(blueprint, command) {
|
|
1965
2075
|
const table = sql4.id(blueprint.table);
|
|
@@ -2033,7 +2143,8 @@ var SchemaGrammar = class {
|
|
|
2033
2143
|
if (!foreign.referencedTable) {
|
|
2034
2144
|
throw new LogicError(`Foreign key [${foreign.indexName}] has no referenced table: call on('table') or constrained().`);
|
|
2035
2145
|
}
|
|
2036
|
-
const
|
|
2146
|
+
const columns = foreign.referencedColumns.length ? sql4` (${columnList(foreign.referencedColumns)})` : sql4.raw("");
|
|
2147
|
+
const parts = [sql4`references ${sql4.id(foreign.referencedTable)}${columns}`];
|
|
2037
2148
|
if (foreign.deleteAction) parts.push(sql4.raw(`on delete ${foreign.deleteAction}`));
|
|
2038
2149
|
if (foreign.updateAction) parts.push(sql4.raw(`on update ${foreign.updateAction}`));
|
|
2039
2150
|
return join2(parts, " ");
|
|
@@ -2061,9 +2172,21 @@ var SchemaGrammar = class {
|
|
|
2061
2172
|
}
|
|
2062
2173
|
};
|
|
2063
2174
|
var present = (parts) => parts.filter((part) => part !== void 0);
|
|
2175
|
+
function mergeRebuilds(steps) {
|
|
2176
|
+
const merged = [];
|
|
2177
|
+
for (const step of steps) {
|
|
2178
|
+
const previous = merged.at(-1);
|
|
2179
|
+
if (isTableRebuild(step) && previous !== void 0 && isTableRebuild(previous)) {
|
|
2180
|
+
merged[merged.length - 1] = { ...previous, commands: [...previous.commands, ...step.commands], changes: [...previous.changes, ...step.changes] };
|
|
2181
|
+
} else {
|
|
2182
|
+
merged.push(step);
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
return merged;
|
|
2186
|
+
}
|
|
2064
2187
|
var SqliteSchemaGrammar = class extends SchemaGrammar {
|
|
2065
2188
|
driver = "sqlite";
|
|
2066
|
-
/**
|
|
2189
|
+
/** A new table's primary and foreign keys go inside create table (adding them later rebuilds the table). */
|
|
2067
2190
|
compileCreate(blueprint, commands, handled) {
|
|
2068
2191
|
const parts = blueprint.columns.map((column) => this.columnDefinition(column));
|
|
2069
2192
|
for (const command of commands) {
|
|
@@ -2079,7 +2202,7 @@ var SqliteSchemaGrammar = class extends SchemaGrammar {
|
|
|
2079
2202
|
}
|
|
2080
2203
|
/** New columns may carry an inline `references` clause (the only foreign key SQLite can add later). */
|
|
2081
2204
|
compileAdd(blueprint, commands, handled) {
|
|
2082
|
-
return blueprint.
|
|
2205
|
+
return blueprint.addedColumns().map((column) => {
|
|
2083
2206
|
const foreign = commands.find(
|
|
2084
2207
|
(command) => command.name === "foreign" && command.foreign.columns.length === 1 && command.foreign.columns[0] === column.name
|
|
2085
2208
|
);
|
|
@@ -2091,17 +2214,27 @@ var SqliteSchemaGrammar = class extends SchemaGrammar {
|
|
|
2091
2214
|
return sql4`alter table ${sql4.id(blueprint.table)} add column ${definition}`;
|
|
2092
2215
|
});
|
|
2093
2216
|
}
|
|
2217
|
+
/**
|
|
2218
|
+
* SQLite can't add or drop a primary or foreign key on an existing table: those commands rebuild the table (Laravel
|
|
2219
|
+
* 11+'s compileAlter), as a step SchemaBuilder.build() runs against the live table.
|
|
2220
|
+
*/
|
|
2094
2221
|
compileCommand(blueprint, command) {
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
}
|
|
2101
|
-
const action = unsupported[command.name];
|
|
2102
|
-
if (action) throw new LogicError(`SQLite doesn't support ${action}. Recreate the table instead.`);
|
|
2222
|
+
if (command.name === "dropForeign" && !command.columns?.length) {
|
|
2223
|
+
throw new LogicError("This database driver does not support dropping foreign keys by name.");
|
|
2224
|
+
}
|
|
2225
|
+
if (command.name === "primary" || command.name === "foreign" || command.name === "dropPrimary" || command.name === "dropForeign") {
|
|
2226
|
+
return [{ kind: "rebuild", table: blueprint.table, commands: [command], changes: [] }];
|
|
2227
|
+
}
|
|
2103
2228
|
return super.compileCommand(blueprint, command);
|
|
2104
2229
|
}
|
|
2230
|
+
/** SQLite can't alter a column: changing one rebuilds the table with the new definition. */
|
|
2231
|
+
compileChange(blueprint, column) {
|
|
2232
|
+
return [{ kind: "rebuild", table: blueprint.table, commands: [], changes: [column] }];
|
|
2233
|
+
}
|
|
2234
|
+
/** `foreign key (…) references … on delete …`, a table constraint of a rebuilt table. */
|
|
2235
|
+
compileForeignKeyConstraint(foreign) {
|
|
2236
|
+
return this.foreignKeyClause(foreign);
|
|
2237
|
+
}
|
|
2105
2238
|
compileUnique(blueprint, index, columns) {
|
|
2106
2239
|
return sql4`create unique index ${sql4.id(index)} on ${sql4.id(blueprint.table)} (${columnList(columns)})`;
|
|
2107
2240
|
}
|
|
@@ -2173,6 +2306,37 @@ var SqliteSchemaGrammar = class extends SchemaGrammar {
|
|
|
2173
2306
|
};
|
|
2174
2307
|
});
|
|
2175
2308
|
}
|
|
2309
|
+
/** Laravel's query: the primary key from pragma_table_xinfo, then every index of pragma_index_list with its columns. */
|
|
2310
|
+
compileIndexes(table) {
|
|
2311
|
+
return sql4`select 'primary' as name, group_concat(col) as columns, 1 as "unique", 1 as "primary" from (select name as col from pragma_table_xinfo(${table}) where pk > 0 order by pk, cid) group by name
|
|
2312
|
+
union select name, group_concat(col) as columns, "unique", origin = 'pk' as "primary" from (select il.*, ii.name as col from pragma_index_list(${table}) il, pragma_index_info(il.name) ii order by il.seq, ii.seqno) group by name, "unique", "primary"`;
|
|
2313
|
+
}
|
|
2314
|
+
/** A table whose primary key has its own index (not a rowid alias) lists it twice: the index entry is kept. */
|
|
2315
|
+
normalizeIndexes(rows) {
|
|
2316
|
+
const indexes = rows.map((row) => ({
|
|
2317
|
+
name: String(row.name).toLowerCase(),
|
|
2318
|
+
columns: list(row.columns),
|
|
2319
|
+
type: null,
|
|
2320
|
+
unique: Number(row.unique) === 1,
|
|
2321
|
+
primary: Number(row.primary) === 1
|
|
2322
|
+
}));
|
|
2323
|
+
return indexes.filter((index) => index.primary).length > 1 ? indexes.filter((index) => index.name !== "primary") : indexes;
|
|
2324
|
+
}
|
|
2325
|
+
compileForeignKeys(table) {
|
|
2326
|
+
return sql4`select group_concat("from") as columns, 'main' as foreign_schema, "table" as foreign_table, group_concat("to") as foreign_columns, on_update, on_delete
|
|
2327
|
+
from (select * from pragma_foreign_key_list(${table}) order by id desc, seq) group by id, "table", on_update, on_delete`;
|
|
2328
|
+
}
|
|
2329
|
+
normalizeForeignKeys(rows) {
|
|
2330
|
+
return rows.map((row) => ({
|
|
2331
|
+
name: null,
|
|
2332
|
+
columns: list(row.columns),
|
|
2333
|
+
foreign_schema: String(row.foreign_schema),
|
|
2334
|
+
foreign_table: String(row.foreign_table),
|
|
2335
|
+
foreign_columns: list(row.foreign_columns),
|
|
2336
|
+
on_update: String(row.on_update).toLowerCase(),
|
|
2337
|
+
on_delete: String(row.on_delete).toLowerCase()
|
|
2338
|
+
}));
|
|
2339
|
+
}
|
|
2176
2340
|
compileEnableForeignKeyConstraints() {
|
|
2177
2341
|
return sql4.raw("PRAGMA foreign_keys = ON");
|
|
2178
2342
|
}
|
|
@@ -2180,10 +2344,31 @@ var SqliteSchemaGrammar = class extends SchemaGrammar {
|
|
|
2180
2344
|
return sql4.raw("PRAGMA foreign_keys = OFF");
|
|
2181
2345
|
}
|
|
2182
2346
|
};
|
|
2347
|
+
var POSTGRES_ACTIONS = { a: "no action", r: "restrict", c: "cascade", n: "set null", d: "set default" };
|
|
2183
2348
|
var PostgresSchemaGrammar = class extends SchemaGrammar {
|
|
2184
2349
|
driver = "pgsql";
|
|
2350
|
+
/** A changed column's comment is set again, or cleared (`is NULL`) when the new definition has none (Laravel 11+). */
|
|
2185
2351
|
compileComments(blueprint) {
|
|
2186
|
-
|
|
2352
|
+
const changed = new Set(blueprint.changedColumns());
|
|
2353
|
+
return blueprint.columns.filter((column) => column.attributes.comment !== void 0 || changed.has(column)).map((column) => {
|
|
2354
|
+
const comment = column.attributes.comment;
|
|
2355
|
+
return sql4`comment on column ${sql4.id(blueprint.table, column.name)} is ${comment === void 0 ? sql4.raw("NULL") : sql4.lit(comment)}`;
|
|
2356
|
+
});
|
|
2357
|
+
}
|
|
2358
|
+
/**
|
|
2359
|
+
* Laravel's compileChange(): `alter column` for the type, the nullability and the default, in one statement. A serial
|
|
2360
|
+
* type becomes its integer type (the sequence stays), and an auto-increment column keeps its default. No `using`
|
|
2361
|
+
* clause: a change Postgres can't cast implicitly fails, as in Laravel.
|
|
2362
|
+
*/
|
|
2363
|
+
compileChange(blueprint, column) {
|
|
2364
|
+
const name = sql4.id(column.name);
|
|
2365
|
+
const { autoIncrement, nullable, default: value } = column.attributes;
|
|
2366
|
+
const changes = [
|
|
2367
|
+
sql4`type ${this.type(new ColumnDefinition({ ...column.attributes, autoIncrement: false }))}`,
|
|
2368
|
+
sql4.raw(nullable ? "drop not null" : "set not null")
|
|
2369
|
+
];
|
|
2370
|
+
if (!autoIncrement) changes.push(value === void 0 || value === null ? sql4.raw("drop default") : sql4`set default ${this.defaultValue(value)}`);
|
|
2371
|
+
return [sql4`alter table ${sql4.id(blueprint.table)} ${join2(changes.map((change) => sql4`alter column ${name} ${change}`))}`];
|
|
2187
2372
|
}
|
|
2188
2373
|
type(column) {
|
|
2189
2374
|
const { type, autoIncrement, length, total, places, precision } = column.attributes;
|
|
@@ -2262,6 +2447,52 @@ var PostgresSchemaGrammar = class extends SchemaGrammar {
|
|
|
2262
2447
|
};
|
|
2263
2448
|
});
|
|
2264
2449
|
}
|
|
2450
|
+
compileIndexes(table) {
|
|
2451
|
+
return sql4`select ic.relname as name, string_agg(a.attname, ',' order by indseq.ord) as columns, am.amname as ${sql4.id("type")}, i.indisunique as ${sql4.id("unique")}, i.indisprimary as ${sql4.id("primary")}
|
|
2452
|
+
from pg_index i
|
|
2453
|
+
join pg_class tc on tc.oid = i.indrelid
|
|
2454
|
+
join pg_namespace tn on tn.oid = tc.relnamespace
|
|
2455
|
+
join pg_class ic on ic.oid = i.indexrelid
|
|
2456
|
+
join pg_am am on am.oid = ic.relam
|
|
2457
|
+
join lateral unnest(i.indkey) with ordinality as indseq(num, ord) on true
|
|
2458
|
+
left join pg_attribute a on a.attrelid = i.indrelid and a.attnum = indseq.num
|
|
2459
|
+
where tc.relname = ${table} and tn.nspname = current_schema()
|
|
2460
|
+
group by ic.relname, am.amname, i.indisunique, i.indisprimary`;
|
|
2461
|
+
}
|
|
2462
|
+
normalizeIndexes(rows) {
|
|
2463
|
+
return rows.map((row) => ({
|
|
2464
|
+
name: String(row.name).toLowerCase(),
|
|
2465
|
+
columns: list(row.columns),
|
|
2466
|
+
type: String(row.type).toLowerCase(),
|
|
2467
|
+
unique: row.unique === true,
|
|
2468
|
+
primary: row.primary === true
|
|
2469
|
+
}));
|
|
2470
|
+
}
|
|
2471
|
+
compileForeignKeys(table) {
|
|
2472
|
+
return sql4`select c.conname as name, string_agg(la.attname, ',' order by conseq.ord) as columns, fn.nspname as foreign_schema, fc.relname as foreign_table,
|
|
2473
|
+
string_agg(fa.attname, ',' order by conseq.ord) as foreign_columns, c.confupdtype as on_update, c.confdeltype as on_delete
|
|
2474
|
+
from pg_constraint c
|
|
2475
|
+
join pg_class tc on c.conrelid = tc.oid
|
|
2476
|
+
join pg_namespace tn on tn.oid = tc.relnamespace
|
|
2477
|
+
join pg_class fc on c.confrelid = fc.oid
|
|
2478
|
+
join pg_namespace fn on fn.oid = fc.relnamespace
|
|
2479
|
+
join lateral unnest(c.conkey) with ordinality as conseq(num, ord) on true
|
|
2480
|
+
join pg_attribute la on la.attrelid = c.conrelid and la.attnum = conseq.num
|
|
2481
|
+
join pg_attribute fa on fa.attrelid = c.confrelid and fa.attnum = c.confkey[conseq.ord]
|
|
2482
|
+
where c.contype = 'f' and tc.relname = ${table} and tn.nspname = current_schema()
|
|
2483
|
+
group by c.conname, fn.nspname, fc.relname, c.confupdtype, c.confdeltype`;
|
|
2484
|
+
}
|
|
2485
|
+
normalizeForeignKeys(rows) {
|
|
2486
|
+
return rows.map((row) => ({
|
|
2487
|
+
name: String(row.name),
|
|
2488
|
+
columns: list(row.columns),
|
|
2489
|
+
foreign_schema: String(row.foreign_schema),
|
|
2490
|
+
foreign_table: String(row.foreign_table),
|
|
2491
|
+
foreign_columns: list(row.foreign_columns),
|
|
2492
|
+
on_update: POSTGRES_ACTIONS[String(row.on_update).toLowerCase()] ?? "no action",
|
|
2493
|
+
on_delete: POSTGRES_ACTIONS[String(row.on_delete).toLowerCase()] ?? "no action"
|
|
2494
|
+
}));
|
|
2495
|
+
}
|
|
2265
2496
|
compileEnableForeignKeyConstraints() {
|
|
2266
2497
|
return sql4.raw("SET CONSTRAINTS ALL IMMEDIATE");
|
|
2267
2498
|
}
|
|
@@ -2277,7 +2508,11 @@ var MySqlSchemaGrammar = class extends SchemaGrammar {
|
|
|
2277
2508
|
return sql4`${super.compileCreate(blueprint, commands, handled)} default character set ${sql4.raw(charset.replace(/[^\w]/g, ""))} collate ${sql4.lit(collation)}`;
|
|
2278
2509
|
}
|
|
2279
2510
|
compileAdd(blueprint) {
|
|
2280
|
-
return blueprint.
|
|
2511
|
+
return blueprint.addedColumns().map((column) => sql4`alter table ${sql4.id(blueprint.table)} add ${this.columnDefinition(column)}`);
|
|
2512
|
+
}
|
|
2513
|
+
/** Laravel's compileChange(): `modify` with the column's whole new definition. */
|
|
2514
|
+
compileChange(blueprint, column) {
|
|
2515
|
+
return [sql4`alter table ${sql4.id(blueprint.table)} modify ${this.columnDefinition(column)}`];
|
|
2281
2516
|
}
|
|
2282
2517
|
compileUnique(blueprint, index, columns) {
|
|
2283
2518
|
return sql4`alter table ${sql4.id(blueprint.table)} add unique ${sql4.id(index)}(${columnList(columns)})`;
|
|
@@ -2350,13 +2585,14 @@ var MySqlSchemaGrammar = class extends SchemaGrammar {
|
|
|
2350
2585
|
}
|
|
2351
2586
|
}
|
|
2352
2587
|
modifiers(column) {
|
|
2353
|
-
const { unsigned, autoIncrement, onUpdate, comment, after, first } = column.attributes;
|
|
2588
|
+
const { unsigned, autoIncrement, onUpdate, comment, after, first, change, primary } = column.attributes;
|
|
2589
|
+
const increment = change && !primary ? " auto_increment" : " auto_increment primary key";
|
|
2354
2590
|
return present([
|
|
2355
2591
|
unsigned ? sql4.raw(" unsigned") : void 0,
|
|
2356
2592
|
this.nullable(column),
|
|
2357
2593
|
this.default(column),
|
|
2358
2594
|
onUpdate ? sql4` on update ${this.defaultValue(onUpdate)}` : void 0,
|
|
2359
|
-
autoIncrement ? sql4.raw(
|
|
2595
|
+
autoIncrement ? sql4.raw(increment) : void 0,
|
|
2360
2596
|
comment === void 0 ? void 0 : sql4` comment ${sql4.lit(comment)}`,
|
|
2361
2597
|
after === void 0 ? void 0 : sql4` after ${sql4.id(after)}`,
|
|
2362
2598
|
first ? sql4.raw(" first") : void 0
|
|
@@ -2379,6 +2615,37 @@ var MySqlSchemaGrammar = class extends SchemaGrammar {
|
|
|
2379
2615
|
auto_increment: Number(row.auto_increment) === 1
|
|
2380
2616
|
}));
|
|
2381
2617
|
}
|
|
2618
|
+
compileIndexes(table) {
|
|
2619
|
+
return sql4`select index_name as ${sql4.id("name")}, group_concat(column_name order by seq_in_index) as ${sql4.id("columns")}, index_type as ${sql4.id("type")}, not non_unique as ${sql4.id("unique")}
|
|
2620
|
+
from information_schema.statistics where table_schema = schema() and table_name = ${table}
|
|
2621
|
+
group by index_name, index_type, non_unique`;
|
|
2622
|
+
}
|
|
2623
|
+
normalizeIndexes(rows) {
|
|
2624
|
+
return rows.map((row) => {
|
|
2625
|
+
const name = String(row.name).toLowerCase();
|
|
2626
|
+
return { name, columns: list(row.columns), type: String(row.type).toLowerCase(), unique: Number(row.unique) === 1, primary: name === "primary" };
|
|
2627
|
+
});
|
|
2628
|
+
}
|
|
2629
|
+
compileForeignKeys(table) {
|
|
2630
|
+
return sql4`select kc.constraint_name as ${sql4.id("name")}, group_concat(kc.column_name order by kc.ordinal_position) as ${sql4.id("columns")},
|
|
2631
|
+
kc.referenced_table_schema as ${sql4.id("foreign_schema")}, kc.referenced_table_name as ${sql4.id("foreign_table")},
|
|
2632
|
+
group_concat(kc.referenced_column_name order by kc.ordinal_position) as ${sql4.id("foreign_columns")}, rc.update_rule as ${sql4.id("on_update")}, rc.delete_rule as ${sql4.id("on_delete")}
|
|
2633
|
+
from information_schema.key_column_usage kc join information_schema.referential_constraints rc
|
|
2634
|
+
on kc.constraint_schema = rc.constraint_schema and kc.constraint_name = rc.constraint_name
|
|
2635
|
+
where kc.table_schema = schema() and kc.table_name = ${table} and kc.referenced_table_name is not null
|
|
2636
|
+
group by kc.constraint_name, kc.referenced_table_schema, kc.referenced_table_name, rc.update_rule, rc.delete_rule`;
|
|
2637
|
+
}
|
|
2638
|
+
normalizeForeignKeys(rows) {
|
|
2639
|
+
return rows.map((row) => ({
|
|
2640
|
+
name: String(row.name),
|
|
2641
|
+
columns: list(row.columns),
|
|
2642
|
+
foreign_schema: String(row.foreign_schema),
|
|
2643
|
+
foreign_table: String(row.foreign_table),
|
|
2644
|
+
foreign_columns: list(row.foreign_columns),
|
|
2645
|
+
on_update: String(row.on_update).toLowerCase(),
|
|
2646
|
+
on_delete: String(row.on_delete).toLowerCase()
|
|
2647
|
+
}));
|
|
2648
|
+
}
|
|
2382
2649
|
compileEnableForeignKeyConstraints() {
|
|
2383
2650
|
return sql4.raw("SET FOREIGN_KEY_CHECKS=1");
|
|
2384
2651
|
}
|
|
@@ -2387,6 +2654,235 @@ var MySqlSchemaGrammar = class extends SchemaGrammar {
|
|
|
2387
2654
|
}
|
|
2388
2655
|
};
|
|
2389
2656
|
|
|
2657
|
+
// Schema/SqliteTableRebuild.ts
|
|
2658
|
+
import { sql as sql5 } from "kysely";
|
|
2659
|
+
var QUOTES = { "'": "'", '"': '"', "`": "`", "[": "]" };
|
|
2660
|
+
var lower = (value) => value.toLowerCase();
|
|
2661
|
+
var join3 = (parts, separator = ", ") => sql5.join(parts, sql5.raw(separator));
|
|
2662
|
+
var columnList2 = (columns) => join3(columns.map((column) => sql5.id(column)));
|
|
2663
|
+
var sameColumns = (a, b) => a.length === b.length && a.every((column, i) => lower(column) === lower(b[i]));
|
|
2664
|
+
function mask(text2) {
|
|
2665
|
+
let out = "";
|
|
2666
|
+
for (let i = 0; i < text2.length; i++) {
|
|
2667
|
+
const char = text2[i];
|
|
2668
|
+
const closer = QUOTES[char];
|
|
2669
|
+
let end = -1;
|
|
2670
|
+
if (closer !== void 0) {
|
|
2671
|
+
end = i + 1;
|
|
2672
|
+
while (end < text2.length && !(text2[end] === closer && (closer === "]" || text2[end + 1] !== closer))) end += text2[end] === closer ? 2 : 1;
|
|
2673
|
+
} else if (char === "-" && text2[i + 1] === "-") {
|
|
2674
|
+
end = text2.indexOf("\n", i);
|
|
2675
|
+
if (end === -1) end = text2.length - 1;
|
|
2676
|
+
} else if (char === "/" && text2[i + 1] === "*") {
|
|
2677
|
+
end = text2.indexOf("*/", i + 2);
|
|
2678
|
+
end = end === -1 ? text2.length - 1 : end + 1;
|
|
2679
|
+
}
|
|
2680
|
+
if (end === -1) {
|
|
2681
|
+
out += char;
|
|
2682
|
+
continue;
|
|
2683
|
+
}
|
|
2684
|
+
out += " ".repeat(Math.min(end, text2.length - 1) - i + 1);
|
|
2685
|
+
i = end;
|
|
2686
|
+
}
|
|
2687
|
+
return out;
|
|
2688
|
+
}
|
|
2689
|
+
function closingParen(masked, open) {
|
|
2690
|
+
let depth = 0;
|
|
2691
|
+
for (let i = open; i < masked.length; i++) {
|
|
2692
|
+
if (masked[i] === "(") depth++;
|
|
2693
|
+
else if (masked[i] === ")" && --depth === 0) return i + 1;
|
|
2694
|
+
}
|
|
2695
|
+
return masked.length;
|
|
2696
|
+
}
|
|
2697
|
+
function splitCreateTable(statement) {
|
|
2698
|
+
const masked = mask(statement);
|
|
2699
|
+
const open = masked.indexOf("(");
|
|
2700
|
+
if (open === -1) return { definitions: [], options: "" };
|
|
2701
|
+
const close = closingParen(masked, open) - 1;
|
|
2702
|
+
const definitions = [];
|
|
2703
|
+
let depth = 0;
|
|
2704
|
+
let start = open + 1;
|
|
2705
|
+
for (let i = open + 1; i < close; i++) {
|
|
2706
|
+
if (masked[i] === "(") depth++;
|
|
2707
|
+
else if (masked[i] === ")") depth--;
|
|
2708
|
+
else if (masked[i] === "," && depth === 0) {
|
|
2709
|
+
definitions.push(statement.slice(start, i).trim());
|
|
2710
|
+
start = i + 1;
|
|
2711
|
+
}
|
|
2712
|
+
}
|
|
2713
|
+
definitions.push(statement.slice(start, close).trim());
|
|
2714
|
+
return { definitions: definitions.filter((definition) => definition !== ""), options: statement.slice(close + 1) };
|
|
2715
|
+
}
|
|
2716
|
+
function definedColumn(definition) {
|
|
2717
|
+
const closer = QUOTES[definition[0] ?? ""];
|
|
2718
|
+
if (closer !== void 0) {
|
|
2719
|
+
const end = definition.indexOf(closer, 1);
|
|
2720
|
+
return definition.slice(1, end === -1 ? void 0 : end).replaceAll(`${closer}${closer}`, closer);
|
|
2721
|
+
}
|
|
2722
|
+
if (/^(constraint|primary|unique|check|foreign)\b/i.test(definition)) return void 0;
|
|
2723
|
+
return /^[^\s(]+/.exec(definition)?.[0];
|
|
2724
|
+
}
|
|
2725
|
+
function columnClauses(definition) {
|
|
2726
|
+
const masked = mask(definition);
|
|
2727
|
+
const checks = [];
|
|
2728
|
+
for (const match of masked.matchAll(/\bcheck\s*\(/gi)) {
|
|
2729
|
+
const open = match.index + match[0].length - 1;
|
|
2730
|
+
checks.push(definition.slice(open, closingParen(masked, open)));
|
|
2731
|
+
}
|
|
2732
|
+
const collate = /\bcollate\s+/i.exec(masked);
|
|
2733
|
+
let collation;
|
|
2734
|
+
if (collate) {
|
|
2735
|
+
const rest = definition.slice(collate.index + collate[0].length);
|
|
2736
|
+
const closer = QUOTES[rest[0] ?? ""];
|
|
2737
|
+
collation = closer === void 0 ? /^\w+/.exec(rest)?.[0] : rest.slice(0, rest.indexOf(closer, 1) + 1);
|
|
2738
|
+
}
|
|
2739
|
+
return { checks, collation, autoincrement: /\bautoincrement\b/i.test(masked) };
|
|
2740
|
+
}
|
|
2741
|
+
var isTableCheck = (definition) => /^(constraint\s+\S+\s+)?check\b/i.test(mask(definition));
|
|
2742
|
+
function renderColumn(column, definition, autoincrement) {
|
|
2743
|
+
const clauses2 = definition === void 0 ? { checks: [], collation: void 0 } : columnClauses(definition);
|
|
2744
|
+
const parts = [sql5.id(column.name)];
|
|
2745
|
+
if (column.type) parts.push(sql5.raw(` ${column.type}`));
|
|
2746
|
+
if (autoincrement) parts.push(sql5.raw(" primary key autoincrement"));
|
|
2747
|
+
if (Number(column.notnull) === 1) parts.push(sql5.raw(" not null"));
|
|
2748
|
+
if (column.dflt_value !== null && column.dflt_value !== void 0) parts.push(sql5.raw(` default (${column.dflt_value})`));
|
|
2749
|
+
if (clauses2.collation) parts.push(sql5.raw(` collate ${clauses2.collation}`));
|
|
2750
|
+
for (const check of clauses2.checks) parts.push(sql5.raw(` check ${check}`));
|
|
2751
|
+
return join3(parts, "");
|
|
2752
|
+
}
|
|
2753
|
+
function foreignKeyDefinition(key) {
|
|
2754
|
+
const definition = new ForeignKeyDefinition(key.columns, "").references(key.foreign_columns).on(key.foreign_table);
|
|
2755
|
+
if (key.on_delete !== "no action") definition.onDelete(key.on_delete);
|
|
2756
|
+
if (key.on_update !== "no action") definition.onUpdate(key.on_update);
|
|
2757
|
+
return definition;
|
|
2758
|
+
}
|
|
2759
|
+
async function sqliteForeignKeysEnabled(db) {
|
|
2760
|
+
const rows = await db.select("PRAGMA foreign_keys");
|
|
2761
|
+
return Number(rows[0]?.foreign_keys) === 1;
|
|
2762
|
+
}
|
|
2763
|
+
async function assertSqliteForeignKeys(db, table, hint) {
|
|
2764
|
+
const statement = table === void 0 ? sql5.raw("PRAGMA foreign_key_check") : sql5`PRAGMA foreign_key_check(${sql5.id(table)})`;
|
|
2765
|
+
const rows = (await db.execute(statement)).rows;
|
|
2766
|
+
if (!rows.length) return;
|
|
2767
|
+
const shown = rows.slice(0, 5).map((row) => `[${row.table}] row ${row.rowid ?? "?"} points at no row of [${row.parent}]`);
|
|
2768
|
+
const more = rows.length > 5 ? `; and ${rows.length - 5} more` : "";
|
|
2769
|
+
throw new LogicError(`Foreign key check failed: ${shown.join("; ")}${more}.${hint === void 0 ? "" : ` ${hint}`}`);
|
|
2770
|
+
}
|
|
2771
|
+
async function referencingTables(db, table) {
|
|
2772
|
+
const rows = await db.select(
|
|
2773
|
+
`select m.name as name from sqlite_master m, pragma_foreign_key_list(m.name) f where m.type = 'table' and lower(f."table") = lower(?) group by m.name order by m.name`,
|
|
2774
|
+
[table]
|
|
2775
|
+
);
|
|
2776
|
+
return rows.map((row) => row.name);
|
|
2777
|
+
}
|
|
2778
|
+
async function rebuildSqliteTable(db, grammar, step) {
|
|
2779
|
+
const enabled = await sqliteForeignKeysEnabled(db);
|
|
2780
|
+
if (enabled && db.transactionLevel() === 0) {
|
|
2781
|
+
await db.statement("PRAGMA foreign_keys = OFF");
|
|
2782
|
+
try {
|
|
2783
|
+
await db.transaction(() => rebuild(db, grammar, step));
|
|
2784
|
+
} finally {
|
|
2785
|
+
await db.statement("PRAGMA foreign_keys = ON");
|
|
2786
|
+
}
|
|
2787
|
+
return;
|
|
2788
|
+
}
|
|
2789
|
+
if (enabled) {
|
|
2790
|
+
const referencing = await referencingTables(db, step.table);
|
|
2791
|
+
if (referencing.length) {
|
|
2792
|
+
const names = referencing.map((name) => `[${name}]`).join(", ");
|
|
2793
|
+
throw new LogicError(
|
|
2794
|
+
`SQLite can't rebuild [${step.table}] inside a transaction while foreign keys are on: ${names} ${referencing.length === 1 ? "references" : "reference"} it, and dropping the old table would run their ON DELETE actions. Run the change outside the transaction, or with foreign keys off (the migrator turns them off around a migration that runs in a transaction).`
|
|
2795
|
+
);
|
|
2796
|
+
}
|
|
2797
|
+
}
|
|
2798
|
+
await db.transaction(() => rebuild(db, grammar, step));
|
|
2799
|
+
}
|
|
2800
|
+
async function rebuild(db, grammar, step) {
|
|
2801
|
+
const { table } = step;
|
|
2802
|
+
const [master] = await db.select("select sql from sqlite_master where type = 'table' and name = ?", [table]);
|
|
2803
|
+
if (!master) throw new LogicError(`Table [${table}] doesn't exist.`);
|
|
2804
|
+
const columns = await db.select('select name, type, "notnull", dflt_value, pk, hidden from pragma_table_xinfo(?) order by cid', [table]);
|
|
2805
|
+
if (columns.some((column) => Number(column.hidden) !== 0)) {
|
|
2806
|
+
throw new LogicError(`SQLite can't rebuild [${table}]: it has generated or hidden columns.`);
|
|
2807
|
+
}
|
|
2808
|
+
const { definitions, options } = splitCreateTable(master.sql);
|
|
2809
|
+
const declared = /* @__PURE__ */ new Map();
|
|
2810
|
+
for (const definition of definitions) {
|
|
2811
|
+
const name = definedColumn(definition);
|
|
2812
|
+
if (name !== void 0) declared.set(lower(name), definition);
|
|
2813
|
+
}
|
|
2814
|
+
const keyColumns = columns.filter((column) => Number(column.pk) > 0).sort((a, b) => Number(a.pk) - Number(b.pk));
|
|
2815
|
+
let autoincrement = keyColumns.length === 1 && columnClauses(declared.get(lower(keyColumns[0].name)) ?? "").autoincrement ? keyColumns[0].name : void 0;
|
|
2816
|
+
let primary = keyColumns.map((column) => column.name);
|
|
2817
|
+
const foreign = grammar.normalizeForeignKeys((await db.execute(grammar.compileForeignKeys(table))).rows).map(foreignKeyDefinition);
|
|
2818
|
+
for (const change of step.changes) {
|
|
2819
|
+
if (!columns.some((column) => lower(column.name) === lower(change.name))) throw new LogicError(`[${table}] has no column [${change.name}] to change.`);
|
|
2820
|
+
if (change.attributes.autoIncrement) {
|
|
2821
|
+
autoincrement = change.name;
|
|
2822
|
+
primary = [change.name];
|
|
2823
|
+
} else if (autoincrement !== void 0 && lower(autoincrement) === lower(change.name)) {
|
|
2824
|
+
autoincrement = void 0;
|
|
2825
|
+
}
|
|
2826
|
+
}
|
|
2827
|
+
const changes = new Map(step.changes.map((change) => [lower(change.name), change]));
|
|
2828
|
+
for (const command of step.commands) {
|
|
2829
|
+
if (command.name === "primary") {
|
|
2830
|
+
if (autoincrement !== void 0) {
|
|
2831
|
+
throw new LogicError(`[${table}] already has an auto-increment primary key [${autoincrement}]: drop it first with dropPrimary().`);
|
|
2832
|
+
}
|
|
2833
|
+
primary = [...command.columns];
|
|
2834
|
+
} else if (command.name === "dropPrimary") {
|
|
2835
|
+
primary = [];
|
|
2836
|
+
autoincrement = void 0;
|
|
2837
|
+
} else if (command.name === "foreign") {
|
|
2838
|
+
foreign.push(command.foreign);
|
|
2839
|
+
} else if (command.name === "dropForeign") {
|
|
2840
|
+
const columnsOf = command.columns ?? [];
|
|
2841
|
+
const index = foreign.findIndex((key) => sameColumns(key.columns, columnsOf));
|
|
2842
|
+
if (index === -1) throw new LogicError(`[${table}] has no foreign key on [${columnsOf.join(", ")}].`);
|
|
2843
|
+
foreign.splice(index, 1);
|
|
2844
|
+
}
|
|
2845
|
+
}
|
|
2846
|
+
const parts = columns.map((column) => {
|
|
2847
|
+
const change = changes.get(lower(column.name));
|
|
2848
|
+
return change ? grammar.columnDefinition(change) : renderColumn(column, declared.get(lower(column.name)), column.name === autoincrement);
|
|
2849
|
+
});
|
|
2850
|
+
if (autoincrement === void 0 && primary.length) parts.push(sql5`primary key (${columnList2(primary)})`);
|
|
2851
|
+
for (const key of foreign) parts.push(grammar.compileForeignKeyConstraint(key));
|
|
2852
|
+
for (const definition of definitions) if (isTableCheck(definition)) parts.push(sql5.raw(definition));
|
|
2853
|
+
const indexes = await db.select("select sql from sqlite_master where type = 'index' and tbl_name = ? and sql is not null", [table]);
|
|
2854
|
+
const uniques = await db.select(
|
|
2855
|
+
"select group_concat(col) as columns from (select il.name as name, ii.name as col from pragma_index_list(?) il, pragma_index_info(il.name) ii where il.origin = 'u' order by il.seq, ii.seqno) group by name",
|
|
2856
|
+
[table]
|
|
2857
|
+
);
|
|
2858
|
+
const triggers = await db.select("select sql from sqlite_master where type = 'trigger' and tbl_name = ?", [table]);
|
|
2859
|
+
const hasSequence = (await db.select("select name from sqlite_master where type = 'table' and name = 'sqlite_sequence'")).length > 0;
|
|
2860
|
+
const sequence = hasSequence ? (await db.select("select seq from sqlite_sequence where name = ?", [table]))[0]?.seq : void 0;
|
|
2861
|
+
const temp = `__temp__${table}`;
|
|
2862
|
+
const names = columns.map((column) => sql5.id(column.name));
|
|
2863
|
+
const statements = [
|
|
2864
|
+
sql5`create table ${sql5.id(temp)} (${join3(parts)})${sql5.raw(options)}`,
|
|
2865
|
+
sql5`insert into ${sql5.id(temp)} (${join3(names)}) select ${join3(names)} from ${sql5.id(table)}`,
|
|
2866
|
+
sql5`drop table ${sql5.id(table)}`,
|
|
2867
|
+
sql5`alter table ${sql5.id(temp)} rename to ${sql5.id(table)}`,
|
|
2868
|
+
...indexes.map((index) => sql5.raw(index.sql)),
|
|
2869
|
+
...uniques.map(({ columns: list3 }) => {
|
|
2870
|
+
const unique = list3.split(",");
|
|
2871
|
+
return sql5`create unique index ${sql5.id(`${table}_${unique.join("_")}_unique`.toLowerCase())} on ${sql5.id(table)} (${columnList2(unique)})`;
|
|
2872
|
+
}),
|
|
2873
|
+
...triggers.map((trigger) => sql5.raw(trigger.sql))
|
|
2874
|
+
];
|
|
2875
|
+
for (const statement of statements) await db.execute(statement);
|
|
2876
|
+
if (autoincrement !== void 0 && sequence !== void 0) await restoreSequence(db, table, Number(sequence));
|
|
2877
|
+
await assertSqliteForeignKeys(db, table);
|
|
2878
|
+
for (const child of await referencingTables(db, table)) if (lower(child) !== lower(table)) await assertSqliteForeignKeys(db, child);
|
|
2879
|
+
}
|
|
2880
|
+
async function restoreSequence(db, table, sequence) {
|
|
2881
|
+
const [current] = await db.select("select seq from sqlite_sequence where name = ?", [table]);
|
|
2882
|
+
if (!current) await db.statement("insert into sqlite_sequence (name, seq) values (?, ?)", [table, sequence]);
|
|
2883
|
+
else if (Number(current.seq) < sequence) await db.statement("update sqlite_sequence set seq = ? where name = ?", [sequence, table]);
|
|
2884
|
+
}
|
|
2885
|
+
|
|
2390
2886
|
// Schema/Builder.ts
|
|
2391
2887
|
var SchemaBuilder = class _SchemaBuilder {
|
|
2392
2888
|
constructor(db, resolveConnection) {
|
|
@@ -2425,9 +2921,15 @@ var SchemaBuilder = class _SchemaBuilder {
|
|
|
2425
2921
|
async rename(from, to) {
|
|
2426
2922
|
await this.run([this.grammar.compileRename(from, to)]);
|
|
2427
2923
|
}
|
|
2428
|
-
/**
|
|
2924
|
+
/**
|
|
2925
|
+
* Runs a blueprint's statements in order (inspect them with grammar.compile(blueprint)). On SQLite, a change to the
|
|
2926
|
+
* keys of an existing table rebuilds it from its live definition at its place in that order.
|
|
2927
|
+
*/
|
|
2429
2928
|
async build(blueprint) {
|
|
2430
|
-
|
|
2929
|
+
for (const step of this.grammar.compileSteps(blueprint)) {
|
|
2930
|
+
if (isTableRebuild(step)) await rebuildSqliteTable(this.db, this.grammar, step);
|
|
2931
|
+
else await this.db.execute(step);
|
|
2932
|
+
}
|
|
2431
2933
|
}
|
|
2432
2934
|
/** The table names of the connection's database (or current schema on Postgres). */
|
|
2433
2935
|
async getTables() {
|
|
@@ -2452,6 +2954,31 @@ var SchemaBuilder = class _SchemaBuilder {
|
|
|
2452
2954
|
const existing = (await this.getColumnListing(table)).map((name) => name.toLowerCase());
|
|
2453
2955
|
return columns.every((column) => existing.includes(column.toLowerCase()));
|
|
2454
2956
|
}
|
|
2957
|
+
/** The table's indexes, its primary key included (Laravel's getIndexes()). */
|
|
2958
|
+
async getIndexes(table) {
|
|
2959
|
+
const rows = (await this.db.execute(this.grammar.compileIndexes(table))).rows;
|
|
2960
|
+
return this.grammar.normalizeIndexes(rows);
|
|
2961
|
+
}
|
|
2962
|
+
async getIndexListing(table) {
|
|
2963
|
+
return (await this.getIndexes(table)).map((index) => index.name);
|
|
2964
|
+
}
|
|
2965
|
+
/**
|
|
2966
|
+
* Whether the table has an index with this name, or on exactly these columns (in order). `type` narrows it:
|
|
2967
|
+
* 'primary', 'unique', or an index method such as 'btree'.
|
|
2968
|
+
*/
|
|
2969
|
+
async hasIndex(table, index, type) {
|
|
2970
|
+
const wanted = type?.toLowerCase();
|
|
2971
|
+
return (await this.getIndexes(table)).some((value) => {
|
|
2972
|
+
const typeMatches = wanted === void 0 || wanted === "primary" && value.primary || wanted === "unique" && value.unique || wanted === value.type;
|
|
2973
|
+
const indexMatches = typeof index === "string" ? value.name === index : value.columns.length === index.length && value.columns.every((column, i) => column === index[i]);
|
|
2974
|
+
return indexMatches && typeMatches;
|
|
2975
|
+
});
|
|
2976
|
+
}
|
|
2977
|
+
/** The table's foreign keys (Laravel's getForeignKeys()). */
|
|
2978
|
+
async getForeignKeys(table) {
|
|
2979
|
+
const rows = (await this.db.execute(this.grammar.compileForeignKeys(table))).rows;
|
|
2980
|
+
return this.grammar.normalizeForeignKeys(rows);
|
|
2981
|
+
}
|
|
2455
2982
|
async enableForeignKeyConstraints() {
|
|
2456
2983
|
await this.run([this.grammar.compileEnableForeignKeyConstraints()]);
|
|
2457
2984
|
}
|
|
@@ -2478,7 +3005,7 @@ var SchemaBuilder = class _SchemaBuilder {
|
|
|
2478
3005
|
const tables = await this.getTables();
|
|
2479
3006
|
if (!tables.length) return;
|
|
2480
3007
|
if (this.db.getDriverName() === "pgsql") {
|
|
2481
|
-
await this.run([
|
|
3008
|
+
await this.run([sql6`drop table ${sql6.join(tables.map((table) => sql6.id(table)))} cascade`]);
|
|
2482
3009
|
return;
|
|
2483
3010
|
}
|
|
2484
3011
|
await this.withoutForeignKeyConstraints(async () => {
|
|
@@ -2624,16 +3151,16 @@ var Connection = class {
|
|
|
2624
3151
|
const parent = this.current();
|
|
2625
3152
|
if (!parent) return { trx: await this.db.startTransaction().execute(), level: 1 };
|
|
2626
3153
|
const level = parent.level + 1;
|
|
2627
|
-
await
|
|
3154
|
+
await sql7.raw(`SAVEPOINT trans${level}`).execute(parent.trx);
|
|
2628
3155
|
return { trx: parent.trx, level };
|
|
2629
3156
|
}
|
|
2630
3157
|
async close(frame, action) {
|
|
2631
3158
|
if (frame.level === 1) {
|
|
2632
3159
|
await (action === "commit" ? frame.trx.commit() : frame.trx.rollback()).execute();
|
|
2633
3160
|
} else if (action === "commit") {
|
|
2634
|
-
await
|
|
3161
|
+
await sql7.raw(`RELEASE SAVEPOINT trans${frame.level}`).execute(frame.trx);
|
|
2635
3162
|
} else {
|
|
2636
|
-
await
|
|
3163
|
+
await sql7.raw(`ROLLBACK TO SAVEPOINT trans${frame.level}`).execute(frame.trx);
|
|
2637
3164
|
}
|
|
2638
3165
|
}
|
|
2639
3166
|
};
|
|
@@ -2797,8 +3324,8 @@ var Schema = facade(SchemaBuilderToken);
|
|
|
2797
3324
|
|
|
2798
3325
|
// Eloquent/Model.ts
|
|
2799
3326
|
import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
|
|
2800
|
-
import { DatabaseManager as DatabaseManager2 } from "@orieljs/contracts";
|
|
2801
|
-
import { Collection as
|
|
3327
|
+
import { DatabaseManager as DatabaseManager2, Hasher } from "@orieljs/contracts";
|
|
3328
|
+
import { Collection as Collection10 } from "@orieljs/collections";
|
|
2802
3329
|
import { currentContainer as currentContainer3, inject } from "@orieljs/container";
|
|
2803
3330
|
import { Str as Str6 } from "@orieljs/support";
|
|
2804
3331
|
|
|
@@ -2844,6 +3371,8 @@ var Builder2 = class extends Builder {
|
|
|
2844
3371
|
scopes = /* @__PURE__ */ new Map();
|
|
2845
3372
|
removedScopes = [];
|
|
2846
3373
|
eagerLoad = /* @__PURE__ */ new Map();
|
|
3374
|
+
/** Casts for the selected columns (withCasts()), merged into every model this query hydrates. */
|
|
3375
|
+
selectCasts = {};
|
|
2847
3376
|
constructor(model) {
|
|
2848
3377
|
super(model.getConnection(), model.getTable());
|
|
2849
3378
|
this.model = model;
|
|
@@ -2937,6 +3466,36 @@ var Builder2 = class extends Builder {
|
|
|
2937
3466
|
whereBetween(column, values) {
|
|
2938
3467
|
return super.whereBetween(column, values);
|
|
2939
3468
|
}
|
|
3469
|
+
whereDate(column, ...args) {
|
|
3470
|
+
return super.whereDate(column, ...args);
|
|
3471
|
+
}
|
|
3472
|
+
orWhereDate(column, ...args) {
|
|
3473
|
+
return super.orWhereDate(column, ...args);
|
|
3474
|
+
}
|
|
3475
|
+
whereTime(column, ...args) {
|
|
3476
|
+
return super.whereTime(column, ...args);
|
|
3477
|
+
}
|
|
3478
|
+
orWhereTime(column, ...args) {
|
|
3479
|
+
return super.orWhereTime(column, ...args);
|
|
3480
|
+
}
|
|
3481
|
+
whereDay(column, ...args) {
|
|
3482
|
+
return super.whereDay(column, ...args);
|
|
3483
|
+
}
|
|
3484
|
+
orWhereDay(column, ...args) {
|
|
3485
|
+
return super.orWhereDay(column, ...args);
|
|
3486
|
+
}
|
|
3487
|
+
whereMonth(column, ...args) {
|
|
3488
|
+
return super.whereMonth(column, ...args);
|
|
3489
|
+
}
|
|
3490
|
+
orWhereMonth(column, ...args) {
|
|
3491
|
+
return super.orWhereMonth(column, ...args);
|
|
3492
|
+
}
|
|
3493
|
+
whereYear(column, ...args) {
|
|
3494
|
+
return super.whereYear(column, ...args);
|
|
3495
|
+
}
|
|
3496
|
+
orWhereYear(column, ...args) {
|
|
3497
|
+
return super.orWhereYear(column, ...args);
|
|
3498
|
+
}
|
|
2940
3499
|
whereLike(column, value, caseSensitive = false, boolean = "and", not = false) {
|
|
2941
3500
|
return super.whereLike(column, value, caseSensitive, boolean, not);
|
|
2942
3501
|
}
|
|
@@ -2972,11 +3531,25 @@ var Builder2 = class extends Builder {
|
|
|
2972
3531
|
return super.where(this.model.getQualifiedKeyName(), "!=", id);
|
|
2973
3532
|
}
|
|
2974
3533
|
// ---------------------------------------------------------------- reading
|
|
3534
|
+
/** The models, in the model's collection (an EloquentCollection). */
|
|
3535
|
+
async get() {
|
|
3536
|
+
return await super.get();
|
|
3537
|
+
}
|
|
3538
|
+
newCollection(models) {
|
|
3539
|
+
return this.model.newCollection(models);
|
|
3540
|
+
}
|
|
3541
|
+
/** chunk() with each chunk in the model's collection. */
|
|
3542
|
+
chunk(count, callback) {
|
|
3543
|
+
return super.chunk(count, callback);
|
|
3544
|
+
}
|
|
3545
|
+
chunkById(count, callback, column, alias) {
|
|
3546
|
+
return super.chunkById(count, callback, column, alias);
|
|
3547
|
+
}
|
|
2975
3548
|
/** Runs the query, hydrates models, fires their retrieved events and eager loads the with() relations. */
|
|
2976
3549
|
async runSelect() {
|
|
2977
3550
|
const query = this.applyScopes();
|
|
2978
3551
|
const rows = await Builder.prototype.runSelect.call(query);
|
|
2979
|
-
const models =
|
|
3552
|
+
const models = query.hydrate(rows);
|
|
2980
3553
|
if (models.length && this.model.hasModelListeners("retrieved")) {
|
|
2981
3554
|
for (const model of models) await model.fireModelEvent("retrieved", false);
|
|
2982
3555
|
}
|
|
@@ -3057,17 +3630,66 @@ var Builder2 = class extends Builder {
|
|
|
3057
3630
|
* withCount('comments as approved_count'). Global scopes of the related model (soft deletes) apply.
|
|
3058
3631
|
*/
|
|
3059
3632
|
withCount(...relations) {
|
|
3633
|
+
return this.withAggregate(relations, "*", "count");
|
|
3634
|
+
}
|
|
3635
|
+
/** Adds `<relation>_sum_<column>`: withSum('orders', 'price'), withSum({ 'orders as paid': (q) => … }, 'price'). */
|
|
3636
|
+
withSum(relations, column) {
|
|
3637
|
+
return this.withAggregate(relations, column, "sum");
|
|
3638
|
+
}
|
|
3639
|
+
/** Adds `<relation>_avg_<column>`. */
|
|
3640
|
+
withAvg(relations, column) {
|
|
3641
|
+
return this.withAggregate(relations, column, "avg");
|
|
3642
|
+
}
|
|
3643
|
+
/** Adds `<relation>_min_<column>`. */
|
|
3644
|
+
withMin(relations, column) {
|
|
3645
|
+
return this.withAggregate(relations, column, "min");
|
|
3646
|
+
}
|
|
3647
|
+
/** Adds `<relation>_max_<column>`. */
|
|
3648
|
+
withMax(relations, column) {
|
|
3649
|
+
return this.withAggregate(relations, column, "max");
|
|
3650
|
+
}
|
|
3651
|
+
/** Adds a boolean `<relation>_exists`: withExists('comments'). */
|
|
3652
|
+
withExists(...relations) {
|
|
3653
|
+
return this.withAggregate(relations, "*", "exists");
|
|
3654
|
+
}
|
|
3655
|
+
/**
|
|
3656
|
+
* Laravel's withAggregate(): a correlated subquery per relation, `select <fn>(<related column>) … as <alias>`, the
|
|
3657
|
+
* alias being `<relation>_<fn>_<column>` unless the relation is named `'orders as alias'`. The relation's
|
|
3658
|
+
* constraint and the related model's global scopes apply; orderings are dropped. 'exists' selects
|
|
3659
|
+
* `exists (…)`, cast to a boolean. Without a function the column's first value is selected.
|
|
3660
|
+
*/
|
|
3661
|
+
withAggregate(relations, column, fn) {
|
|
3662
|
+
const specs = this.normalizeRelationSpecs([relations].flat());
|
|
3663
|
+
if (!specs.length) return this;
|
|
3060
3664
|
if (!this.columns.length) this.columns = [`${this.model.getTable()}.*`];
|
|
3061
|
-
for (const [spec, constraint] of
|
|
3062
|
-
const [
|
|
3063
|
-
const
|
|
3064
|
-
const
|
|
3665
|
+
for (const [spec, constraint] of specs) {
|
|
3666
|
+
const [rawName = "", as] = spec.split(/\s+as\s+/i);
|
|
3667
|
+
const name = rawName.trim();
|
|
3668
|
+
const relation = this.getRelation(name);
|
|
3669
|
+
const target = column instanceof Expression ? column : new Expression(column === "*" ? "*" : this.connection.compile(this.grammar.wrap(relation.getRelated().qualifyColumn(column))).sql);
|
|
3670
|
+
const expression = fn && fn !== "exists" ? new Expression(`${fn}(${target.value})`, target.bindings) : target;
|
|
3671
|
+
const query = relation.getRelationExistenceQuery(relation.getRelated().newQueryWithoutRelationships(), this, [expression]);
|
|
3065
3672
|
query.wheres.push(...relation.wheres);
|
|
3066
3673
|
if (constraint) query.callScope((q) => constraint(q));
|
|
3067
|
-
|
|
3674
|
+
const scoped = query.applyScopes();
|
|
3675
|
+
scoped.orders = [];
|
|
3676
|
+
if (scoped.columns.length > 1) scoped.columns = [scoped.columns[0]];
|
|
3677
|
+
const columnName = (column instanceof Expression ? column.value : column).toLowerCase();
|
|
3678
|
+
const alias = as?.trim() ?? Str2.snake(`${name} ${fn ?? ""} ${columnName}`.replace(/[^\p{L}\p{N}\s_]/gu, ""));
|
|
3679
|
+
if (fn === "exists") {
|
|
3680
|
+
this.columns.push({ query: scoped, as: alias, exists: true });
|
|
3681
|
+
this.withCasts({ [alias]: "bool" });
|
|
3682
|
+
} else {
|
|
3683
|
+
this.selectSub(fn ? scoped : scoped.limit(1), alias);
|
|
3684
|
+
}
|
|
3068
3685
|
}
|
|
3069
3686
|
return this;
|
|
3070
3687
|
}
|
|
3688
|
+
/** Casts for selected columns, as if the model declared them: withCasts({ orders_sum_price: 'float' }). */
|
|
3689
|
+
withCasts(casts) {
|
|
3690
|
+
this.selectCasts = { ...this.selectCasts, ...casts };
|
|
3691
|
+
return this;
|
|
3692
|
+
}
|
|
3071
3693
|
/**
|
|
3072
3694
|
* Rows that have related rows: has('comments'), has('comments', '>=', 3), has('comments.author').
|
|
3073
3695
|
* Uses `exists (…)` for the common "at least one"/"none" cases and a count subquery otherwise.
|
|
@@ -3123,7 +3745,11 @@ var Builder2 = class extends Builder {
|
|
|
3123
3745
|
}
|
|
3124
3746
|
/** Models from raw rows, marked as existing. */
|
|
3125
3747
|
hydrate(rows) {
|
|
3126
|
-
|
|
3748
|
+
const casts = Object.keys(this.selectCasts).length ? this.selectCasts : void 0;
|
|
3749
|
+
return rows.map((row) => {
|
|
3750
|
+
const model = this.model.newFromBuilder(row);
|
|
3751
|
+
return casts ? model.mergeCasts(casts) : model;
|
|
3752
|
+
});
|
|
3127
3753
|
}
|
|
3128
3754
|
async aggregate(fn, column) {
|
|
3129
3755
|
return Builder.prototype.aggregate.call(this.applyScopes(), fn, column);
|
|
@@ -3149,7 +3775,7 @@ var Builder2 = class extends Builder {
|
|
|
3149
3775
|
}
|
|
3150
3776
|
async findMany(ids) {
|
|
3151
3777
|
const keys = ids.filter((id) => !this.isMalformedKey(id));
|
|
3152
|
-
if (!keys.length) return
|
|
3778
|
+
if (!keys.length) return this.model.newCollection([]);
|
|
3153
3779
|
return this.clone().whereKey(keys).get();
|
|
3154
3780
|
}
|
|
3155
3781
|
async findOrFail(id) {
|
|
@@ -3272,6 +3898,7 @@ var Builder2 = class extends Builder {
|
|
|
3272
3898
|
copy.scopes = new Map(this.scopes);
|
|
3273
3899
|
copy.removedScopes = [...this.removedScopes];
|
|
3274
3900
|
copy.eagerLoad = new Map(this.eagerLoad);
|
|
3901
|
+
copy.selectCasts = { ...this.selectCasts };
|
|
3275
3902
|
return new Proxy(copy, handler);
|
|
3276
3903
|
}
|
|
3277
3904
|
/** Nested where groups get a builder of the same model (without global scopes), so local scopes work inside them. */
|
|
@@ -3296,6 +3923,7 @@ import { Collection as Collection5 } from "@orieljs/collections";
|
|
|
3296
3923
|
var JSON_CASTS = /* @__PURE__ */ new Set(["array", "json", "object", "collection"]);
|
|
3297
3924
|
var DATE_CASTS = /* @__PURE__ */ new Set(["date", "datetime", "immutable_date", "immutable_datetime"]);
|
|
3298
3925
|
var PRIMITIVE_CASTS = /* @__PURE__ */ new Set(["int", "integer", "float", "double", "real", "string", "bool", "boolean", "timestamp"]);
|
|
3926
|
+
var HASHED_CAST = "hashed";
|
|
3299
3927
|
var isCustom = (cast) => typeof cast === "object" && typeof cast.get === "function" && typeof cast.set === "function";
|
|
3300
3928
|
var isCustomClass = (cast) => typeof cast === "function";
|
|
3301
3929
|
var isEnum = (cast) => typeof cast === "object" && !isCustom(cast);
|
|
@@ -3311,8 +3939,9 @@ function enumValues(cast) {
|
|
|
3311
3939
|
}
|
|
3312
3940
|
var isJsonCast = (cast) => typeof cast === "string" && JSON_CASTS.has(cast);
|
|
3313
3941
|
var isDateCast = (cast) => typeof cast === "string" && DATE_CASTS.has(cast);
|
|
3942
|
+
var isHashedCast = (cast) => cast === HASHED_CAST;
|
|
3314
3943
|
var decimalPlaces = (cast) => cast.startsWith("decimal:") ? Number(cast.slice(8)) : void 0;
|
|
3315
|
-
var isBuiltInCast = (cast) => JSON_CASTS.has(cast) || DATE_CASTS.has(cast) || PRIMITIVE_CASTS.has(cast) || /^decimal:\d+$/.test(cast);
|
|
3944
|
+
var isBuiltInCast = (cast) => JSON_CASTS.has(cast) || DATE_CASTS.has(cast) || PRIMITIVE_CASTS.has(cast) || cast === HASHED_CAST || /^decimal:\d+$/.test(cast);
|
|
3316
3945
|
function assertBuiltInCast(cast, key, className) {
|
|
3317
3946
|
if (!isBuiltInCast(cast)) throw new InvalidCastError(className, key, cast);
|
|
3318
3947
|
}
|
|
@@ -3401,11 +4030,206 @@ function isEquivalent(cast, current, original, model, key, className) {
|
|
|
3401
4030
|
return numeric(current) && numeric(original) && Number(current) === Number(original);
|
|
3402
4031
|
}
|
|
3403
4032
|
|
|
4033
|
+
// Eloquent/Collection.ts
|
|
4034
|
+
import { Collection as Collection6 } from "@orieljs/collections";
|
|
4035
|
+
var dictionaryKey = (key) => String(key);
|
|
4036
|
+
var isModel = (value) => typeof value === "object" && value !== null && typeof value.getKey === "function" && typeof value.relationLoaded === "function";
|
|
4037
|
+
function uniqueByKey(models) {
|
|
4038
|
+
return [...new Map(models.map((model) => [dictionaryKey(model.getKey()), model])).values()];
|
|
4039
|
+
}
|
|
4040
|
+
function relatedModels(value) {
|
|
4041
|
+
if (value instanceof Collection6) return value.all().filter(isModel);
|
|
4042
|
+
return isModel(value) ? [value] : [];
|
|
4043
|
+
}
|
|
4044
|
+
var EloquentCollection = class extends Collection6 {
|
|
4045
|
+
find(key, defaultValue) {
|
|
4046
|
+
const value = isModel(key) ? key.getKey() : key instanceof Collection6 ? key.all() : key;
|
|
4047
|
+
if (Array.isArray(value)) {
|
|
4048
|
+
const wanted = new Set(value.map(dictionaryKey));
|
|
4049
|
+
return this.filter((model) => wanted.has(dictionaryKey(model.getKey())));
|
|
4050
|
+
}
|
|
4051
|
+
return this.first((model) => dictionaryKey(model.getKey()) === dictionaryKey(value), defaultValue);
|
|
4052
|
+
}
|
|
4053
|
+
findOrFail(key) {
|
|
4054
|
+
const value = key instanceof Collection6 ? key.all() : key;
|
|
4055
|
+
if (Array.isArray(value)) {
|
|
4056
|
+
const found = this.find(value);
|
|
4057
|
+
const keys = [...new Map(value.map((id) => [dictionaryKey(id), id])).values()];
|
|
4058
|
+
if (found.count() === keys.length) return found;
|
|
4059
|
+
const present2 = new Set(found.modelKeys().map(dictionaryKey));
|
|
4060
|
+
throw new ModelNotFoundError(this.first()?.constructor.name ?? "Model", keys.filter((id) => !present2.has(dictionaryKey(id))));
|
|
4061
|
+
}
|
|
4062
|
+
const model = this.find(value);
|
|
4063
|
+
if (model !== void 0) return model;
|
|
4064
|
+
throw new ModelNotFoundError(this.first()?.constructor.name ?? "Model", [isModel(value) ? value.getKey() : value]);
|
|
4065
|
+
}
|
|
4066
|
+
/** The primary keys, in order. */
|
|
4067
|
+
modelKeys() {
|
|
4068
|
+
return this.items.map((model) => model.getKey());
|
|
4069
|
+
}
|
|
4070
|
+
/** The models keyed by their primary key (as text). */
|
|
4071
|
+
getDictionary(items = this.items) {
|
|
4072
|
+
const dictionary = {};
|
|
4073
|
+
for (const model of items) dictionary[dictionaryKey(model.getKey())] = model;
|
|
4074
|
+
return dictionary;
|
|
4075
|
+
}
|
|
4076
|
+
/** The same models in a plain Collection. */
|
|
4077
|
+
toBase() {
|
|
4078
|
+
return new Collection6(this.items);
|
|
4079
|
+
}
|
|
4080
|
+
contains(...args) {
|
|
4081
|
+
if (args.length > 1 || typeof args[0] === "function") return Reflect.apply(Collection6.prototype.contains, this, args);
|
|
4082
|
+
const [key] = args;
|
|
4083
|
+
if (isModel(key)) return this.items.some((model) => model.is(key));
|
|
4084
|
+
return this.items.some((model) => dictionaryKey(model.getKey()) === dictionaryKey(key));
|
|
4085
|
+
}
|
|
4086
|
+
containsStrict(...args) {
|
|
4087
|
+
return Reflect.apply(Collection6.prototype.contains, this, args);
|
|
4088
|
+
}
|
|
4089
|
+
doesntContainStrict(...args) {
|
|
4090
|
+
return !Reflect.apply(Collection6.prototype.contains, this, args);
|
|
4091
|
+
}
|
|
4092
|
+
/** Eager loads relations onto every model, one query per relation: await posts.load('author', 'comments.author'). */
|
|
4093
|
+
async load(...relations) {
|
|
4094
|
+
const first = this.first();
|
|
4095
|
+
if (!first || !relations.length) return this;
|
|
4096
|
+
await first.newQueryWithoutRelationships().with(...relations).eagerLoadRelations(this.items);
|
|
4097
|
+
return this;
|
|
4098
|
+
}
|
|
4099
|
+
/** Loads only the relations that aren't loaded yet; nested paths are followed into the loaded relations. */
|
|
4100
|
+
async loadMissing(...relations) {
|
|
4101
|
+
await loadMissingOn(this.items, relations);
|
|
4102
|
+
return this;
|
|
4103
|
+
}
|
|
4104
|
+
/** Adds <relation>_count attributes to every model with one query: await posts.loadCount('comments'). */
|
|
4105
|
+
loadCount(...relations) {
|
|
4106
|
+
return this.loadAggregate(relations, "*", "count");
|
|
4107
|
+
}
|
|
4108
|
+
/**
|
|
4109
|
+
* Laravel's loadAggregate(): withAggregate() for models already loaded, with one query for the whole collection.
|
|
4110
|
+
* The values become clean attributes (with their casts: loadExists() gives booleans).
|
|
4111
|
+
*/
|
|
4112
|
+
async loadAggregate(relations, column, fn) {
|
|
4113
|
+
const first = this.first();
|
|
4114
|
+
if (!first || ![relations].flat().length) return this;
|
|
4115
|
+
const keyName = first.getKeyName();
|
|
4116
|
+
const rows = await first.newModelQuery().whereKey(this.modelKeys()).select(keyName).withAggregate(relations, column, fn).get();
|
|
4117
|
+
const byKey = new Map(rows.all().map((row) => [dictionaryKey(row.getKey()), row]));
|
|
4118
|
+
for (const model of this.items) {
|
|
4119
|
+
const row = byKey.get(dictionaryKey(model.getKey()));
|
|
4120
|
+
if (!row) continue;
|
|
4121
|
+
const values = Object.fromEntries(Object.entries(row.getAttributes()).filter(([name]) => name !== keyName));
|
|
4122
|
+
const casts = Object.fromEntries(Object.entries(row.getCasts()).filter(([name]) => Object.hasOwn(values, name)));
|
|
4123
|
+
model.forceFill(values).syncOriginalAttributes(...Object.keys(values)).mergeCasts(casts);
|
|
4124
|
+
}
|
|
4125
|
+
return this;
|
|
4126
|
+
}
|
|
4127
|
+
/** Adds <relation>_sum_<column> to every model: await users.loadSum('orders', 'price'). */
|
|
4128
|
+
loadSum(relations, column) {
|
|
4129
|
+
return this.loadAggregate(relations, column, "sum");
|
|
4130
|
+
}
|
|
4131
|
+
loadAvg(relations, column) {
|
|
4132
|
+
return this.loadAggregate(relations, column, "avg");
|
|
4133
|
+
}
|
|
4134
|
+
loadMin(relations, column) {
|
|
4135
|
+
return this.loadAggregate(relations, column, "min");
|
|
4136
|
+
}
|
|
4137
|
+
loadMax(relations, column) {
|
|
4138
|
+
return this.loadAggregate(relations, column, "max");
|
|
4139
|
+
}
|
|
4140
|
+
/** Adds a boolean <relation>_exists to every model. */
|
|
4141
|
+
loadExists(...relations) {
|
|
4142
|
+
return this.loadAggregate(relations, "*", "exists");
|
|
4143
|
+
}
|
|
4144
|
+
/** The models as they are in the database now (without global scopes), with relations loaded; deleted ones drop out. */
|
|
4145
|
+
async fresh(...relations) {
|
|
4146
|
+
const first = this.first();
|
|
4147
|
+
if (!first) return this.newInstance();
|
|
4148
|
+
const fresh = this.getDictionary(await first.newQueryWithoutScopes().with(...relations).whereKey(this.modelKeys()).get());
|
|
4149
|
+
const models = [];
|
|
4150
|
+
for (const model of this.items) {
|
|
4151
|
+
const found = model.exists ? fresh[dictionaryKey(model.getKey())] : void 0;
|
|
4152
|
+
if (found) models.push(found);
|
|
4153
|
+
}
|
|
4154
|
+
return this.newInstance(models);
|
|
4155
|
+
}
|
|
4156
|
+
/** The models whose keys aren't in the given models. */
|
|
4157
|
+
diff(items) {
|
|
4158
|
+
const other = this.getDictionary(items);
|
|
4159
|
+
return this.filter((model) => !Object.hasOwn(other, dictionaryKey(model.getKey())));
|
|
4160
|
+
}
|
|
4161
|
+
/** The models whose keys are also in the given models. */
|
|
4162
|
+
intersect(items) {
|
|
4163
|
+
const other = this.getDictionary(items);
|
|
4164
|
+
return this.filter((model) => Object.hasOwn(other, dictionaryKey(model.getKey())));
|
|
4165
|
+
}
|
|
4166
|
+
/** One model per key (the last instance, at the first one's place); with a key or callback, Collection's unique(). */
|
|
4167
|
+
unique(key) {
|
|
4168
|
+
if (key !== void 0) return super.unique(key);
|
|
4169
|
+
return this.newInstance(uniqueByKey(this.items));
|
|
4170
|
+
}
|
|
4171
|
+
/** The models with these keys, in the collection's order. */
|
|
4172
|
+
only(...keys) {
|
|
4173
|
+
const wanted = new Set(keys.flat().map(dictionaryKey));
|
|
4174
|
+
return this.newInstance(uniqueByKey(this.items).filter((model) => wanted.has(dictionaryKey(model.getKey()))));
|
|
4175
|
+
}
|
|
4176
|
+
/** The models without these keys, in the collection's order. */
|
|
4177
|
+
except(...keys) {
|
|
4178
|
+
const unwanted = new Set(keys.flat().map(dictionaryKey));
|
|
4179
|
+
return this.newInstance(uniqueByKey(this.items).filter((model) => !unwanted.has(dictionaryKey(model.getKey()))));
|
|
4180
|
+
}
|
|
4181
|
+
/** Adds the given models, replacing the ones with the same key. */
|
|
4182
|
+
merge(items) {
|
|
4183
|
+
const dictionary = new Map(this.items.map((model) => [dictionaryKey(model.getKey()), model]));
|
|
4184
|
+
for (const model of items) dictionary.set(dictionaryKey(model.getKey()), model);
|
|
4185
|
+
return this.newInstance(dictionary.values());
|
|
4186
|
+
}
|
|
4187
|
+
makeHidden(...attributes) {
|
|
4188
|
+
for (const model of this.items) model.makeHidden(...attributes);
|
|
4189
|
+
return this;
|
|
4190
|
+
}
|
|
4191
|
+
makeVisible(...attributes) {
|
|
4192
|
+
for (const model of this.items) model.makeVisible(...attributes);
|
|
4193
|
+
return this;
|
|
4194
|
+
}
|
|
4195
|
+
setVisible(visible) {
|
|
4196
|
+
for (const model of this.items) model.setVisible(visible);
|
|
4197
|
+
return this;
|
|
4198
|
+
}
|
|
4199
|
+
setHidden(hidden) {
|
|
4200
|
+
for (const model of this.items) model.setHidden(hidden);
|
|
4201
|
+
return this;
|
|
4202
|
+
}
|
|
4203
|
+
append(...attributes) {
|
|
4204
|
+
for (const model of this.items) model.append(...attributes);
|
|
4205
|
+
return this;
|
|
4206
|
+
}
|
|
4207
|
+
/** A query of exactly these models (where key in …), for mass updates: await posts.toQuery().update({ … }). */
|
|
4208
|
+
toQuery() {
|
|
4209
|
+
const first = this.first();
|
|
4210
|
+
if (!first) throw new LogicError("Unable to create query for empty collection.");
|
|
4211
|
+
if (this.items.some((model) => model.constructor !== first.constructor)) {
|
|
4212
|
+
throw new LogicError("Unable to create query for collection with mixed types.");
|
|
4213
|
+
}
|
|
4214
|
+
return first.newModelQuery().whereKey(this.modelKeys());
|
|
4215
|
+
}
|
|
4216
|
+
};
|
|
4217
|
+
async function loadMissingOn(models, paths) {
|
|
4218
|
+
for (const path of paths) {
|
|
4219
|
+
const [head = "", ...rest] = path.split(".");
|
|
4220
|
+
const missing = models.filter((model) => !model.relationLoaded(head));
|
|
4221
|
+
if (missing.length) await missing[0].newQueryWithoutRelationships().with(path).eagerLoadRelations(missing);
|
|
4222
|
+
if (!rest.length) continue;
|
|
4223
|
+
const related = models.flatMap((model) => relatedModels(model.getRelations()[head]));
|
|
4224
|
+
if (related.length) await loadMissingOn(related, [rest.join(".")]);
|
|
4225
|
+
}
|
|
4226
|
+
}
|
|
4227
|
+
|
|
3404
4228
|
// Eloquent/Factories/Factory.ts
|
|
3405
4229
|
import { existsSync, readdirSync } from "fs";
|
|
3406
|
-
import { join as
|
|
4230
|
+
import { join as join4 } from "path";
|
|
3407
4231
|
import { pathToFileURL } from "url";
|
|
3408
|
-
import { Collection as
|
|
4232
|
+
import { Collection as Collection9 } from "@orieljs/collections";
|
|
3409
4233
|
import { Str as Str5 } from "@orieljs/support";
|
|
3410
4234
|
|
|
3411
4235
|
// Eloquent/Relations/BelongsTo.ts
|
|
@@ -3571,7 +4395,7 @@ var BelongsTo = class extends Relation {
|
|
|
3571
4395
|
};
|
|
3572
4396
|
|
|
3573
4397
|
// Eloquent/Relations/BelongsToMany.ts
|
|
3574
|
-
import { Collection as
|
|
4398
|
+
import { Collection as Collection7 } from "@orieljs/collections";
|
|
3575
4399
|
var BelongsToMany = class extends Relation {
|
|
3576
4400
|
constructor(related, parent, table, foreignPivotKey, relatedPivotKey, parentKey, relatedKey) {
|
|
3577
4401
|
super(related, parent);
|
|
@@ -3639,10 +4463,10 @@ var BelongsToMany = class extends Relation {
|
|
|
3639
4463
|
}
|
|
3640
4464
|
async getResults() {
|
|
3641
4465
|
const key = this.getParentKey();
|
|
3642
|
-
return key === null || key === void 0 ?
|
|
4466
|
+
return key === null || key === void 0 ? this.getRelated().newCollection() : this.get();
|
|
3643
4467
|
}
|
|
3644
4468
|
initRelation(models, relation) {
|
|
3645
|
-
for (const model of models) model.setRelation(relation,
|
|
4469
|
+
for (const model of models) model.setRelation(relation, this.getRelated().newCollection());
|
|
3646
4470
|
return models;
|
|
3647
4471
|
}
|
|
3648
4472
|
match(models, results, relation) {
|
|
@@ -3653,7 +4477,7 @@ var BelongsToMany = class extends Relation {
|
|
|
3653
4477
|
if (group) group.push(result);
|
|
3654
4478
|
else dictionary.set(key, [result]);
|
|
3655
4479
|
}
|
|
3656
|
-
for (const model of models) model.setRelation(relation,
|
|
4480
|
+
for (const model of models) model.setRelation(relation, this.getRelated().newCollection(dictionary.get(String(model.getAttribute(this.parentKey))) ?? []));
|
|
3657
4481
|
return models;
|
|
3658
4482
|
}
|
|
3659
4483
|
getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
|
|
@@ -3669,9 +4493,9 @@ var BelongsToMany = class extends Relation {
|
|
|
3669
4493
|
async detach(ids) {
|
|
3670
4494
|
const query = this.newPivotQuery().where(this.foreignPivotKey, "=", this.getParentKey());
|
|
3671
4495
|
if (ids !== void 0) {
|
|
3672
|
-
const
|
|
3673
|
-
if (!
|
|
3674
|
-
query.whereIn(this.relatedPivotKey,
|
|
4496
|
+
const list3 = [...this.parseIds(ids).keys()];
|
|
4497
|
+
if (!list3.length) return 0;
|
|
4498
|
+
query.whereIn(this.relatedPivotKey, list3);
|
|
3675
4499
|
}
|
|
3676
4500
|
return query.delete();
|
|
3677
4501
|
}
|
|
@@ -3775,7 +4599,7 @@ var BelongsToMany = class extends Relation {
|
|
|
3775
4599
|
/** ids → Map(id → extra pivot attributes). Models become their related key. */
|
|
3776
4600
|
parseIds(ids) {
|
|
3777
4601
|
const parsed = /* @__PURE__ */ new Map();
|
|
3778
|
-
if (ids instanceof
|
|
4602
|
+
if (ids instanceof Collection7) ids = ids.all();
|
|
3779
4603
|
if (Array.isArray(ids)) {
|
|
3780
4604
|
for (const id of ids) parsed.set(this.idOf(id), {});
|
|
3781
4605
|
} else if (ids !== null && typeof ids === "object" && !this.isModel(ids)) {
|
|
@@ -3946,7 +4770,7 @@ var HasOneOrMany = class extends Relation {
|
|
|
3946
4770
|
};
|
|
3947
4771
|
|
|
3948
4772
|
// Eloquent/Relations/MorphTo.ts
|
|
3949
|
-
import { Collection as
|
|
4773
|
+
import { Collection as Collection8 } from "@orieljs/collections";
|
|
3950
4774
|
var MorphTo = class extends BelongsTo {
|
|
3951
4775
|
/**
|
|
3952
4776
|
* @param related an instance of the current type's class (the child's own class when the type is empty)
|
|
@@ -4008,7 +4832,7 @@ var MorphTo = class extends BelongsTo {
|
|
|
4008
4832
|
results.push(result);
|
|
4009
4833
|
}
|
|
4010
4834
|
}
|
|
4011
|
-
return new
|
|
4835
|
+
return new Collection8(results);
|
|
4012
4836
|
}
|
|
4013
4837
|
match(models, results, relation) {
|
|
4014
4838
|
for (const result of results) {
|
|
@@ -4124,10 +4948,10 @@ var Factory = class _Factory {
|
|
|
4124
4948
|
}
|
|
4125
4949
|
/** One model per record (or `count` models). */
|
|
4126
4950
|
async createMany(records) {
|
|
4127
|
-
const
|
|
4951
|
+
const list3 = typeof records === "number" ? Array.from({ length: records }, () => ({})) : records;
|
|
4128
4952
|
const created = [];
|
|
4129
|
-
for (const record of
|
|
4130
|
-
return new
|
|
4953
|
+
for (const record of list3) created.push(await this.createOne(record));
|
|
4954
|
+
return new Collection9(created);
|
|
4131
4955
|
}
|
|
4132
4956
|
newInstance(changes) {
|
|
4133
4957
|
const copy = Object.create(Object.getPrototypeOf(this));
|
|
@@ -4173,7 +4997,7 @@ var Factory = class _Factory {
|
|
|
4173
4997
|
const relation = this.relationOn(model, relationship);
|
|
4174
4998
|
if (relation instanceof BelongsToMany) {
|
|
4175
4999
|
const related = await factory.create();
|
|
4176
|
-
await relation.attach(related instanceof
|
|
5000
|
+
await relation.attach(related instanceof Collection9 ? related.all() : related, pivot);
|
|
4177
5001
|
} else if (relation instanceof HasOneOrMany) {
|
|
4178
5002
|
const foreign = { [relation.getForeignKeyName()]: relation.getParentKey() };
|
|
4179
5003
|
if (relation.morph) foreign[relation.getMorphType()] = relation.getMorphClass();
|
|
@@ -4187,14 +5011,14 @@ var Factory = class _Factory {
|
|
|
4187
5011
|
return model.getRelationInstance(relationship);
|
|
4188
5012
|
}
|
|
4189
5013
|
result(models) {
|
|
4190
|
-
return this.countValue === void 0 ? models[0] : new
|
|
5014
|
+
return this.countValue === void 0 ? models[0] : new Collection9(models);
|
|
4191
5015
|
}
|
|
4192
5016
|
};
|
|
4193
5017
|
async function discoverFactories(path) {
|
|
4194
5018
|
if (!existsSync(path)) return;
|
|
4195
5019
|
for (const file of readdirSync(path).sort()) {
|
|
4196
5020
|
if (!/\.(ts|js|mts|mjs)$/.test(file) || /\.d\.[mc]?ts$/.test(file)) continue;
|
|
4197
|
-
const module = await import(pathToFileURL(
|
|
5021
|
+
const module = await import(pathToFileURL(join4(path, file)).href);
|
|
4198
5022
|
for (const exported of Object.values(module)) {
|
|
4199
5023
|
if (typeof exported === "function" && exported.prototype instanceof Factory) {
|
|
4200
5024
|
Factory.register(exported);
|
|
@@ -4245,28 +5069,26 @@ function modelEventsMuted() {
|
|
|
4245
5069
|
}
|
|
4246
5070
|
|
|
4247
5071
|
// Eloquent/Relations/HasMany.ts
|
|
4248
|
-
import { Collection as Collection9 } from "@orieljs/collections";
|
|
4249
5072
|
var HasMany = class extends HasOneOrMany {
|
|
4250
5073
|
async getResults() {
|
|
4251
5074
|
const key = this.getParentKey();
|
|
4252
|
-
return key === null || key === void 0 ?
|
|
5075
|
+
return key === null || key === void 0 ? this.getRelated().newCollection() : this.get();
|
|
4253
5076
|
}
|
|
4254
5077
|
initRelation(models, relation) {
|
|
4255
|
-
for (const model of models) model.setRelation(relation,
|
|
5078
|
+
for (const model of models) model.setRelation(relation, this.getRelated().newCollection());
|
|
4256
5079
|
return models;
|
|
4257
5080
|
}
|
|
4258
5081
|
match(models, results, relation) {
|
|
4259
5082
|
const dictionary = this.buildDictionary(results);
|
|
4260
5083
|
for (const model of models) {
|
|
4261
5084
|
const children = this.applyInverseRelationToMany(dictionary.get(String(model.getAttribute(this.localKey))) ?? [], model);
|
|
4262
|
-
model.setRelation(relation,
|
|
5085
|
+
model.setRelation(relation, this.getRelated().newCollection(children));
|
|
4263
5086
|
}
|
|
4264
5087
|
return models;
|
|
4265
5088
|
}
|
|
4266
5089
|
};
|
|
4267
5090
|
|
|
4268
5091
|
// Eloquent/Relations/HasManyThrough.ts
|
|
4269
|
-
import { Collection as Collection10 } from "@orieljs/collections";
|
|
4270
5092
|
var THROUGH_KEY = "laravel_through_key";
|
|
4271
5093
|
var HasManyThrough = class extends Relation {
|
|
4272
5094
|
/**
|
|
@@ -4332,13 +5154,13 @@ var HasManyThrough = class extends Relation {
|
|
|
4332
5154
|
}
|
|
4333
5155
|
async getResults() {
|
|
4334
5156
|
const key = this.parent.getAttribute(this.localKey);
|
|
4335
|
-
return key === null || key === void 0 ?
|
|
5157
|
+
return key === null || key === void 0 ? this.getRelated().newCollection() : this.get();
|
|
4336
5158
|
}
|
|
4337
5159
|
async getEager() {
|
|
4338
5160
|
return this.get();
|
|
4339
5161
|
}
|
|
4340
5162
|
initRelation(models, relation) {
|
|
4341
|
-
for (const model of models) model.setRelation(relation,
|
|
5163
|
+
for (const model of models) model.setRelation(relation, this.getRelated().newCollection());
|
|
4342
5164
|
return models;
|
|
4343
5165
|
}
|
|
4344
5166
|
match(models, results, relation) {
|
|
@@ -4349,7 +5171,7 @@ var HasManyThrough = class extends Relation {
|
|
|
4349
5171
|
if (group) group.push(result);
|
|
4350
5172
|
else dictionary.set(key, [result]);
|
|
4351
5173
|
}
|
|
4352
|
-
for (const model of models) model.setRelation(relation,
|
|
5174
|
+
for (const model of models) model.setRelation(relation, this.getRelated().newCollection(dictionary.get(String(model.getAttribute(this.localKey))) ?? []));
|
|
4353
5175
|
return models;
|
|
4354
5176
|
}
|
|
4355
5177
|
getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
|
|
@@ -4400,7 +5222,13 @@ var MorphOne = class extends HasOne {
|
|
|
4400
5222
|
// Eloquent/Model.ts
|
|
4401
5223
|
var handler2 = {
|
|
4402
5224
|
get(target, key, receiver) {
|
|
4403
|
-
if (typeof key === "symbol" || key in target)
|
|
5225
|
+
if (typeof key === "symbol" || key in target) {
|
|
5226
|
+
const value = Reflect.get(target, key, receiver);
|
|
5227
|
+
if (relationGuard.enabled && typeof key === "string" && typeof value === "function" && !(key in Model.prototype) && !Object.hasOwn(target, key)) {
|
|
5228
|
+
return guardedMethod(target.constructor, key, value);
|
|
5229
|
+
}
|
|
5230
|
+
return value;
|
|
5231
|
+
}
|
|
4404
5232
|
return receiver.getAttribute(key);
|
|
4405
5233
|
},
|
|
4406
5234
|
set(target, key, value, receiver) {
|
|
@@ -4409,6 +5237,35 @@ var handler2 = {
|
|
|
4409
5237
|
return true;
|
|
4410
5238
|
}
|
|
4411
5239
|
};
|
|
5240
|
+
var relationGuard = { enabled: true, warned: /* @__PURE__ */ new Set() };
|
|
5241
|
+
var guardedMethods = /* @__PURE__ */ new WeakMap();
|
|
5242
|
+
function guardedMethod(cls, key, method) {
|
|
5243
|
+
let byClass = guardedMethods.get(method);
|
|
5244
|
+
if (!byClass) guardedMethods.set(method, byClass = /* @__PURE__ */ new Map());
|
|
5245
|
+
let guarded = byClass.get(cls);
|
|
5246
|
+
if (!guarded) {
|
|
5247
|
+
guarded = new Proxy(method, {
|
|
5248
|
+
get(target, property, receiver) {
|
|
5249
|
+
if (typeof property === "string" && (property === "name" || property === "length" || !(property in target))) {
|
|
5250
|
+
warnRelationPropertyAccess(cls.name, key, property);
|
|
5251
|
+
}
|
|
5252
|
+
if (property === "bind") return (thisArg, ...args) => Function.prototype.bind.call(target, thisArg, ...args);
|
|
5253
|
+
if (property === "toString") return () => Function.prototype.toString.call(target);
|
|
5254
|
+
return Reflect.get(target, property, receiver);
|
|
5255
|
+
}
|
|
5256
|
+
});
|
|
5257
|
+
byClass.set(cls, guarded);
|
|
5258
|
+
}
|
|
5259
|
+
return guarded;
|
|
5260
|
+
}
|
|
5261
|
+
function warnRelationPropertyAccess(model, method, property) {
|
|
5262
|
+
const id = `${model}.${method}.${property}`;
|
|
5263
|
+
if (relationGuard.warned.has(id)) return;
|
|
5264
|
+
relationGuard.warned.add(id);
|
|
5265
|
+
console.warn(
|
|
5266
|
+
`[${model}] ${method} is a method, so ${method}.${property} reads the function, not an attribute of a related model. Read a loaded relation with getRelation('${method}') (after with('${method}') or load('${method}')), or query it with await ${method}().first().`
|
|
5267
|
+
);
|
|
5268
|
+
}
|
|
4412
5269
|
var bootedModels = /* @__PURE__ */ new Set();
|
|
4413
5270
|
var prototypes = /* @__PURE__ */ new Map();
|
|
4414
5271
|
var unguardedGlobally = { value: false };
|
|
@@ -4439,6 +5296,11 @@ function methodOf(model, name) {
|
|
|
4439
5296
|
const value = Reflect.get(Object.getPrototypeOf(model), name);
|
|
4440
5297
|
return typeof value === "function" ? value : void 0;
|
|
4441
5298
|
}
|
|
5299
|
+
function hasher() {
|
|
5300
|
+
const container = currentContainer3();
|
|
5301
|
+
if (!container?.bound(Hasher)) throw new LogicError("The hashed cast needs a Hasher: register HashingServiceProvider (or bind the Hasher contract).");
|
|
5302
|
+
return container.make(Hasher);
|
|
5303
|
+
}
|
|
4442
5304
|
var serializing = /* @__PURE__ */ new WeakSet();
|
|
4443
5305
|
function serializeDate(date) {
|
|
4444
5306
|
return date.toISOString().replace(/\.(\d{3})Z$/, ".$1000Z");
|
|
@@ -4484,6 +5346,8 @@ var Model = class _Model {
|
|
|
4484
5346
|
relations = {};
|
|
4485
5347
|
/** Decoded json/array/object/collection values, so in-place changes are seen by save(). */
|
|
4486
5348
|
castCache = /* @__PURE__ */ new Map();
|
|
5349
|
+
/** Attributes with the hashed cast that were assigned a value since the last save; save() hashes them. */
|
|
5350
|
+
pendingHashes = /* @__PURE__ */ new Set();
|
|
4487
5351
|
constructor() {
|
|
4488
5352
|
;
|
|
4489
5353
|
this.constructor.bootIfNotBooted();
|
|
@@ -4617,6 +5481,18 @@ var Model = class _Model {
|
|
|
4617
5481
|
}
|
|
4618
5482
|
}
|
|
4619
5483
|
}
|
|
5484
|
+
/**
|
|
5485
|
+
* Turns the relation guard on or off: while it is on, reading a property of a relation method as if it were the
|
|
5486
|
+
* related model (`post.author.name`) warns once with how to read the relation. DatabaseServiceProvider turns it on
|
|
5487
|
+
* outside production. Turning it on again forgets which warnings were given.
|
|
5488
|
+
*/
|
|
5489
|
+
static warnOnRelationPropertyAccess(enabled = true) {
|
|
5490
|
+
relationGuard.enabled = enabled;
|
|
5491
|
+
if (enabled) relationGuard.warned.clear();
|
|
5492
|
+
}
|
|
5493
|
+
static warnsOnRelationPropertyAccess() {
|
|
5494
|
+
return relationGuard.enabled;
|
|
5495
|
+
}
|
|
4620
5496
|
/** Runs fn with model events off, for this async context only. */
|
|
4621
5497
|
static withoutEvents(fn) {
|
|
4622
5498
|
return withoutModelEvents(fn);
|
|
@@ -4663,11 +5539,27 @@ var Model = class _Model {
|
|
|
4663
5539
|
static whereNotLike(column, value, caseSensitive = false) {
|
|
4664
5540
|
return this.query().whereNotLike(column, value, caseSensitive);
|
|
4665
5541
|
}
|
|
5542
|
+
/** Post.whereDate('published_at', '2026-01-05'), Post.whereDate('published_at', '<', new Date()). */
|
|
5543
|
+
static whereDate(column, ...args) {
|
|
5544
|
+
return this.query().whereDate(column, ...args);
|
|
5545
|
+
}
|
|
5546
|
+
static whereTime(column, ...args) {
|
|
5547
|
+
return this.query().whereTime(column, ...args);
|
|
5548
|
+
}
|
|
5549
|
+
static whereDay(column, ...args) {
|
|
5550
|
+
return this.query().whereDay(column, ...args);
|
|
5551
|
+
}
|
|
5552
|
+
static whereMonth(column, ...args) {
|
|
5553
|
+
return this.query().whereMonth(column, ...args);
|
|
5554
|
+
}
|
|
5555
|
+
static whereYear(column, ...args) {
|
|
5556
|
+
return this.query().whereYear(column, ...args);
|
|
5557
|
+
}
|
|
4666
5558
|
static whereColumn(first, operatorOrSecond, second) {
|
|
4667
5559
|
return this.query().whereColumn(first, operatorOrSecond, second);
|
|
4668
5560
|
}
|
|
4669
|
-
static whereRaw(
|
|
4670
|
-
return this.query().whereRaw(
|
|
5561
|
+
static whereRaw(sql8, bindings = []) {
|
|
5562
|
+
return this.query().whereRaw(sql8, bindings);
|
|
4671
5563
|
}
|
|
4672
5564
|
static select(...columns) {
|
|
4673
5565
|
return this.query().select(...columns);
|
|
@@ -4703,6 +5595,25 @@ var Model = class _Model {
|
|
|
4703
5595
|
static withCount(...relations) {
|
|
4704
5596
|
return this.query().withCount(...relations);
|
|
4705
5597
|
}
|
|
5598
|
+
/** Post.withSum('orders', 'price'): adds orders_sum_price. */
|
|
5599
|
+
static withSum(relations, column) {
|
|
5600
|
+
return this.query().withSum(relations, column);
|
|
5601
|
+
}
|
|
5602
|
+
static withAvg(relations, column) {
|
|
5603
|
+
return this.query().withAvg(relations, column);
|
|
5604
|
+
}
|
|
5605
|
+
static withMin(relations, column) {
|
|
5606
|
+
return this.query().withMin(relations, column);
|
|
5607
|
+
}
|
|
5608
|
+
static withMax(relations, column) {
|
|
5609
|
+
return this.query().withMax(relations, column);
|
|
5610
|
+
}
|
|
5611
|
+
static withExists(...relations) {
|
|
5612
|
+
return this.query().withExists(...relations);
|
|
5613
|
+
}
|
|
5614
|
+
static withAggregate(relations, column, fn) {
|
|
5615
|
+
return this.query().withAggregate(relations, column, fn);
|
|
5616
|
+
}
|
|
4706
5617
|
static has(relation, operator = ">=", count = 1) {
|
|
4707
5618
|
return this.query().has(relation, operator, count);
|
|
4708
5619
|
}
|
|
@@ -4848,8 +5759,8 @@ var Model = class _Model {
|
|
|
4848
5759
|
/** Guarded names match case-insensitively: SQLite and MySQL column names are case-insensitive. */
|
|
4849
5760
|
isGuarded(key) {
|
|
4850
5761
|
if (this.guarded.length === 0) return false;
|
|
4851
|
-
const
|
|
4852
|
-
return this.guarded.some((guarded) => guarded === "*" || guarded.toLowerCase() ===
|
|
5762
|
+
const lower2 = key.toLowerCase();
|
|
5763
|
+
return this.guarded.some((guarded) => guarded === "*" || guarded.toLowerCase() === lower2);
|
|
4853
5764
|
}
|
|
4854
5765
|
totallyGuarded() {
|
|
4855
5766
|
return !_Model.isUnguarded() && this.fillable.length === 0 && this.guarded.length === 1 && this.guarded[0] === "*";
|
|
@@ -4884,6 +5795,10 @@ var Model = class _Model {
|
|
|
4884
5795
|
const cast = this.getCasts()[key];
|
|
4885
5796
|
this.castCache.delete(key);
|
|
4886
5797
|
this.attributes[key] = cast === void 0 ? value : castSet(this, key, cast, value, this.attributes, this.constructor.name);
|
|
5798
|
+
if (isHashedCast(cast)) {
|
|
5799
|
+
if (value === null || value === void 0) this.pendingHashes.delete(key);
|
|
5800
|
+
else this.pendingHashes.add(key);
|
|
5801
|
+
}
|
|
4887
5802
|
return this;
|
|
4888
5803
|
}
|
|
4889
5804
|
hasGetMutator(key) {
|
|
@@ -4905,6 +5820,11 @@ var Model = class _Model {
|
|
|
4905
5820
|
if (this.softDeletes) implied[this.getDeletedAtColumn()] = "datetime";
|
|
4906
5821
|
return { ...implied, ...this.casts };
|
|
4907
5822
|
}
|
|
5823
|
+
/** Adds casts to this instance only (Laravel's mergeCasts()); withCasts() on a query does it for each result. */
|
|
5824
|
+
mergeCasts(casts) {
|
|
5825
|
+
this.casts = { ...this.casts, ...casts };
|
|
5826
|
+
return this;
|
|
5827
|
+
}
|
|
4908
5828
|
hasCast(key, types) {
|
|
4909
5829
|
const cast = this.getCasts()[key];
|
|
4910
5830
|
if (cast === void 0) return false;
|
|
@@ -4919,6 +5839,7 @@ var Model = class _Model {
|
|
|
4919
5839
|
setRawAttributes(attributes, sync = false) {
|
|
4920
5840
|
this.attributes = { ...attributes };
|
|
4921
5841
|
this.castCache.clear();
|
|
5842
|
+
this.pendingHashes.clear();
|
|
4922
5843
|
if (sync) this.syncOriginal();
|
|
4923
5844
|
return this;
|
|
4924
5845
|
}
|
|
@@ -5176,6 +6097,7 @@ var Model = class _Model {
|
|
|
5176
6097
|
*/
|
|
5177
6098
|
async save() {
|
|
5178
6099
|
const query = this.newModelQuery();
|
|
6100
|
+
await this.hashPendingAttributes();
|
|
5179
6101
|
if (await this.fireModelEvent("saving") === false) return false;
|
|
5180
6102
|
let saved;
|
|
5181
6103
|
if (this.exists) saved = this.isDirty() ? await this.performUpdate(query) : true;
|
|
@@ -5183,6 +6105,28 @@ var Model = class _Model {
|
|
|
5183
6105
|
if (saved) await this.finishSave();
|
|
5184
6106
|
return saved;
|
|
5185
6107
|
}
|
|
6108
|
+
/**
|
|
6109
|
+
* Laravel's hashed cast (castAttributeAsHashedString()), run when the model is saved because the Hasher is
|
|
6110
|
+
* asynchronous: each newly assigned value is hashed before the saving event, so every listener sees the hash, and
|
|
6111
|
+
* again just before the write (after the creating or updating event), so a value a listener assigns is hashed too.
|
|
6112
|
+
* A value that is already a hash is kept when it matches the configured algorithm and options, and refused
|
|
6113
|
+
* otherwise. Only strings and numbers are hashed (null stays null); any other value is refused.
|
|
6114
|
+
*/
|
|
6115
|
+
async hashPendingAttributes() {
|
|
6116
|
+
if (!this.pendingHashes.size) return;
|
|
6117
|
+
const hashing = hasher();
|
|
6118
|
+
for (const key of this.pendingHashes) {
|
|
6119
|
+
const value = this.attributes[key];
|
|
6120
|
+
if (value === null || value === void 0) continue;
|
|
6121
|
+
if (typeof value !== "string" && typeof value !== "number" && typeof value !== "bigint") {
|
|
6122
|
+
throw new LogicError(`The hashed cast on [${key}] needs a string, got ${Array.isArray(value) ? "array" : typeof value}.`);
|
|
6123
|
+
}
|
|
6124
|
+
const text2 = String(value);
|
|
6125
|
+
if (hashing.info(text2).algorithm === "unknown") this.attributes[key] = await hashing.make(text2);
|
|
6126
|
+
else if (hashing.needsRehash(text2)) throw new LogicError("Could not verify the hashed value's configuration.");
|
|
6127
|
+
}
|
|
6128
|
+
this.pendingHashes.clear();
|
|
6129
|
+
}
|
|
5186
6130
|
/** Fills and saves an existing model. */
|
|
5187
6131
|
async update(attributes = {}) {
|
|
5188
6132
|
if (!this.exists) return false;
|
|
@@ -5299,6 +6243,7 @@ var Model = class _Model {
|
|
|
5299
6243
|
if (this.usesUniqueIds()) this.setUniqueIds();
|
|
5300
6244
|
if (await this.fireModelEvent("creating") === false) return false;
|
|
5301
6245
|
if (this.usesTimestamps()) this.updateTimestamps();
|
|
6246
|
+
await this.hashPendingAttributes();
|
|
5302
6247
|
const attributes = this.getAttributes();
|
|
5303
6248
|
if (this.getIncrementing()) {
|
|
5304
6249
|
const id = await query.insertGetId(attributes, this.getKeyName());
|
|
@@ -5315,6 +6260,7 @@ var Model = class _Model {
|
|
|
5315
6260
|
async performUpdate(query) {
|
|
5316
6261
|
if (await this.fireModelEvent("updating") === false) return false;
|
|
5317
6262
|
if (this.usesTimestamps()) this.updateTimestamps();
|
|
6263
|
+
await this.hashPendingAttributes();
|
|
5318
6264
|
const dirty = this.getDirty();
|
|
5319
6265
|
if (Object.keys(dirty).length) {
|
|
5320
6266
|
await this.setKeysForSaveQuery(query).update(dirty);
|
|
@@ -5495,7 +6441,7 @@ var Model = class _Model {
|
|
|
5495
6441
|
}
|
|
5496
6442
|
/**
|
|
5497
6443
|
* A loaded relation, typed from the relation method: post.getRelation('author') is User | null,
|
|
5498
|
-
* post.getRelation('comments') is
|
|
6444
|
+
* post.getRelation('comments') is EloquentCollection<Comment>. Throws RelationNotLoadedError when it isn't loaded
|
|
5499
6445
|
* (JavaScript can't lazy-load synchronously: use with(), load() or post.comments().get()).
|
|
5500
6446
|
*/
|
|
5501
6447
|
getRelation(name) {
|
|
@@ -5504,23 +6450,48 @@ var Model = class _Model {
|
|
|
5504
6450
|
}
|
|
5505
6451
|
/** Eager loads relations onto this model: await post.load('comments.author'). */
|
|
5506
6452
|
async load(...relations) {
|
|
5507
|
-
await this.
|
|
6453
|
+
await this.newCollection([this]).load(...relations);
|
|
5508
6454
|
return this;
|
|
5509
6455
|
}
|
|
5510
6456
|
/** Loads only the relations that aren't loaded yet (nested paths are followed into loaded relations). */
|
|
5511
6457
|
async loadMissing(...relations) {
|
|
5512
|
-
await
|
|
6458
|
+
await this.newCollection([this]).loadMissing(...relations);
|
|
5513
6459
|
return this;
|
|
5514
6460
|
}
|
|
5515
6461
|
/** Loads <relation>_count attributes: await post.loadCount('comments'). */
|
|
5516
6462
|
async loadCount(...relations) {
|
|
5517
|
-
|
|
5518
|
-
|
|
5519
|
-
|
|
5520
|
-
|
|
5521
|
-
|
|
6463
|
+
await this.newCollection([this]).loadCount(...relations);
|
|
6464
|
+
return this;
|
|
6465
|
+
}
|
|
6466
|
+
/** Loads an aggregate of a relation as an attribute (Laravel's loadAggregate()): see withAggregate(). */
|
|
6467
|
+
async loadAggregate(relations, column, fn) {
|
|
6468
|
+
await this.newCollection([this]).loadAggregate(relations, column, fn);
|
|
5522
6469
|
return this;
|
|
5523
6470
|
}
|
|
6471
|
+
/** Loads <relation>_sum_<column>: await user.loadSum('orders', 'price'). */
|
|
6472
|
+
loadSum(relations, column) {
|
|
6473
|
+
return this.loadAggregate(relations, column, "sum");
|
|
6474
|
+
}
|
|
6475
|
+
loadAvg(relations, column) {
|
|
6476
|
+
return this.loadAggregate(relations, column, "avg");
|
|
6477
|
+
}
|
|
6478
|
+
loadMin(relations, column) {
|
|
6479
|
+
return this.loadAggregate(relations, column, "min");
|
|
6480
|
+
}
|
|
6481
|
+
loadMax(relations, column) {
|
|
6482
|
+
return this.loadAggregate(relations, column, "max");
|
|
6483
|
+
}
|
|
6484
|
+
/** Loads a boolean <relation>_exists. */
|
|
6485
|
+
loadExists(...relations) {
|
|
6486
|
+
return this.loadAggregate(relations, "*", "exists");
|
|
6487
|
+
}
|
|
6488
|
+
/**
|
|
6489
|
+
* The collection queries of this model return (Laravel's newCollection()): an EloquentCollection. Override it to
|
|
6490
|
+
* return a subclass with your own methods.
|
|
6491
|
+
*/
|
|
6492
|
+
newCollection(models = []) {
|
|
6493
|
+
return new EloquentCollection(models);
|
|
6494
|
+
}
|
|
5524
6495
|
// ---------------------------------------------------------------- relations storage
|
|
5525
6496
|
/** Stores a loaded relation (eager loading and load() use this). */
|
|
5526
6497
|
setRelation(name, value) {
|
|
@@ -5615,7 +6586,7 @@ var Model = class _Model {
|
|
|
5615
6586
|
const key = Str6.snake(name);
|
|
5616
6587
|
if (!this.isArrayableKey(key)) continue;
|
|
5617
6588
|
if (value === null || value === void 0) result[key] = null;
|
|
5618
|
-
else if (value instanceof
|
|
6589
|
+
else if (value instanceof Collection10) result[key] = value.toArray();
|
|
5619
6590
|
else if (typeof value.toArray === "function") result[key] = value.toArray();
|
|
5620
6591
|
else result[key] = value;
|
|
5621
6592
|
}
|
|
@@ -5623,7 +6594,7 @@ var Model = class _Model {
|
|
|
5623
6594
|
}
|
|
5624
6595
|
serializeValue(value) {
|
|
5625
6596
|
if (value instanceof Date) return serializeDate(value);
|
|
5626
|
-
if (value instanceof
|
|
6597
|
+
if (value instanceof Collection10) return value.toArray();
|
|
5627
6598
|
return value;
|
|
5628
6599
|
}
|
|
5629
6600
|
isArrayableKey(key) {
|
|
@@ -5636,24 +6607,10 @@ var Model = class _Model {
|
|
|
5636
6607
|
};
|
|
5637
6608
|
setModelBaseClass(Model);
|
|
5638
6609
|
async function loadRelations(models, ...relations) {
|
|
5639
|
-
const
|
|
5640
|
-
if (!
|
|
5641
|
-
await
|
|
5642
|
-
return
|
|
5643
|
-
}
|
|
5644
|
-
async function loadMissingOn(models, paths) {
|
|
5645
|
-
for (const path of paths) {
|
|
5646
|
-
const [head = "", ...rest] = path.split(".");
|
|
5647
|
-
const missing = models.filter((model) => !model.relationLoaded(head));
|
|
5648
|
-
if (missing.length) await loadRelations(missing, path);
|
|
5649
|
-
if (!rest.length) continue;
|
|
5650
|
-
const related = models.flatMap((model) => {
|
|
5651
|
-
const value = model.getRelations()[head];
|
|
5652
|
-
if (value instanceof Collection11) return value.all();
|
|
5653
|
-
return value instanceof Model ? [value] : [];
|
|
5654
|
-
});
|
|
5655
|
-
if (related.length) await loadMissingOn(related, [rest.join(".")]);
|
|
5656
|
-
}
|
|
6610
|
+
const list3 = [...models];
|
|
6611
|
+
if (!list3.length) return list3;
|
|
6612
|
+
await list3[0].newQueryWithoutRelationships().with(...relations).eagerLoadRelations(list3);
|
|
6613
|
+
return list3;
|
|
5657
6614
|
}
|
|
5658
6615
|
var Pivot = class extends Model {
|
|
5659
6616
|
guarded = [];
|
|
@@ -5661,9 +6618,6 @@ var Pivot = class extends Model {
|
|
|
5661
6618
|
timestamps = false;
|
|
5662
6619
|
};
|
|
5663
6620
|
|
|
5664
|
-
// Eloquent/DatabaseNotification.ts
|
|
5665
|
-
import { Collection as Collection12 } from "@orieljs/collections";
|
|
5666
|
-
|
|
5667
6621
|
// Eloquent/HasUniqueStringIds.ts
|
|
5668
6622
|
import { Str as Str7 } from "@orieljs/support";
|
|
5669
6623
|
function uniqueStringIds(Base, generate, valid) {
|
|
@@ -5720,6 +6674,10 @@ var DatabaseNotification = class extends HasUuids(Model) {
|
|
|
5720
6674
|
unread() {
|
|
5721
6675
|
return !this.read();
|
|
5722
6676
|
}
|
|
6677
|
+
/** Queries of notifications return a DatabaseNotificationCollection (markAsRead() on all of them). */
|
|
6678
|
+
newCollection(models = []) {
|
|
6679
|
+
return new DatabaseNotificationCollection(models);
|
|
6680
|
+
}
|
|
5723
6681
|
/** `query.read()`: only read notifications. */
|
|
5724
6682
|
static scopeRead(query) {
|
|
5725
6683
|
return query.whereNotNull("read_at");
|
|
@@ -5729,7 +6687,7 @@ var DatabaseNotification = class extends HasUuids(Model) {
|
|
|
5729
6687
|
return query.whereNull("read_at");
|
|
5730
6688
|
}
|
|
5731
6689
|
};
|
|
5732
|
-
var DatabaseNotificationCollection = class extends
|
|
6690
|
+
var DatabaseNotificationCollection = class extends EloquentCollection {
|
|
5733
6691
|
/** Marks every notification as read (one save each, as in Laravel). */
|
|
5734
6692
|
async markAsRead() {
|
|
5735
6693
|
for (const notification of this.all()) await notification.markAsRead();
|
|
@@ -5793,7 +6751,7 @@ var Migration = class {
|
|
|
5793
6751
|
|
|
5794
6752
|
// Migrations/MigrationCreator.ts
|
|
5795
6753
|
import { existsSync as existsSync2, mkdirSync, writeFileSync } from "fs";
|
|
5796
|
-
import { join as
|
|
6754
|
+
import { join as join5 } from "path";
|
|
5797
6755
|
import { Str as Str8 } from "@orieljs/support";
|
|
5798
6756
|
var MIGRATION_CREATE_STUB = `import { Migration, Schema } from '{{ importSource }}'
|
|
5799
6757
|
|
|
@@ -5846,8 +6804,8 @@ function guessTable(migration) {
|
|
|
5846
6804
|
return void 0;
|
|
5847
6805
|
}
|
|
5848
6806
|
function migrationDatePrefix(date = /* @__PURE__ */ new Date()) {
|
|
5849
|
-
const
|
|
5850
|
-
return `${date.getUTCFullYear()}_${
|
|
6807
|
+
const pad3 = (value) => String(value).padStart(2, "0");
|
|
6808
|
+
return `${date.getUTCFullYear()}_${pad3(date.getUTCMonth() + 1)}_${pad3(date.getUTCDate())}_${pad3(date.getUTCHours())}${pad3(date.getUTCMinutes())}${pad3(date.getUTCSeconds())}`;
|
|
5851
6809
|
}
|
|
5852
6810
|
var MigrationCreator = class {
|
|
5853
6811
|
/** Returns the path of the new file. */
|
|
@@ -5860,7 +6818,7 @@ var MigrationCreator = class {
|
|
|
5860
6818
|
if (guessed) ({ table, create } = guessed);
|
|
5861
6819
|
}
|
|
5862
6820
|
const stub = table === void 0 ? MIGRATION_STUB : create ? MIGRATION_CREATE_STUB : MIGRATION_UPDATE_STUB;
|
|
5863
|
-
const file =
|
|
6821
|
+
const file = join5(path, `${migrationDatePrefix(options.date)}_${snake}.ts`);
|
|
5864
6822
|
if (existsSync2(file)) throw new LogicError(`Migration [${file}] already exists.`);
|
|
5865
6823
|
mkdirSync(path, { recursive: true });
|
|
5866
6824
|
writeFileSync(
|
|
@@ -5935,8 +6893,9 @@ var MigrationRepository = class {
|
|
|
5935
6893
|
|
|
5936
6894
|
// Migrations/Migrator.ts
|
|
5937
6895
|
import { existsSync as existsSync3, readdirSync as readdirSync2 } from "fs";
|
|
5938
|
-
import { basename, extname, join as
|
|
6896
|
+
import { basename, extname, join as join6 } from "path";
|
|
5939
6897
|
import { pathToFileURL as pathToFileURL2 } from "url";
|
|
6898
|
+
var SQLITE_MIGRATION_HINT = "SQLite runs a migration with foreign keys off, so ON DELETE and ON UPDATE actions don't run in it: change the child rows first, or set withinTransaction = false.";
|
|
5940
6899
|
var MIGRATION_FILE = /^(?!.*\.d\.[mc]?ts$).+\.(ts|js|mts|mjs)$/;
|
|
5941
6900
|
var Migrator = class {
|
|
5942
6901
|
constructor(manager, output = () => void 0) {
|
|
@@ -5963,7 +6922,7 @@ var Migrator = class {
|
|
|
5963
6922
|
for (const path of paths) {
|
|
5964
6923
|
if (!existsSync3(path)) continue;
|
|
5965
6924
|
for (const file of readdirSync2(path)) {
|
|
5966
|
-
if (MIGRATION_FILE.test(file)) files.push([basename(file, extname(file)),
|
|
6925
|
+
if (MIGRATION_FILE.test(file)) files.push([basename(file, extname(file)), join6(path, file)]);
|
|
5967
6926
|
}
|
|
5968
6927
|
}
|
|
5969
6928
|
return new Map(files.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
|
|
@@ -6062,10 +7021,31 @@ var Migrator = class {
|
|
|
6062
7021
|
const run = async () => {
|
|
6063
7022
|
await migration[method]();
|
|
6064
7023
|
};
|
|
6065
|
-
if (
|
|
7024
|
+
if (connection.getDriverName() === "sqlite") await this.runOnSqlite(connection, migration, run);
|
|
7025
|
+
else if (migration.withinTransaction && connection.getDriverName() !== "mysql") await connection.transaction(run);
|
|
6066
7026
|
else await run();
|
|
6067
7027
|
});
|
|
6068
7028
|
}
|
|
7029
|
+
/**
|
|
7030
|
+
* SQLite's order for a migration in a transaction: foreign keys off before the transaction (SQLite ignores the pragma
|
|
7031
|
+
* inside one, and a table rebuild would otherwise run the ON DELETE actions of the tables that reference it), the
|
|
7032
|
+
* migration, a foreign key check before the commit (rows that break a key fail the migration), then foreign keys back
|
|
7033
|
+
* on. A migration outside a transaction runs with foreign keys as they are, so its ON DELETE and ON UPDATE actions
|
|
7034
|
+
* run; a table rebuild in it turns them off around itself and checks the table.
|
|
7035
|
+
*/
|
|
7036
|
+
async runOnSqlite(connection, migration, run) {
|
|
7037
|
+
if (!migration.withinTransaction) return run();
|
|
7038
|
+
const toggle = connection.transactionLevel() === 0 && await sqliteForeignKeysEnabled(connection);
|
|
7039
|
+
if (toggle) await connection.statement("PRAGMA foreign_keys = OFF");
|
|
7040
|
+
try {
|
|
7041
|
+
await connection.transaction(async () => {
|
|
7042
|
+
await run();
|
|
7043
|
+
if (toggle) await assertSqliteForeignKeys(connection, void 0, SQLITE_MIGRATION_HINT);
|
|
7044
|
+
});
|
|
7045
|
+
} finally {
|
|
7046
|
+
if (toggle) await connection.statement("PRAGMA foreign_keys = ON");
|
|
7047
|
+
}
|
|
7048
|
+
}
|
|
6069
7049
|
};
|
|
6070
7050
|
|
|
6071
7051
|
// Seeder.ts
|
|
@@ -6095,7 +7075,7 @@ var Seeder = class {
|
|
|
6095
7075
|
|
|
6096
7076
|
// Console/commands.ts
|
|
6097
7077
|
import { existsSync as existsSync4 } from "fs";
|
|
6098
|
-
import { isAbsolute, join as
|
|
7078
|
+
import { isAbsolute, join as join7, relative as relative2 } from "path";
|
|
6099
7079
|
import { pathToFileURL as pathToFileURL3 } from "url";
|
|
6100
7080
|
|
|
6101
7081
|
// Types/TypeGenerator.ts
|
|
@@ -6111,7 +7091,7 @@ function castType(cast) {
|
|
|
6111
7091
|
if (cast === void 0) return void 0;
|
|
6112
7092
|
if (typeof cast === "string") {
|
|
6113
7093
|
if (["int", "integer", "float", "double", "real", "timestamp"].includes(cast)) return "number";
|
|
6114
|
-
if (cast === "string" || cast.startsWith("decimal:")) return "string";
|
|
7094
|
+
if (cast === "string" || cast === "hashed" || cast.startsWith("decimal:")) return "string";
|
|
6115
7095
|
if (cast === "bool" || cast === "boolean") return "boolean";
|
|
6116
7096
|
if (["date", "datetime", "immutable_date", "immutable_datetime"].includes(cast)) return "Date";
|
|
6117
7097
|
return "unknown";
|
|
@@ -6220,7 +7200,7 @@ var TypeGenerator = class {
|
|
|
6220
7200
|
|
|
6221
7201
|
// Console/commands.ts
|
|
6222
7202
|
var text = (value) => typeof value === "string" && value !== "" ? value : void 0;
|
|
6223
|
-
var
|
|
7203
|
+
var list2 = (value) => Array.isArray(value) ? value.map(String) : text(value) ? [String(value)] : [];
|
|
6224
7204
|
var integer = (value) => {
|
|
6225
7205
|
const number = Number(value ?? 0);
|
|
6226
7206
|
return Number.isInteger(number) && number > 0 ? number : 0;
|
|
@@ -6236,7 +7216,7 @@ function confirmToProceed(context, command) {
|
|
|
6236
7216
|
return false;
|
|
6237
7217
|
}
|
|
6238
7218
|
function migrationPaths(context, command) {
|
|
6239
|
-
const paths =
|
|
7219
|
+
const paths = list2(command.option("path"));
|
|
6240
7220
|
if (!paths.length) return [context.app.databasePath("migrations")];
|
|
6241
7221
|
return paths.map((path) => isAbsolute(path) ? path : context.app.basePath(path));
|
|
6242
7222
|
}
|
|
@@ -6245,7 +7225,7 @@ function migrator(context, command) {
|
|
|
6245
7225
|
}
|
|
6246
7226
|
async function runSeeder(context, className, output, database) {
|
|
6247
7227
|
const name = className.split("\\").pop();
|
|
6248
|
-
const file = ["ts", "js", "mts", "mjs"].map((extension) => context.app.databasePath(
|
|
7228
|
+
const file = ["ts", "js", "mts", "mjs"].map((extension) => context.app.databasePath(join7("seeders", `${name}.${extension}`))).find(existsSync4);
|
|
6249
7229
|
if (!file) throw new LogicError(`Seeder [${name}] not found in ${context.app.databasePath("seeders")}.`);
|
|
6250
7230
|
const module = await import(pathToFileURL3(file).href);
|
|
6251
7231
|
const exported = module.default ?? module[name];
|
|
@@ -6255,7 +7235,7 @@ async function runSeeder(context, className, output, database) {
|
|
|
6255
7235
|
}
|
|
6256
7236
|
async function generateModelTypes(context) {
|
|
6257
7237
|
if (!context.models) return void 0;
|
|
6258
|
-
const outputFile = context.app.basePath(
|
|
7238
|
+
const outputFile = context.app.basePath(join7("types", "models.d.ts"));
|
|
6259
7239
|
await new TypeGenerator({ outputFile, importSource: context.typesImportSource }).write((await context.models()).all());
|
|
6260
7240
|
return relative2(context.app.basePath(), outputFile);
|
|
6261
7241
|
}
|
|
@@ -6366,7 +7346,7 @@ function registerModelTypesCommand(kernel, context) {
|
|
|
6366
7346
|
|
|
6367
7347
|
// ModelRegistry.ts
|
|
6368
7348
|
import { existsSync as existsSync5, readdirSync as readdirSync3, statSync } from "fs";
|
|
6369
|
-
import { join as
|
|
7349
|
+
import { join as join8 } from "path";
|
|
6370
7350
|
import { pathToFileURL as pathToFileURL4 } from "url";
|
|
6371
7351
|
import { Str as Str10 } from "@orieljs/support";
|
|
6372
7352
|
var MODEL_FILE = /^(?!.*\.d\.[mc]?ts$).+\.(ts|js|mts|mjs)$/;
|
|
@@ -6410,7 +7390,7 @@ function listFiles(directory) {
|
|
|
6410
7390
|
if (!existsSync5(directory)) return [];
|
|
6411
7391
|
const files = [];
|
|
6412
7392
|
for (const entry of readdirSync3(directory).sort()) {
|
|
6413
|
-
const path =
|
|
7393
|
+
const path = join8(directory, entry);
|
|
6414
7394
|
if (statSync(path).isDirectory()) files.push(...listFiles(path));
|
|
6415
7395
|
else if (MODEL_FILE.test(entry)) files.push(path);
|
|
6416
7396
|
}
|
|
@@ -6878,11 +7858,15 @@ var DatabaseServiceProvider = class extends ServiceProvider {
|
|
|
6878
7858
|
Model.clearBootedModels();
|
|
6879
7859
|
this.mergeConfigFrom(databaseConfigDefaults(this.app), "database");
|
|
6880
7860
|
this.app.singleton(DatabaseManager3, () => new DatabaseManagerImpl(() => this.app.make(ConfigRepository).get("database")));
|
|
7861
|
+
this.app.onShutdown(async () => {
|
|
7862
|
+
if (this.app.resolved(DatabaseManager3)) await this.app.make(DatabaseManager3).disconnectAll();
|
|
7863
|
+
});
|
|
6881
7864
|
this.app.singleton(ModelRegistry);
|
|
6882
7865
|
this.app.singleton(RouteModelResolver, () => new RouteModelResolverImpl(this.app.make(ModelRegistry)));
|
|
6883
7866
|
this.app.bind(SchemaBuilderToken, () => this.manager().getSchemaBuilder());
|
|
6884
7867
|
}
|
|
6885
7868
|
async boot() {
|
|
7869
|
+
Model.warnOnRelationPropertyAccess(!this.app.isProduction());
|
|
6886
7870
|
usePaginationResolvers();
|
|
6887
7871
|
const registry2 = this.app.make(ModelRegistry);
|
|
6888
7872
|
const classes = this.app.bound(ClassRegistry2) ? this.app.make(ClassRegistry2) : void 0;
|
|
@@ -6920,6 +7904,7 @@ export {
|
|
|
6920
7904
|
DatabaseNotificationCollection,
|
|
6921
7905
|
DatabaseNotificationsRelation,
|
|
6922
7906
|
DatabaseServiceProvider,
|
|
7907
|
+
EloquentCollection,
|
|
6923
7908
|
Expression,
|
|
6924
7909
|
Factory,
|
|
6925
7910
|
Faker,
|
|
@@ -6991,6 +7976,7 @@ export {
|
|
|
6991
7976
|
isDateCast,
|
|
6992
7977
|
isEquivalent,
|
|
6993
7978
|
isJsonCast,
|
|
7979
|
+
isTableRebuild,
|
|
6994
7980
|
loadRelations,
|
|
6995
7981
|
migrationDatePrefix,
|
|
6996
7982
|
modelEventName,
|