@orieljs/database 0.1.0-alpha.5 → 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/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, sql7, bindings, cause) {
20
- super(`${cause instanceof Error ? cause.message : String(cause)} (Connection: ${connectionName}, SQL: ${sql7})`, { cause });
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 = sql7;
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(sql7) {
94
- const statement = this.database.prepare(sql7);
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,
@@ -363,7 +363,10 @@ var AbstractPaginator = class _AbstractPaginator {
363
363
  this.collection = items;
364
364
  return this;
365
365
  }
366
- /** Transforms each item in place, typically for serialization: paginator.through(post => ({ id: post.id })). */
366
+ /**
367
+ * Transforms each item in place, typically for serialization, and returns this paginator typed with the new items:
368
+ * `posts.through((post) => ({ id: post.id }))`. Each paginator narrows the return type to its own class.
369
+ */
367
370
  through(callback) {
368
371
  this.collection = this.collection.map(callback);
369
372
  return this;
@@ -466,6 +469,9 @@ var CursorPaginator = class extends AbstractPaginator {
466
469
  getCursorName() {
467
470
  return this.cursorName;
468
471
  }
472
+ through(callback) {
473
+ return super.through(callback);
474
+ }
469
475
  hasMorePages() {
470
476
  return this.cursorValue === void 0 && this.hasMore || this.cursorValue !== void 0 && this.cursorValue.pointsToNextItems() && this.hasMore || this.cursorValue !== void 0 && this.cursorValue.pointsToPreviousItems();
471
477
  }
@@ -524,6 +530,9 @@ var LengthAwarePaginator = class extends AbstractPaginator {
524
530
  total() {
525
531
  return this.totalValue;
526
532
  }
533
+ through(callback) {
534
+ return super.through(callback);
535
+ }
527
536
  lastPage() {
528
537
  return this.lastPageValue;
529
538
  }
@@ -614,6 +623,9 @@ var Paginator = class extends AbstractPaginator {
614
623
  hasMorePages() {
615
624
  return this.hasMore;
616
625
  }
626
+ through(callback) {
627
+ return super.through(callback);
628
+ }
617
629
  hasPages() {
618
630
  return this.currentPageValue !== 1 || this.hasMore;
619
631
  }
@@ -683,6 +695,7 @@ var clauses = (parts) => join(parts.filter((part) => part !== void 0), " ");
683
695
  function likeToGlob(pattern) {
684
696
  return pattern.replaceAll("*", "[*]").replaceAll("?", "[?]").replaceAll("%", "*").replaceAll("_", "?");
685
697
  }
698
+ var SQLITE_DATE_FORMATS = { date: "%Y-%m-%d", time: "%H:%M:%S", day: "%d", month: "%m", year: "%Y" };
686
699
  var Grammar = class {
687
700
  constructor(driver) {
688
701
  this.driver = driver;
@@ -724,7 +737,7 @@ var Grammar = class {
724
737
  return join(columns.map((column) => this.wrap(column)));
725
738
  }
726
739
  compileSelect(query) {
727
- const columns = query.columns.length ? join(query.columns.map((column) => typeof column === "object" && "query" in column ? sql2`(${this.compileSelect(column.query)}) as ${sql2.id(column.as)}` : this.wrap(column))) : sql2.raw("*");
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("*");
728
741
  return clauses([query.distinctRows ? sql2`select distinct ${columns}` : sql2`select ${columns}`, this.compileComponents(query)]);
729
742
  }
730
743
  /** Everything after the select list: from, joins, where, group by, having, order by, limit/offset, lock. */
@@ -775,7 +788,24 @@ var Grammar = class {
775
788
  return sql2`${sql2.raw(where.not ? "not exists" : "exists")} (${this.compileSelect(where.query)})`;
776
789
  case "raw":
777
790
  return rawWithBindings(where.sql, where.bindings.map((value) => this.prepare(value)));
791
+ case "date":
792
+ return this.compileWhereDate(where);
793
+ }
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}`;
778
807
  }
808
+ return sql2`${sql2.raw(where.part)}(${column}) ${operator} ${value}`;
779
809
  }
780
810
  /**
781
811
  * whereLike() per driver, as Laravel 12's grammars: Postgres compares the column as text with ilike (like when
@@ -934,6 +964,19 @@ function keyOf(item, alias) {
934
964
  }
935
965
  return value;
936
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
+ }
937
980
  var isRow = (value) => typeof value === "object" && value !== null && !(value instanceof Expression) && !(value instanceof Builder) && !Array.isArray(value);
938
981
  function columnKey(column) {
939
982
  const alias = /\s+as\s+/i.exec(column);
@@ -1043,6 +1086,41 @@ var Builder = class _Builder {
1043
1086
  this.wheres.push({ type: "between", column, values, not: true, boolean: "and" });
1044
1087
  return this;
1045
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
+ }
1046
1124
  /**
1047
1125
  * Laravel's whereLike(): the value is the pattern, `%` and `_` included (`whereLike('title', `%${term}%`)`).
1048
1126
  * Case-insensitive unless caseSensitive: ilike on Postgres, like on MySQL and SQLite (their like already ignores
@@ -1072,12 +1150,12 @@ var Builder = class _Builder {
1072
1150
  orWhereColumn(first, operatorOrSecond, second) {
1073
1151
  return this.whereColumn(first, operatorOrSecond, second, "or");
1074
1152
  }
1075
- whereRaw(sql7, bindings = [], boolean = "and") {
1076
- this.wheres.push({ type: "raw", sql: sql7, bindings, boolean });
1153
+ whereRaw(sql8, bindings = [], boolean = "and") {
1154
+ this.wheres.push({ type: "raw", sql: sql8, bindings, boolean });
1077
1155
  return this;
1078
1156
  }
1079
- orWhereRaw(sql7, bindings = []) {
1080
- return this.whereRaw(sql7, bindings, "or");
1157
+ orWhereRaw(sql8, bindings = []) {
1158
+ return this.whereRaw(sql8, bindings, "or");
1081
1159
  }
1082
1160
  whereExists(query, boolean = "and", not = false) {
1083
1161
  const sub = query instanceof _Builder ? query : this.subQuery(query);
@@ -1128,8 +1206,8 @@ var Builder = class _Builder {
1128
1206
  this.havings.push({ column, operator, value: operand, boolean });
1129
1207
  return this;
1130
1208
  }
1131
- havingRaw(sql7, bindings = [], boolean = "and") {
1132
- this.havings.push({ raw: new Expression(sql7, bindings), boolean });
1209
+ havingRaw(sql8, bindings = [], boolean = "and") {
1210
+ this.havings.push({ raw: new Expression(sql8, bindings), boolean });
1133
1211
  return this;
1134
1212
  }
1135
1213
  orderBy(column, direction = "asc") {
@@ -1151,8 +1229,8 @@ var Builder = class _Builder {
1151
1229
  this.orders.push({ raw: this.grammar.compileRandom() });
1152
1230
  return this;
1153
1231
  }
1154
- orderByRaw(sql7, bindings = []) {
1155
- this.orders.push({ raw: new Expression(sql7, bindings) });
1232
+ orderByRaw(sql8, bindings = []) {
1233
+ this.orders.push({ raw: new Expression(sql8, bindings) });
1156
1234
  return this;
1157
1235
  }
1158
1236
  /** Removes existing orders, optionally adding a new one. */
@@ -1203,7 +1281,11 @@ var Builder = class _Builder {
1203
1281
  }
1204
1282
  // ---------------------------------------------------------------- reading
1205
1283
  async get() {
1206
- return new Collection3(await this.runSelect());
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);
1207
1289
  }
1208
1290
  /** The raw rows, without a Collection around them. */
1209
1291
  async runSelect() {
@@ -1358,7 +1440,7 @@ var Builder = class _Builder {
1358
1440
  for (let page = 1; ; page++) {
1359
1441
  const results = await this.clone().forPage(page, count).runSelect();
1360
1442
  if (!results.length) return true;
1361
- if (await callback(new Collection3(results), page) === false) return false;
1443
+ if (await callback(this.newCollection(results), page) === false) return false;
1362
1444
  if (results.length < count) return true;
1363
1445
  }
1364
1446
  }
@@ -1370,7 +1452,7 @@ var Builder = class _Builder {
1370
1452
  for (let page = 1; ; page++) {
1371
1453
  const results = await this.clone().forPageAfterId(count, lastId, key).runSelect();
1372
1454
  if (!results.length) return true;
1373
- if (await callback(new Collection3(results), page) === false) return false;
1455
+ if (await callback(this.newCollection(results), page) === false) return false;
1374
1456
  if (results.length < count) return true;
1375
1457
  lastId = keyOf(results.at(-1), aliasName);
1376
1458
  }
@@ -1501,6 +1583,13 @@ var Builder = class _Builder {
1501
1583
  this.wheres.push({ type: "basic", column: ref, operator, value, boolean });
1502
1584
  return this;
1503
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
+ }
1504
1593
  pushNull(column, not, boolean) {
1505
1594
  this.wheres.push({ type: "null", column, not, boolean });
1506
1595
  return this;
@@ -1524,10 +1613,10 @@ var JoinClause = class extends Builder {
1524
1613
 
1525
1614
  // Connection.ts
1526
1615
  import { AsyncLocalStorage } from "async_hooks";
1527
- import { Kysely, sql as sql6 } from "kysely";
1616
+ import { Kysely, sql as sql7 } from "kysely";
1528
1617
 
1529
1618
  // Schema/Builder.ts
1530
- import { sql as sql5 } from "kysely";
1619
+ import { sql as sql6 } from "kysely";
1531
1620
 
1532
1621
  // Schema/ColumnDefinition.ts
1533
1622
  var ColumnDefinition = class {
@@ -1590,6 +1679,15 @@ var ColumnDefinition = class {
1590
1679
  this.attributes.default = new Expression("CURRENT_TIMESTAMP");
1591
1680
  return this;
1592
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
+ }
1593
1691
  /** MySQL only: on update CURRENT_TIMESTAMP. */
1594
1692
  useCurrentOnUpdate() {
1595
1693
  this.attributes.onUpdate = new Expression("CURRENT_TIMESTAMP");
@@ -1833,8 +1931,8 @@ var Blueprint = class {
1833
1931
  }
1834
1932
  /** t.foreign('user_id').references('id').on('users') */
1835
1933
  foreign(columns, name) {
1836
- const list2 = [columns].flat();
1837
- const foreign = new ForeignKeyDefinition(list2, name ?? this.createIndexName("foreign", list2));
1934
+ const list3 = [columns].flat();
1935
+ const foreign = new ForeignKeyDefinition(list3, name ?? this.createIndexName("foreign", list3));
1838
1936
  this.commands.push({ name: "foreign", foreign });
1839
1937
  return foreign;
1840
1938
  }
@@ -1855,8 +1953,10 @@ var Blueprint = class {
1855
1953
  dropIndex(index) {
1856
1954
  this.commands.push({ name: "dropIndex", index: this.indexNameFor("index", index) });
1857
1955
  }
1956
+ /** By name, or by columns (the conventional name; SQLite needs the columns, it doesn't keep foreign key names). */
1858
1957
  dropForeign(index) {
1859
- this.commands.push({ name: "dropForeign", index: this.indexNameFor("foreign", index) });
1958
+ const columns = Array.isArray(index) ? [...index] : void 0;
1959
+ this.commands.push({ name: "dropForeign", index: this.indexNameFor("foreign", index), ...columns ? { columns } : {} });
1860
1960
  }
1861
1961
  /** Drops the foreign key on the column, then the column. */
1862
1962
  dropConstrainedForeignId(column) {
@@ -1886,6 +1986,14 @@ var Blueprint = class {
1886
1986
  this.commands.push({ name: "dropIfExists" });
1887
1987
  }
1888
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
+ }
1889
1997
  /** Laravel's default index name: {table}_{columns}_{type}, lowercased, with - and . replaced by _. */
1890
1998
  createIndexName(type, columns) {
1891
1999
  return `${this.table}_${columns.join("_")}_${type}`.toLowerCase().replace(/[-.]/g, "_");
@@ -1904,8 +2012,8 @@ var Blueprint = class {
1904
2012
  return commands;
1905
2013
  }
1906
2014
  indexCommand(type, columns, name) {
1907
- const list2 = [columns].flat();
1908
- this.commands.push({ name: type, columns: list2, index: name ?? this.createIndexName(type, list2) });
2015
+ const list3 = [columns].flat();
2016
+ this.commands.push({ name: type, columns: list3, index: name ?? this.createIndexName(type, list3) });
1909
2017
  }
1910
2018
  indexNameFor(type, index) {
1911
2019
  return Array.isArray(index) ? this.createIndexName(type, index) : index;
@@ -1914,6 +2022,8 @@ var Blueprint = class {
1914
2022
 
1915
2023
  // Schema/Grammar.ts
1916
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";
1917
2027
  var join2 = (parts, separator = ", ") => sql4.join(parts, sql4.raw(separator));
1918
2028
  var columnList = (columns) => join2(columns.map((column) => sql4.id(column)));
1919
2029
  var SchemaGrammar = class {
@@ -1926,28 +2036,40 @@ var SchemaGrammar = class {
1926
2036
  if (driver === "mysql") return new MySqlSchemaGrammar(config);
1927
2037
  return new SqliteSchemaGrammar(config);
1928
2038
  }
1929
- /** Every statement for the blueprint: create/add first, then commands in order, then indexes from column modifiers. */
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
+ */
1930
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) {
1931
2052
  const statements = [];
1932
2053
  const commands = [...blueprint.commands, ...blueprint.fluentIndexCommands()];
1933
2054
  const handled = /* @__PURE__ */ new Set();
1934
2055
  if (blueprint.creating) {
1935
2056
  statements.push(this.compileCreate(blueprint, commands, handled));
1936
- } else if (blueprint.columns.length) {
1937
- 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));
1938
2060
  }
1939
2061
  for (const command of commands) {
1940
2062
  if (command.name === "create" || handled.has(command)) continue;
1941
2063
  statements.push(...this.compileCommand(blueprint, command));
1942
2064
  }
1943
2065
  if (blueprint.creating || blueprint.columns.length) statements.push(...this.compileComments(blueprint));
1944
- return statements;
2066
+ return mergeRebuilds(statements);
1945
2067
  }
1946
2068
  compileCreate(blueprint, _commands, _handled) {
1947
2069
  return sql4`create table ${sql4.id(blueprint.table)} (${join2(blueprint.columns.map((column) => this.columnDefinition(column)))})`;
1948
2070
  }
1949
2071
  compileAdd(blueprint, _commands, _handled) {
1950
- return blueprint.columns.map((column) => sql4`alter table ${sql4.id(blueprint.table)} add column ${this.columnDefinition(column)}`);
2072
+ return blueprint.addedColumns().map((column) => sql4`alter table ${sql4.id(blueprint.table)} add column ${this.columnDefinition(column)}`);
1951
2073
  }
1952
2074
  compileCommand(blueprint, command) {
1953
2075
  const table = sql4.id(blueprint.table);
@@ -2021,7 +2143,8 @@ var SchemaGrammar = class {
2021
2143
  if (!foreign.referencedTable) {
2022
2144
  throw new LogicError(`Foreign key [${foreign.indexName}] has no referenced table: call on('table') or constrained().`);
2023
2145
  }
2024
- const parts = [sql4`references ${sql4.id(foreign.referencedTable)} (${columnList(foreign.referencedColumns)})`];
2146
+ const columns = foreign.referencedColumns.length ? sql4` (${columnList(foreign.referencedColumns)})` : sql4.raw("");
2147
+ const parts = [sql4`references ${sql4.id(foreign.referencedTable)}${columns}`];
2025
2148
  if (foreign.deleteAction) parts.push(sql4.raw(`on delete ${foreign.deleteAction}`));
2026
2149
  if (foreign.updateAction) parts.push(sql4.raw(`on update ${foreign.updateAction}`));
2027
2150
  return join2(parts, " ");
@@ -2049,9 +2172,21 @@ var SchemaGrammar = class {
2049
2172
  }
2050
2173
  };
2051
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
+ }
2052
2187
  var SqliteSchemaGrammar = class extends SchemaGrammar {
2053
2188
  driver = "sqlite";
2054
- /** SQLite can't add keys to an existing table, so primary and foreign keys go inside create table. */
2189
+ /** A new table's primary and foreign keys go inside create table (adding them later rebuilds the table). */
2055
2190
  compileCreate(blueprint, commands, handled) {
2056
2191
  const parts = blueprint.columns.map((column) => this.columnDefinition(column));
2057
2192
  for (const command of commands) {
@@ -2067,7 +2202,7 @@ var SqliteSchemaGrammar = class extends SchemaGrammar {
2067
2202
  }
2068
2203
  /** New columns may carry an inline `references` clause (the only foreign key SQLite can add later). */
2069
2204
  compileAdd(blueprint, commands, handled) {
2070
- return blueprint.columns.map((column) => {
2205
+ return blueprint.addedColumns().map((column) => {
2071
2206
  const foreign = commands.find(
2072
2207
  (command) => command.name === "foreign" && command.foreign.columns.length === 1 && command.foreign.columns[0] === column.name
2073
2208
  );
@@ -2079,17 +2214,27 @@ var SqliteSchemaGrammar = class extends SchemaGrammar {
2079
2214
  return sql4`alter table ${sql4.id(blueprint.table)} add column ${definition}`;
2080
2215
  });
2081
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
+ */
2082
2221
  compileCommand(blueprint, command) {
2083
- const unsupported = {
2084
- primary: "adding a primary key to an existing table",
2085
- foreign: "adding a foreign key to an existing column",
2086
- dropPrimary: "dropping a primary key",
2087
- dropForeign: "dropping a foreign key"
2088
- };
2089
- const action = unsupported[command.name];
2090
- 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
+ }
2091
2228
  return super.compileCommand(blueprint, command);
2092
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
+ }
2093
2238
  compileUnique(blueprint, index, columns) {
2094
2239
  return sql4`create unique index ${sql4.id(index)} on ${sql4.id(blueprint.table)} (${columnList(columns)})`;
2095
2240
  }
@@ -2161,6 +2306,37 @@ var SqliteSchemaGrammar = class extends SchemaGrammar {
2161
2306
  };
2162
2307
  });
2163
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
+ }
2164
2340
  compileEnableForeignKeyConstraints() {
2165
2341
  return sql4.raw("PRAGMA foreign_keys = ON");
2166
2342
  }
@@ -2168,10 +2344,31 @@ var SqliteSchemaGrammar = class extends SchemaGrammar {
2168
2344
  return sql4.raw("PRAGMA foreign_keys = OFF");
2169
2345
  }
2170
2346
  };
2347
+ var POSTGRES_ACTIONS = { a: "no action", r: "restrict", c: "cascade", n: "set null", d: "set default" };
2171
2348
  var PostgresSchemaGrammar = class extends SchemaGrammar {
2172
2349
  driver = "pgsql";
2350
+ /** A changed column's comment is set again, or cleared (`is NULL`) when the new definition has none (Laravel 11+). */
2173
2351
  compileComments(blueprint) {
2174
- return blueprint.columns.filter((column) => column.attributes.comment !== void 0).map((column) => sql4`comment on column ${sql4.id(blueprint.table, column.name)} is ${sql4.lit(column.attributes.comment)}`);
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}`))}`];
2175
2372
  }
2176
2373
  type(column) {
2177
2374
  const { type, autoIncrement, length, total, places, precision } = column.attributes;
@@ -2250,6 +2447,52 @@ var PostgresSchemaGrammar = class extends SchemaGrammar {
2250
2447
  };
2251
2448
  });
2252
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
+ }
2253
2496
  compileEnableForeignKeyConstraints() {
2254
2497
  return sql4.raw("SET CONSTRAINTS ALL IMMEDIATE");
2255
2498
  }
@@ -2265,7 +2508,11 @@ var MySqlSchemaGrammar = class extends SchemaGrammar {
2265
2508
  return sql4`${super.compileCreate(blueprint, commands, handled)} default character set ${sql4.raw(charset.replace(/[^\w]/g, ""))} collate ${sql4.lit(collation)}`;
2266
2509
  }
2267
2510
  compileAdd(blueprint) {
2268
- return blueprint.columns.map((column) => sql4`alter table ${sql4.id(blueprint.table)} add ${this.columnDefinition(column)}`);
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)}`];
2269
2516
  }
2270
2517
  compileUnique(blueprint, index, columns) {
2271
2518
  return sql4`alter table ${sql4.id(blueprint.table)} add unique ${sql4.id(index)}(${columnList(columns)})`;
@@ -2338,13 +2585,14 @@ var MySqlSchemaGrammar = class extends SchemaGrammar {
2338
2585
  }
2339
2586
  }
2340
2587
  modifiers(column) {
2341
- 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";
2342
2590
  return present([
2343
2591
  unsigned ? sql4.raw(" unsigned") : void 0,
2344
2592
  this.nullable(column),
2345
2593
  this.default(column),
2346
2594
  onUpdate ? sql4` on update ${this.defaultValue(onUpdate)}` : void 0,
2347
- autoIncrement ? sql4.raw(" auto_increment primary key") : void 0,
2595
+ autoIncrement ? sql4.raw(increment) : void 0,
2348
2596
  comment === void 0 ? void 0 : sql4` comment ${sql4.lit(comment)}`,
2349
2597
  after === void 0 ? void 0 : sql4` after ${sql4.id(after)}`,
2350
2598
  first ? sql4.raw(" first") : void 0
@@ -2367,6 +2615,37 @@ var MySqlSchemaGrammar = class extends SchemaGrammar {
2367
2615
  auto_increment: Number(row.auto_increment) === 1
2368
2616
  }));
2369
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
+ }
2370
2649
  compileEnableForeignKeyConstraints() {
2371
2650
  return sql4.raw("SET FOREIGN_KEY_CHECKS=1");
2372
2651
  }
@@ -2375,6 +2654,235 @@ var MySqlSchemaGrammar = class extends SchemaGrammar {
2375
2654
  }
2376
2655
  };
2377
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
+
2378
2886
  // Schema/Builder.ts
2379
2887
  var SchemaBuilder = class _SchemaBuilder {
2380
2888
  constructor(db, resolveConnection) {
@@ -2413,9 +2921,15 @@ var SchemaBuilder = class _SchemaBuilder {
2413
2921
  async rename(from, to) {
2414
2922
  await this.run([this.grammar.compileRename(from, to)]);
2415
2923
  }
2416
- /** Runs a blueprint's statements. Also useful to inspect the DDL: grammar.compile(blueprint). */
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
+ */
2417
2928
  async build(blueprint) {
2418
- await this.run(this.grammar.compile(blueprint));
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
+ }
2419
2933
  }
2420
2934
  /** The table names of the connection's database (or current schema on Postgres). */
2421
2935
  async getTables() {
@@ -2440,6 +2954,31 @@ var SchemaBuilder = class _SchemaBuilder {
2440
2954
  const existing = (await this.getColumnListing(table)).map((name) => name.toLowerCase());
2441
2955
  return columns.every((column) => existing.includes(column.toLowerCase()));
2442
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
+ }
2443
2982
  async enableForeignKeyConstraints() {
2444
2983
  await this.run([this.grammar.compileEnableForeignKeyConstraints()]);
2445
2984
  }
@@ -2466,7 +3005,7 @@ var SchemaBuilder = class _SchemaBuilder {
2466
3005
  const tables = await this.getTables();
2467
3006
  if (!tables.length) return;
2468
3007
  if (this.db.getDriverName() === "pgsql") {
2469
- await this.run([sql5`drop table ${sql5.join(tables.map((table) => sql5.id(table)))} cascade`]);
3008
+ await this.run([sql6`drop table ${sql6.join(tables.map((table) => sql6.id(table)))} cascade`]);
2470
3009
  return;
2471
3010
  }
2472
3011
  await this.withoutForeignKeyConstraints(async () => {
@@ -2612,16 +3151,16 @@ var Connection = class {
2612
3151
  const parent = this.current();
2613
3152
  if (!parent) return { trx: await this.db.startTransaction().execute(), level: 1 };
2614
3153
  const level = parent.level + 1;
2615
- await sql6.raw(`SAVEPOINT trans${level}`).execute(parent.trx);
3154
+ await sql7.raw(`SAVEPOINT trans${level}`).execute(parent.trx);
2616
3155
  return { trx: parent.trx, level };
2617
3156
  }
2618
3157
  async close(frame, action) {
2619
3158
  if (frame.level === 1) {
2620
3159
  await (action === "commit" ? frame.trx.commit() : frame.trx.rollback()).execute();
2621
3160
  } else if (action === "commit") {
2622
- await sql6.raw(`RELEASE SAVEPOINT trans${frame.level}`).execute(frame.trx);
3161
+ await sql7.raw(`RELEASE SAVEPOINT trans${frame.level}`).execute(frame.trx);
2623
3162
  } else {
2624
- await sql6.raw(`ROLLBACK TO SAVEPOINT trans${frame.level}`).execute(frame.trx);
3163
+ await sql7.raw(`ROLLBACK TO SAVEPOINT trans${frame.level}`).execute(frame.trx);
2625
3164
  }
2626
3165
  }
2627
3166
  };
@@ -2785,10 +3324,10 @@ var Schema = facade(SchemaBuilderToken);
2785
3324
 
2786
3325
  // Eloquent/Model.ts
2787
3326
  import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
2788
- import { DatabaseManager as DatabaseManager2 } from "@orieljs/contracts";
2789
- import { Collection as Collection11 } from "@orieljs/collections";
3327
+ import { DatabaseManager as DatabaseManager2, Hasher } from "@orieljs/contracts";
3328
+ import { Collection as Collection10 } from "@orieljs/collections";
2790
3329
  import { currentContainer as currentContainer3, inject } from "@orieljs/container";
2791
- import { Str as Str5 } from "@orieljs/support";
3330
+ import { Str as Str6 } from "@orieljs/support";
2792
3331
 
2793
3332
  // Eloquent/Builder.ts
2794
3333
  import { Collection as Collection4 } from "@orieljs/collections";
@@ -2832,6 +3371,8 @@ var Builder2 = class extends Builder {
2832
3371
  scopes = /* @__PURE__ */ new Map();
2833
3372
  removedScopes = [];
2834
3373
  eagerLoad = /* @__PURE__ */ new Map();
3374
+ /** Casts for the selected columns (withCasts()), merged into every model this query hydrates. */
3375
+ selectCasts = {};
2835
3376
  constructor(model) {
2836
3377
  super(model.getConnection(), model.getTable());
2837
3378
  this.model = model;
@@ -2925,6 +3466,36 @@ var Builder2 = class extends Builder {
2925
3466
  whereBetween(column, values) {
2926
3467
  return super.whereBetween(column, values);
2927
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
+ }
2928
3499
  whereLike(column, value, caseSensitive = false, boolean = "and", not = false) {
2929
3500
  return super.whereLike(column, value, caseSensitive, boolean, not);
2930
3501
  }
@@ -2960,11 +3531,25 @@ var Builder2 = class extends Builder {
2960
3531
  return super.where(this.model.getQualifiedKeyName(), "!=", id);
2961
3532
  }
2962
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
+ }
2963
3548
  /** Runs the query, hydrates models, fires their retrieved events and eager loads the with() relations. */
2964
3549
  async runSelect() {
2965
3550
  const query = this.applyScopes();
2966
3551
  const rows = await Builder.prototype.runSelect.call(query);
2967
- const models = this.hydrate(rows);
3552
+ const models = query.hydrate(rows);
2968
3553
  if (models.length && this.model.hasModelListeners("retrieved")) {
2969
3554
  for (const model of models) await model.fireModelEvent("retrieved", false);
2970
3555
  }
@@ -3045,17 +3630,66 @@ var Builder2 = class extends Builder {
3045
3630
  * withCount('comments as approved_count'). Global scopes of the related model (soft deletes) apply.
3046
3631
  */
3047
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;
3048
3664
  if (!this.columns.length) this.columns = [`${this.model.getTable()}.*`];
3049
- for (const [spec, constraint] of this.normalizeRelationSpecs(relations)) {
3050
- const [name = "", alias] = spec.split(/\s+as\s+/i);
3051
- const relation = this.getRelation(name.trim());
3052
- const query = relation.getRelationExistenceCountQuery(relation.getRelated().newQueryWithoutRelationships(), this);
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]);
3053
3672
  query.wheres.push(...relation.wheres);
3054
3673
  if (constraint) query.callScope((q) => constraint(q));
3055
- this.selectSub(query.applyScopes(), alias?.trim() ?? `${Str2.snake(name.trim())}_count`);
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
+ }
3056
3685
  }
3057
3686
  return this;
3058
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
+ }
3059
3693
  /**
3060
3694
  * Rows that have related rows: has('comments'), has('comments', '>=', 3), has('comments.author').
3061
3695
  * Uses `exists (…)` for the common "at least one"/"none" cases and a count subquery otherwise.
@@ -3111,7 +3745,11 @@ var Builder2 = class extends Builder {
3111
3745
  }
3112
3746
  /** Models from raw rows, marked as existing. */
3113
3747
  hydrate(rows) {
3114
- return rows.map((row) => this.model.newFromBuilder(row));
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
+ });
3115
3753
  }
3116
3754
  async aggregate(fn, column) {
3117
3755
  return Builder.prototype.aggregate.call(this.applyScopes(), fn, column);
@@ -3126,12 +3764,19 @@ var Builder2 = class extends Builder {
3126
3764
  const key = column.includes(".") ? column.slice(column.lastIndexOf(".") + 1) : column;
3127
3765
  return new Collection4(rows.map((row) => this.model.newInstance().setRawAttributes({ [key]: row[key] }).getAttribute(key)));
3128
3766
  }
3767
+ /** Whether `id` can't be one of the model's unique ids (not a UUID for HasUuids): it matches no row. */
3768
+ isMalformedKey(id) {
3769
+ return this.model.uniqueIds().includes(this.model.getKeyName()) && !this.model.isValidUniqueId(id);
3770
+ }
3771
+ /** A malformed unique id (HasUuids, HasUlids) finds nothing without a query, as route model binding does. */
3129
3772
  async find(id) {
3773
+ if (this.isMalformedKey(id)) return void 0;
3130
3774
  return this.clone().whereKey(id).first();
3131
3775
  }
3132
3776
  async findMany(ids) {
3133
- if (!ids.length) return new Collection4();
3134
- return this.clone().whereKey([...ids]).get();
3777
+ const keys = ids.filter((id) => !this.isMalformedKey(id));
3778
+ if (!keys.length) return this.model.newCollection([]);
3779
+ return this.clone().whereKey(keys).get();
3135
3780
  }
3136
3781
  async findOrFail(id) {
3137
3782
  if (Array.isArray(id)) {
@@ -3253,6 +3898,7 @@ var Builder2 = class extends Builder {
3253
3898
  copy.scopes = new Map(this.scopes);
3254
3899
  copy.removedScopes = [...this.removedScopes];
3255
3900
  copy.eagerLoad = new Map(this.eagerLoad);
3901
+ copy.selectCasts = { ...this.selectCasts };
3256
3902
  return new Proxy(copy, handler);
3257
3903
  }
3258
3904
  /** Nested where groups get a builder of the same model (without global scopes), so local scopes work inside them. */
@@ -3277,6 +3923,7 @@ import { Collection as Collection5 } from "@orieljs/collections";
3277
3923
  var JSON_CASTS = /* @__PURE__ */ new Set(["array", "json", "object", "collection"]);
3278
3924
  var DATE_CASTS = /* @__PURE__ */ new Set(["date", "datetime", "immutable_date", "immutable_datetime"]);
3279
3925
  var PRIMITIVE_CASTS = /* @__PURE__ */ new Set(["int", "integer", "float", "double", "real", "string", "bool", "boolean", "timestamp"]);
3926
+ var HASHED_CAST = "hashed";
3280
3927
  var isCustom = (cast) => typeof cast === "object" && typeof cast.get === "function" && typeof cast.set === "function";
3281
3928
  var isCustomClass = (cast) => typeof cast === "function";
3282
3929
  var isEnum = (cast) => typeof cast === "object" && !isCustom(cast);
@@ -3292,8 +3939,9 @@ function enumValues(cast) {
3292
3939
  }
3293
3940
  var isJsonCast = (cast) => typeof cast === "string" && JSON_CASTS.has(cast);
3294
3941
  var isDateCast = (cast) => typeof cast === "string" && DATE_CASTS.has(cast);
3942
+ var isHashedCast = (cast) => cast === HASHED_CAST;
3295
3943
  var decimalPlaces = (cast) => cast.startsWith("decimal:") ? Number(cast.slice(8)) : void 0;
3296
- 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);
3297
3945
  function assertBuiltInCast(cast, key, className) {
3298
3946
  if (!isBuiltInCast(cast)) throw new InvalidCastError(className, key, cast);
3299
3947
  }
@@ -3382,12 +4030,207 @@ function isEquivalent(cast, current, original, model, key, className) {
3382
4030
  return numeric(current) && numeric(original) && Number(current) === Number(original);
3383
4031
  }
3384
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
+
3385
4228
  // Eloquent/Factories/Factory.ts
3386
4229
  import { existsSync, readdirSync } from "fs";
3387
- import { join as join3 } from "path";
4230
+ import { join as join4 } from "path";
3388
4231
  import { pathToFileURL } from "url";
3389
- import { Collection as Collection8 } from "@orieljs/collections";
3390
- import { Str as Str4 } from "@orieljs/support";
4232
+ import { Collection as Collection9 } from "@orieljs/collections";
4233
+ import { Str as Str5 } from "@orieljs/support";
3391
4234
 
3392
4235
  // Eloquent/Relations/BelongsTo.ts
3393
4236
  import { Str as Str3 } from "@orieljs/support";
@@ -3552,7 +4395,7 @@ var BelongsTo = class extends Relation {
3552
4395
  };
3553
4396
 
3554
4397
  // Eloquent/Relations/BelongsToMany.ts
3555
- import { Collection as Collection6 } from "@orieljs/collections";
4398
+ import { Collection as Collection7 } from "@orieljs/collections";
3556
4399
  var BelongsToMany = class extends Relation {
3557
4400
  constructor(related, parent, table, foreignPivotKey, relatedPivotKey, parentKey, relatedKey) {
3558
4401
  super(related, parent);
@@ -3620,10 +4463,10 @@ var BelongsToMany = class extends Relation {
3620
4463
  }
3621
4464
  async getResults() {
3622
4465
  const key = this.getParentKey();
3623
- return key === null || key === void 0 ? new Collection6() : this.get();
4466
+ return key === null || key === void 0 ? this.getRelated().newCollection() : this.get();
3624
4467
  }
3625
4468
  initRelation(models, relation) {
3626
- for (const model of models) model.setRelation(relation, new Collection6());
4469
+ for (const model of models) model.setRelation(relation, this.getRelated().newCollection());
3627
4470
  return models;
3628
4471
  }
3629
4472
  match(models, results, relation) {
@@ -3634,7 +4477,7 @@ var BelongsToMany = class extends Relation {
3634
4477
  if (group) group.push(result);
3635
4478
  else dictionary.set(key, [result]);
3636
4479
  }
3637
- for (const model of models) model.setRelation(relation, new Collection6(dictionary.get(String(model.getAttribute(this.parentKey))) ?? []));
4480
+ for (const model of models) model.setRelation(relation, this.getRelated().newCollection(dictionary.get(String(model.getAttribute(this.parentKey))) ?? []));
3638
4481
  return models;
3639
4482
  }
3640
4483
  getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
@@ -3650,9 +4493,9 @@ var BelongsToMany = class extends Relation {
3650
4493
  async detach(ids) {
3651
4494
  const query = this.newPivotQuery().where(this.foreignPivotKey, "=", this.getParentKey());
3652
4495
  if (ids !== void 0) {
3653
- const list2 = [...this.parseIds(ids).keys()];
3654
- if (!list2.length) return 0;
3655
- query.whereIn(this.relatedPivotKey, list2);
4496
+ const list3 = [...this.parseIds(ids).keys()];
4497
+ if (!list3.length) return 0;
4498
+ query.whereIn(this.relatedPivotKey, list3);
3656
4499
  }
3657
4500
  return query.delete();
3658
4501
  }
@@ -3756,7 +4599,7 @@ var BelongsToMany = class extends Relation {
3756
4599
  /** ids → Map(id → extra pivot attributes). Models become their related key. */
3757
4600
  parseIds(ids) {
3758
4601
  const parsed = /* @__PURE__ */ new Map();
3759
- if (ids instanceof Collection6) ids = ids.all();
4602
+ if (ids instanceof Collection7) ids = ids.all();
3760
4603
  if (Array.isArray(ids)) {
3761
4604
  for (const id of ids) parsed.set(this.idOf(id), {});
3762
4605
  } else if (ids !== null && typeof ids === "object" && !this.isModel(ids)) {
@@ -3779,6 +4622,7 @@ var BelongsToMany = class extends Relation {
3779
4622
  };
3780
4623
 
3781
4624
  // Eloquent/Relations/HasOneOrMany.ts
4625
+ import { Str as Str4 } from "@orieljs/support";
3782
4626
  var HasOneOrMany = class extends Relation {
3783
4627
  /**
3784
4628
  * @param foreignKey the qualified foreign key on the related table ('comments.post_id')
@@ -3795,6 +4639,8 @@ var HasOneOrMany = class extends Relation {
3795
4639
  foreignKey;
3796
4640
  localKey;
3797
4641
  morph;
4642
+ /** The relation on each related model that chaperone() points back at the parent. */
4643
+ inverseRelationship;
3798
4644
  /** 'post_id' */
3799
4645
  getForeignKeyName() {
3800
4646
  return this.foreignKey.slice(this.foreignKey.lastIndexOf(".") + 1);
@@ -3816,6 +4662,61 @@ var HasOneOrMany = class extends Relation {
3816
4662
  getMorphClass() {
3817
4663
  return this.morph?.value;
3818
4664
  }
4665
+ /**
4666
+ * Laravel's chaperone(): every related model this relation loads, eagerly or lazily, or makes, gets the parent as
4667
+ * its `relation` (guessed when not given: post_id → post, the parent's class, owner), so reading it needs no query:
4668
+ * `comments() { return this.hasMany(Comment).chaperone() }`.
4669
+ */
4670
+ chaperone(relation) {
4671
+ const name = relation ?? this.guessInverseRelation();
4672
+ if (name === void 0 || !this.model.isRelation(name)) throw new RelationNotFoundError(this.model.constructor.name, name ?? "null");
4673
+ this.inverseRelationship = name;
4674
+ return this;
4675
+ }
4676
+ /** Laravel's inverse(): chaperone() under its other name. */
4677
+ inverse(relation) {
4678
+ return this.chaperone(relation);
4679
+ }
4680
+ withoutChaperone() {
4681
+ this.inverseRelationship = void 0;
4682
+ return this;
4683
+ }
4684
+ withoutInverse() {
4685
+ return this.withoutChaperone();
4686
+ }
4687
+ getInverseRelationship() {
4688
+ return this.inverseRelationship;
4689
+ }
4690
+ /** The first of the possible names that is a relation of the related model. */
4691
+ guessInverseRelation() {
4692
+ return this.getPossibleInverseRelations().find((name) => this.model.isRelation(name));
4693
+ }
4694
+ /** Laravel's candidates: the morph name, the foreign key without the parent's key, the parent's class, owner, parent. */
4695
+ getPossibleInverseRelations() {
4696
+ const key = this.parent.getKeyName();
4697
+ const names = [
4698
+ this.morph ? Str4.beforeLast(this.getMorphType(), "_type") : "",
4699
+ Str4.camel(Str4.beforeLast(this.getForeignKeyName(), key)),
4700
+ Str4.camel(Str4.beforeLast(this.parent.getForeignKey(), key)),
4701
+ Str4.camel(this.parent.constructor.name),
4702
+ "owner",
4703
+ this.parent.constructor === this.model.constructor ? "parent" : ""
4704
+ ];
4705
+ return [...new Set(names.filter((name) => name !== ""))];
4706
+ }
4707
+ /** Sets the parent on a related model, when chaperone() named the relation. */
4708
+ applyInverseRelationToModel(model, parent = this.parent) {
4709
+ if (model && this.inverseRelationship !== void 0) model.setRelation(this.inverseRelationship, parent);
4710
+ return model;
4711
+ }
4712
+ applyInverseRelationToMany(models, parent = this.parent) {
4713
+ for (const model of models) this.applyInverseRelationToModel(model, parent);
4714
+ return models;
4715
+ }
4716
+ /** The relation query's rows (get(), first(), paginate(), …), pointing back at the parent with chaperone(). */
4717
+ async runSelect() {
4718
+ return this.applyInverseRelationToMany(await super.runSelect());
4719
+ }
3819
4720
  addConstraints() {
3820
4721
  this.where(this.foreignKey, "=", this.getParentKey());
3821
4722
  this.whereNotNull(this.foreignKey);
@@ -3849,7 +4750,7 @@ var HasOneOrMany = class extends Relation {
3849
4750
  setForeignAttributes(model) {
3850
4751
  model.setAttribute(this.getForeignKeyName(), this.getParentKey());
3851
4752
  if (this.morph) model.setAttribute(this.getMorphType(), this.morph.value);
3852
- return model;
4753
+ return this.applyInverseRelationToModel(model);
3853
4754
  }
3854
4755
  async saveMany(models) {
3855
4756
  const saved = [];
@@ -3869,7 +4770,7 @@ var HasOneOrMany = class extends Relation {
3869
4770
  };
3870
4771
 
3871
4772
  // Eloquent/Relations/MorphTo.ts
3872
- import { Collection as Collection7 } from "@orieljs/collections";
4773
+ import { Collection as Collection8 } from "@orieljs/collections";
3873
4774
  var MorphTo = class extends BelongsTo {
3874
4775
  /**
3875
4776
  * @param related an instance of the current type's class (the child's own class when the type is empty)
@@ -3931,7 +4832,7 @@ var MorphTo = class extends BelongsTo {
3931
4832
  results.push(result);
3932
4833
  }
3933
4834
  }
3934
- return new Collection7(results);
4835
+ return new Collection8(results);
3935
4836
  }
3936
4837
  match(models, results, relation) {
3937
4838
  for (const result of results) {
@@ -4004,13 +4905,13 @@ var Factory = class _Factory {
4004
4905
  }
4005
4906
  /** Creates related models for each created model: has(Post.factory().count(3)) (relationship default: 'posts'). */
4006
4907
  has(factory, relationship, pivot = {}) {
4007
- const name = relationship ?? Str4.camel(Str4.plural(new factory.model().constructor.name));
4908
+ const name = relationship ?? Str5.camel(Str5.plural(new factory.model().constructor.name));
4008
4909
  return this.newInstance({ hasRelations: [...this.hasRelations, { factory, relationship: name, pivot }] });
4009
4910
  }
4010
4911
  /** Sets a belongsTo parent: for(User.factory()) or for(user) (relationship default: 'user'). Created once. */
4011
4912
  for(parent, relationship) {
4012
4913
  const cls = parent instanceof Model ? parent.constructor : new parent.model().constructor;
4013
- return this.newInstance({ forRelations: [...this.forRelations, { parent, relationship: relationship ?? Str4.camel(cls.name) }] });
4914
+ return this.newInstance({ forRelations: [...this.forRelations, { parent, relationship: relationship ?? Str5.camel(cls.name) }] });
4014
4915
  }
4015
4916
  afterMaking(callback) {
4016
4917
  return this.newInstance({ afterMakingCallbacks: [...this.afterMakingCallbacks, callback] });
@@ -4047,10 +4948,10 @@ var Factory = class _Factory {
4047
4948
  }
4048
4949
  /** One model per record (or `count` models). */
4049
4950
  async createMany(records) {
4050
- const list2 = typeof records === "number" ? Array.from({ length: records }, () => ({})) : records;
4951
+ const list3 = typeof records === "number" ? Array.from({ length: records }, () => ({})) : records;
4051
4952
  const created = [];
4052
- for (const record of list2) created.push(await this.createOne(record));
4053
- return new Collection8(created);
4953
+ for (const record of list3) created.push(await this.createOne(record));
4954
+ return new Collection9(created);
4054
4955
  }
4055
4956
  newInstance(changes) {
4056
4957
  const copy = Object.create(Object.getPrototypeOf(this));
@@ -4096,7 +4997,7 @@ var Factory = class _Factory {
4096
4997
  const relation = this.relationOn(model, relationship);
4097
4998
  if (relation instanceof BelongsToMany) {
4098
4999
  const related = await factory.create();
4099
- await relation.attach(related instanceof Collection8 ? related.all() : related, pivot);
5000
+ await relation.attach(related instanceof Collection9 ? related.all() : related, pivot);
4100
5001
  } else if (relation instanceof HasOneOrMany) {
4101
5002
  const foreign = { [relation.getForeignKeyName()]: relation.getParentKey() };
4102
5003
  if (relation.morph) foreign[relation.getMorphType()] = relation.getMorphClass();
@@ -4110,14 +5011,14 @@ var Factory = class _Factory {
4110
5011
  return model.getRelationInstance(relationship);
4111
5012
  }
4112
5013
  result(models) {
4113
- return this.countValue === void 0 ? models[0] : new Collection8(models);
5014
+ return this.countValue === void 0 ? models[0] : new Collection9(models);
4114
5015
  }
4115
5016
  };
4116
5017
  async function discoverFactories(path) {
4117
5018
  if (!existsSync(path)) return;
4118
5019
  for (const file of readdirSync(path).sort()) {
4119
5020
  if (!/\.(ts|js|mts|mjs)$/.test(file) || /\.d\.[mc]?ts$/.test(file)) continue;
4120
- const module = await import(pathToFileURL(join3(path, file)).href);
5021
+ const module = await import(pathToFileURL(join4(path, file)).href);
4121
5022
  for (const exported of Object.values(module)) {
4122
5023
  if (typeof exported === "function" && exported.prototype instanceof Factory) {
4123
5024
  Factory.register(exported);
@@ -4168,27 +5069,26 @@ function modelEventsMuted() {
4168
5069
  }
4169
5070
 
4170
5071
  // Eloquent/Relations/HasMany.ts
4171
- import { Collection as Collection9 } from "@orieljs/collections";
4172
5072
  var HasMany = class extends HasOneOrMany {
4173
5073
  async getResults() {
4174
5074
  const key = this.getParentKey();
4175
- return key === null || key === void 0 ? new Collection9() : this.get();
5075
+ return key === null || key === void 0 ? this.getRelated().newCollection() : this.get();
4176
5076
  }
4177
5077
  initRelation(models, relation) {
4178
- for (const model of models) model.setRelation(relation, new Collection9());
5078
+ for (const model of models) model.setRelation(relation, this.getRelated().newCollection());
4179
5079
  return models;
4180
5080
  }
4181
5081
  match(models, results, relation) {
4182
5082
  const dictionary = this.buildDictionary(results);
4183
5083
  for (const model of models) {
4184
- model.setRelation(relation, new Collection9(dictionary.get(String(model.getAttribute(this.localKey))) ?? []));
5084
+ const children = this.applyInverseRelationToMany(dictionary.get(String(model.getAttribute(this.localKey))) ?? [], model);
5085
+ model.setRelation(relation, this.getRelated().newCollection(children));
4185
5086
  }
4186
5087
  return models;
4187
5088
  }
4188
5089
  };
4189
5090
 
4190
5091
  // Eloquent/Relations/HasManyThrough.ts
4191
- import { Collection as Collection10 } from "@orieljs/collections";
4192
5092
  var THROUGH_KEY = "laravel_through_key";
4193
5093
  var HasManyThrough = class extends Relation {
4194
5094
  /**
@@ -4254,13 +5154,13 @@ var HasManyThrough = class extends Relation {
4254
5154
  }
4255
5155
  async getResults() {
4256
5156
  const key = this.parent.getAttribute(this.localKey);
4257
- return key === null || key === void 0 ? new Collection10() : this.get();
5157
+ return key === null || key === void 0 ? this.getRelated().newCollection() : this.get();
4258
5158
  }
4259
5159
  async getEager() {
4260
5160
  return this.get();
4261
5161
  }
4262
5162
  initRelation(models, relation) {
4263
- for (const model of models) model.setRelation(relation, new Collection10());
5163
+ for (const model of models) model.setRelation(relation, this.getRelated().newCollection());
4264
5164
  return models;
4265
5165
  }
4266
5166
  match(models, results, relation) {
@@ -4271,7 +5171,7 @@ var HasManyThrough = class extends Relation {
4271
5171
  if (group) group.push(result);
4272
5172
  else dictionary.set(key, [result]);
4273
5173
  }
4274
- for (const model of models) model.setRelation(relation, new Collection10(dictionary.get(String(model.getAttribute(this.localKey))) ?? []));
5174
+ for (const model of models) model.setRelation(relation, this.getRelated().newCollection(dictionary.get(String(model.getAttribute(this.localKey))) ?? []));
4275
5175
  return models;
4276
5176
  }
4277
5177
  getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
@@ -4295,7 +5195,7 @@ var HasOne = class extends HasOneOrMany {
4295
5195
  match(models, results, relation) {
4296
5196
  const dictionary = this.buildDictionary(results);
4297
5197
  for (const model of models) {
4298
- model.setRelation(relation, dictionary.get(String(model.getAttribute(this.localKey)))?.[0] ?? null);
5198
+ model.setRelation(relation, this.applyInverseRelationToModel(dictionary.get(String(model.getAttribute(this.localKey)))?.[0] ?? null, model));
4299
5199
  }
4300
5200
  return models;
4301
5201
  }
@@ -4322,7 +5222,13 @@ var MorphOne = class extends HasOne {
4322
5222
  // Eloquent/Model.ts
4323
5223
  var handler2 = {
4324
5224
  get(target, key, receiver) {
4325
- if (typeof key === "symbol" || key in target) return Reflect.get(target, key, receiver);
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
+ }
4326
5232
  return receiver.getAttribute(key);
4327
5233
  },
4328
5234
  set(target, key, value, receiver) {
@@ -4331,6 +5237,35 @@ var handler2 = {
4331
5237
  return true;
4332
5238
  }
4333
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
+ }
4334
5269
  var bootedModels = /* @__PURE__ */ new Set();
4335
5270
  var prototypes = /* @__PURE__ */ new Map();
4336
5271
  var unguardedGlobally = { value: false };
@@ -4344,7 +5279,7 @@ function installScopeProxies(cls) {
4344
5279
  for (const key of Object.getOwnPropertyNames(current)) {
4345
5280
  if (!key.startsWith("scope") || key.length <= 5) continue;
4346
5281
  if (typeof Reflect.get(current, key) !== "function") continue;
4347
- const name = Str5.lcfirst(key.slice(5));
5282
+ const name = Str6.lcfirst(key.slice(5));
4348
5283
  if (name in cls) continue;
4349
5284
  Object.defineProperty(cls, name, {
4350
5285
  configurable: true,
@@ -4361,6 +5296,12 @@ function methodOf(model, name) {
4361
5296
  const value = Reflect.get(Object.getPrototypeOf(model), name);
4362
5297
  return typeof value === "function" ? value : void 0;
4363
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
+ }
5304
+ var serializing = /* @__PURE__ */ new WeakSet();
4364
5305
  function serializeDate(date) {
4365
5306
  return date.toISOString().replace(/\.(\d{3})Z$/, ".$1000Z");
4366
5307
  }
@@ -4405,6 +5346,8 @@ var Model = class _Model {
4405
5346
  relations = {};
4406
5347
  /** Decoded json/array/object/collection values, so in-place changes are seen by save(). */
4407
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();
4408
5351
  constructor() {
4409
5352
  ;
4410
5353
  this.constructor.bootIfNotBooted();
@@ -4538,6 +5481,18 @@ var Model = class _Model {
4538
5481
  }
4539
5482
  }
4540
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
+ }
4541
5496
  /** Runs fn with model events off, for this async context only. */
4542
5497
  static withoutEvents(fn) {
4543
5498
  return withoutModelEvents(fn);
@@ -4584,11 +5539,27 @@ var Model = class _Model {
4584
5539
  static whereNotLike(column, value, caseSensitive = false) {
4585
5540
  return this.query().whereNotLike(column, value, caseSensitive);
4586
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
+ }
4587
5558
  static whereColumn(first, operatorOrSecond, second) {
4588
5559
  return this.query().whereColumn(first, operatorOrSecond, second);
4589
5560
  }
4590
- static whereRaw(sql7, bindings = []) {
4591
- return this.query().whereRaw(sql7, bindings);
5561
+ static whereRaw(sql8, bindings = []) {
5562
+ return this.query().whereRaw(sql8, bindings);
4592
5563
  }
4593
5564
  static select(...columns) {
4594
5565
  return this.query().select(...columns);
@@ -4624,6 +5595,25 @@ var Model = class _Model {
4624
5595
  static withCount(...relations) {
4625
5596
  return this.query().withCount(...relations);
4626
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
+ }
4627
5617
  static has(relation, operator = ">=", count = 1) {
4628
5618
  return this.query().has(relation, operator, count);
4629
5619
  }
@@ -4769,8 +5759,8 @@ var Model = class _Model {
4769
5759
  /** Guarded names match case-insensitively: SQLite and MySQL column names are case-insensitive. */
4770
5760
  isGuarded(key) {
4771
5761
  if (this.guarded.length === 0) return false;
4772
- const lower = key.toLowerCase();
4773
- return this.guarded.some((guarded) => guarded === "*" || guarded.toLowerCase() === lower);
5762
+ const lower2 = key.toLowerCase();
5763
+ return this.guarded.some((guarded) => guarded === "*" || guarded.toLowerCase() === lower2);
4774
5764
  }
4775
5765
  totallyGuarded() {
4776
5766
  return !_Model.isUnguarded() && this.fillable.length === 0 && this.guarded.length === 1 && this.guarded[0] === "*";
@@ -4805,6 +5795,10 @@ var Model = class _Model {
4805
5795
  const cast = this.getCasts()[key];
4806
5796
  this.castCache.delete(key);
4807
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
+ }
4808
5802
  return this;
4809
5803
  }
4810
5804
  hasGetMutator(key) {
@@ -4816,7 +5810,7 @@ var Model = class _Model {
4816
5810
  /** Every cast, including the implied ones: the incrementing key (int) and the timestamp columns (datetime). */
4817
5811
  getCasts() {
4818
5812
  const implied = {};
4819
- if (this.incrementing) implied[this.getKeyName()] = this.keyType === "int" ? "int" : "string";
5813
+ if (this.getIncrementing()) implied[this.getKeyName()] = this.getKeyType() === "int" ? "int" : "string";
4820
5814
  if (this.usesTimestamps()) {
4821
5815
  const created = this.getCreatedAtColumn();
4822
5816
  const updated = this.getUpdatedAtColumn();
@@ -4826,6 +5820,11 @@ var Model = class _Model {
4826
5820
  if (this.softDeletes) implied[this.getDeletedAtColumn()] = "datetime";
4827
5821
  return { ...implied, ...this.casts };
4828
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
+ }
4829
5828
  hasCast(key, types) {
4830
5829
  const cast = this.getCasts()[key];
4831
5830
  if (cast === void 0) return false;
@@ -4840,6 +5839,7 @@ var Model = class _Model {
4840
5839
  setRawAttributes(attributes, sync = false) {
4841
5840
  this.attributes = { ...attributes };
4842
5841
  this.castCache.clear();
5842
+ this.pendingHashes.clear();
4843
5843
  if (sync) this.syncOriginal();
4844
5844
  return this;
4845
5845
  }
@@ -4927,7 +5927,7 @@ var Model = class _Model {
4927
5927
  }
4928
5928
  }
4929
5929
  mutatorFor(kind, key) {
4930
- return methodOf(this, `${kind}${Str5.studly(key)}Attribute`);
5930
+ return methodOf(this, `${kind}${Str6.studly(key)}Attribute`);
4931
5931
  }
4932
5932
  // ---------------------------------------------------------------- keys, table and naming
4933
5933
  getKeyName() {
@@ -4939,11 +5939,34 @@ var Model = class _Model {
4939
5939
  getIncrementing() {
4940
5940
  return this.incrementing;
4941
5941
  }
5942
+ /** Whether new rows get unique string ids before `creating` (HasUuids, HasUlids). */
5943
+ usesUniqueIds() {
5944
+ return false;
5945
+ }
5946
+ /** The columns that get a unique id (HasUuids and HasUlids: the primary key). */
5947
+ uniqueIds() {
5948
+ return [];
5949
+ }
5950
+ /** A new unique id (HasUuids: a version 7 UUID; HasUlids: a lower-case ULID). */
5951
+ newUniqueId() {
5952
+ return void 0;
5953
+ }
5954
+ /** Whether a value has the shape of this model's unique ids (HasUuids: a UUID). Any value passes by default. */
5955
+ isValidUniqueId(_value) {
5956
+ return true;
5957
+ }
5958
+ /** Fills each empty unique id column with newUniqueId() (Laravel's setUniqueIds()). */
5959
+ setUniqueIds() {
5960
+ for (const column of this.uniqueIds()) {
5961
+ const value = this.getAttribute(column);
5962
+ if (value === void 0 || value === null || value === "") this.setAttribute(column, this.newUniqueId());
5963
+ }
5964
+ }
4942
5965
  getKey() {
4943
5966
  return this.getAttribute(this.getKeyName());
4944
5967
  }
4945
5968
  getTable() {
4946
- return this.table ?? Str5.snake(Str5.plural(this.constructor.name));
5969
+ return this.table ?? Str6.snake(Str6.plural(this.constructor.name));
4947
5970
  }
4948
5971
  getConnectionName() {
4949
5972
  return this.connection;
@@ -4960,7 +5983,7 @@ var Model = class _Model {
4960
5983
  }
4961
5984
  /** The conventional foreign key pointing at this model: user_id for User. */
4962
5985
  getForeignKey() {
4963
- return `${Str5.snake(this.constructor.name)}_${this.getKeyName()}`;
5986
+ return `${Str6.snake(this.constructor.name)}_${this.getKeyName()}`;
4964
5987
  }
4965
5988
  getRouteKeyName() {
4966
5989
  return this.getKeyName();
@@ -4970,11 +5993,13 @@ var Model = class _Model {
4970
5993
  }
4971
5994
  /**
4972
5995
  * The model a route parameter value points at: where <field or route key> = value (global scopes apply, so a
4973
- * soft-deleted row isn't found). A non-numeric value for an integer primary key finds nothing without a query.
5996
+ * soft-deleted row isn't found). A non-numeric value for an integer primary key, or a value that isn't a UUID
5997
+ * (ULID) for a unique id column, finds nothing without a query.
4974
5998
  */
4975
5999
  async resolveRouteBinding(value, field) {
4976
6000
  const column = field ?? this.getRouteKeyName();
4977
- if (column === this.getKeyName() && this.keyType === "int" && !/^-?\d+$/.test(value)) return void 0;
6001
+ if (column === this.getKeyName() && this.getKeyType() === "int" && !/^-?\d+$/.test(value)) return void 0;
6002
+ if (this.uniqueIds().includes(column) && !this.isValidUniqueId(value)) return void 0;
4978
6003
  return this.resolveRouteBindingQuery(this.newQuery(), value, column).first();
4979
6004
  }
4980
6005
  /** Override to customize the binding query (Laravel's resolveRouteBindingQuery()). */
@@ -5072,6 +6097,7 @@ var Model = class _Model {
5072
6097
  */
5073
6098
  async save() {
5074
6099
  const query = this.newModelQuery();
6100
+ await this.hashPendingAttributes();
5075
6101
  if (await this.fireModelEvent("saving") === false) return false;
5076
6102
  let saved;
5077
6103
  if (this.exists) saved = this.isDirty() ? await this.performUpdate(query) : true;
@@ -5079,6 +6105,28 @@ var Model = class _Model {
5079
6105
  if (saved) await this.finishSave();
5080
6106
  return saved;
5081
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
+ }
5082
6130
  /** Fills and saves an existing model. */
5083
6131
  async update(attributes = {}) {
5084
6132
  if (!this.exists) return false;
@@ -5192,8 +6240,10 @@ var Model = class _Model {
5192
6240
  if (!this.exists && created && !this.isDirty(created)) this.setAttribute(created, time);
5193
6241
  }
5194
6242
  async performInsert(query) {
6243
+ if (this.usesUniqueIds()) this.setUniqueIds();
5195
6244
  if (await this.fireModelEvent("creating") === false) return false;
5196
6245
  if (this.usesTimestamps()) this.updateTimestamps();
6246
+ await this.hashPendingAttributes();
5197
6247
  const attributes = this.getAttributes();
5198
6248
  if (this.getIncrementing()) {
5199
6249
  const id = await query.insertGetId(attributes, this.getKeyName());
@@ -5210,6 +6260,7 @@ var Model = class _Model {
5210
6260
  async performUpdate(query) {
5211
6261
  if (await this.fireModelEvent("updating") === false) return false;
5212
6262
  if (this.usesTimestamps()) this.updateTimestamps();
6263
+ await this.hashPendingAttributes();
5213
6264
  const dirty = this.getDirty();
5214
6265
  if (Object.keys(dirty).length) {
5215
6266
  await this.setKeysForSaveQuery(query).update(dirty);
@@ -5307,7 +6358,7 @@ var Model = class _Model {
5307
6358
  */
5308
6359
  belongsToMany(related, table, foreignPivotKey, relatedPivotKey, parentKey, relatedKey) {
5309
6360
  const instance = this.newRelatedInstance(related);
5310
- const joining = table ?? [Str5.snake(this.constructor.name), Str5.snake(related.name)].sort().join("_").toLowerCase();
6361
+ const joining = table ?? [Str6.snake(this.constructor.name), Str6.snake(related.name)].sort().join("_").toLowerCase();
5311
6362
  const relation = new BelongsToMany(
5312
6363
  instance,
5313
6364
  this,
@@ -5375,6 +6426,10 @@ var Model = class _Model {
5375
6426
  if (!instance.getConnectionName()) instance.setConnection(this.getConnectionName());
5376
6427
  return instance;
5377
6428
  }
6429
+ /** Whether the model has a relation method called `name` (Laravel's isRelation()). */
6430
+ isRelation(name) {
6431
+ return !(name in _Model.prototype) && methodOf(this, name) !== void 0;
6432
+ }
5378
6433
  /** Calls the relation method `name` (post.comments()) and checks that it returns a relation. */
5379
6434
  getRelationInstance(name) {
5380
6435
  if (name in _Model.prototype) throw new RelationNotFoundError(this.constructor.name, name);
@@ -5386,7 +6441,7 @@ var Model = class _Model {
5386
6441
  }
5387
6442
  /**
5388
6443
  * A loaded relation, typed from the relation method: post.getRelation('author') is User | null,
5389
- * post.getRelation('comments') is Collection<Comment>. Throws RelationNotLoadedError when it isn't loaded
6444
+ * post.getRelation('comments') is EloquentCollection<Comment>. Throws RelationNotLoadedError when it isn't loaded
5390
6445
  * (JavaScript can't lazy-load synchronously: use with(), load() or post.comments().get()).
5391
6446
  */
5392
6447
  getRelation(name) {
@@ -5395,23 +6450,48 @@ var Model = class _Model {
5395
6450
  }
5396
6451
  /** Eager loads relations onto this model: await post.load('comments.author'). */
5397
6452
  async load(...relations) {
5398
- await this.newQueryWithoutRelationships().with(...relations).eagerLoadRelations([this]);
6453
+ await this.newCollection([this]).load(...relations);
5399
6454
  return this;
5400
6455
  }
5401
6456
  /** Loads only the relations that aren't loaded yet (nested paths are followed into loaded relations). */
5402
6457
  async loadMissing(...relations) {
5403
- await loadMissingOn([this], relations);
6458
+ await this.newCollection([this]).loadMissing(...relations);
5404
6459
  return this;
5405
6460
  }
5406
6461
  /** Loads <relation>_count attributes: await post.loadCount('comments'). */
5407
6462
  async loadCount(...relations) {
5408
- const row = await this.newQueryWithoutRelationships().whereKey(this.getKey()).select(this.getKeyName()).withCount(...relations).first();
5409
- if (row) {
5410
- const counts = Object.fromEntries(Object.entries(row.getAttributes()).filter(([key]) => key !== this.getKeyName()));
5411
- this.forceFill(counts).syncOriginalAttributes(...Object.keys(counts));
5412
- }
6463
+ await this.newCollection([this]).loadCount(...relations);
5413
6464
  return this;
5414
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);
6469
+ return this;
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
+ }
5415
6495
  // ---------------------------------------------------------------- relations storage
5416
6496
  /** Stores a loaded relation (eager loading and load() use this). */
5417
6497
  setRelation(name, value) {
@@ -5469,9 +6549,18 @@ var Model = class _Model {
5469
6549
  this.appends = [.../* @__PURE__ */ new Set([...this.appends, ...attributes.flat()])];
5470
6550
  return this;
5471
6551
  }
5472
- /** Attributes (through accessors and casts, dates as ISO strings), appends and loaded relations, minus hidden ones. */
6552
+ /**
6553
+ * Attributes (through accessors and casts, dates as ISO strings), appends and loaded relations, minus hidden ones.
6554
+ * A model met again while its own toArray() runs (a child chaperone() pointed back at it) gives its attributes only.
6555
+ */
5473
6556
  toArray() {
5474
- return { ...this.attributesToArray(), ...this.relationsToArray() };
6557
+ if (serializing.has(this)) return this.attributesToArray();
6558
+ serializing.add(this);
6559
+ try {
6560
+ return { ...this.attributesToArray(), ...this.relationsToArray() };
6561
+ } finally {
6562
+ serializing.delete(this);
6563
+ }
5475
6564
  }
5476
6565
  toJSON() {
5477
6566
  return this.toArray();
@@ -5494,10 +6583,10 @@ var Model = class _Model {
5494
6583
  relationsToArray() {
5495
6584
  const result = {};
5496
6585
  for (const [name, value] of Object.entries(this.relations)) {
5497
- const key = Str5.snake(name);
6586
+ const key = Str6.snake(name);
5498
6587
  if (!this.isArrayableKey(key)) continue;
5499
6588
  if (value === null || value === void 0) result[key] = null;
5500
- else if (value instanceof Collection11) result[key] = value.toArray();
6589
+ else if (value instanceof Collection10) result[key] = value.toArray();
5501
6590
  else if (typeof value.toArray === "function") result[key] = value.toArray();
5502
6591
  else result[key] = value;
5503
6592
  }
@@ -5505,7 +6594,7 @@ var Model = class _Model {
5505
6594
  }
5506
6595
  serializeValue(value) {
5507
6596
  if (value instanceof Date) return serializeDate(value);
5508
- if (value instanceof Collection11) return value.toArray();
6597
+ if (value instanceof Collection10) return value.toArray();
5509
6598
  return value;
5510
6599
  }
5511
6600
  isArrayableKey(key) {
@@ -5518,24 +6607,10 @@ var Model = class _Model {
5518
6607
  };
5519
6608
  setModelBaseClass(Model);
5520
6609
  async function loadRelations(models, ...relations) {
5521
- const list2 = [...models];
5522
- if (!list2.length) return list2;
5523
- await list2[0].newQueryWithoutRelationships().with(...relations).eagerLoadRelations(list2);
5524
- return list2;
5525
- }
5526
- async function loadMissingOn(models, paths) {
5527
- for (const path of paths) {
5528
- const [head = "", ...rest] = path.split(".");
5529
- const missing = models.filter((model) => !model.relationLoaded(head));
5530
- if (missing.length) await loadRelations(missing, path);
5531
- if (!rest.length) continue;
5532
- const related = models.flatMap((model) => {
5533
- const value = model.getRelations()[head];
5534
- if (value instanceof Collection11) return value.all();
5535
- return value instanceof Model ? [value] : [];
5536
- });
5537
- if (related.length) await loadMissingOn(related, [rest.join(".")]);
5538
- }
6610
+ const list3 = [...models];
6611
+ if (!list3.length) return list3;
6612
+ await list3[0].newQueryWithoutRelationships().with(...relations).eagerLoadRelations(list3);
6613
+ return list3;
5539
6614
  }
5540
6615
  var Pivot = class extends Model {
5541
6616
  guarded = [];
@@ -5543,9 +6618,39 @@ var Pivot = class extends Model {
5543
6618
  timestamps = false;
5544
6619
  };
5545
6620
 
6621
+ // Eloquent/HasUniqueStringIds.ts
6622
+ import { Str as Str7 } from "@orieljs/support";
6623
+ function uniqueStringIds(Base, generate, valid) {
6624
+ return class WithUniqueStringIds extends Base {
6625
+ usesUniqueIds() {
6626
+ return true;
6627
+ }
6628
+ uniqueIds() {
6629
+ return [this.getKeyName()];
6630
+ }
6631
+ newUniqueId() {
6632
+ return generate();
6633
+ }
6634
+ isValidUniqueId(value) {
6635
+ return valid(value);
6636
+ }
6637
+ getKeyType() {
6638
+ return this.uniqueIds().includes(this.getKeyName()) ? "string" : super.getKeyType();
6639
+ }
6640
+ getIncrementing() {
6641
+ return this.uniqueIds().includes(this.getKeyName()) ? false : super.getIncrementing();
6642
+ }
6643
+ };
6644
+ }
6645
+ function HasUuids(Base) {
6646
+ return uniqueStringIds(Base, () => Str7.uuid7(), Str7.isUuid);
6647
+ }
6648
+ function HasUlids(Base) {
6649
+ return uniqueStringIds(Base, () => Str7.ulid().toLowerCase(), Str7.isUlid);
6650
+ }
6651
+
5546
6652
  // Eloquent/DatabaseNotification.ts
5547
- import { Collection as Collection12 } from "@orieljs/collections";
5548
- var DatabaseNotification = class extends Model {
6653
+ var DatabaseNotification = class extends HasUuids(Model) {
5549
6654
  table = "notifications";
5550
6655
  keyType = "string";
5551
6656
  incrementing = false;
@@ -5569,6 +6674,10 @@ var DatabaseNotification = class extends Model {
5569
6674
  unread() {
5570
6675
  return !this.read();
5571
6676
  }
6677
+ /** Queries of notifications return a DatabaseNotificationCollection (markAsRead() on all of them). */
6678
+ newCollection(models = []) {
6679
+ return new DatabaseNotificationCollection(models);
6680
+ }
5572
6681
  /** `query.read()`: only read notifications. */
5573
6682
  static scopeRead(query) {
5574
6683
  return query.whereNotNull("read_at");
@@ -5578,7 +6687,7 @@ var DatabaseNotification = class extends Model {
5578
6687
  return query.whereNull("read_at");
5579
6688
  }
5580
6689
  };
5581
- var DatabaseNotificationCollection = class extends Collection12 {
6690
+ var DatabaseNotificationCollection = class extends EloquentCollection {
5582
6691
  /** Marks every notification as read (one save each, as in Laravel). */
5583
6692
  async markAsRead() {
5584
6693
  for (const notification of this.all()) await notification.markAsRead();
@@ -5642,8 +6751,8 @@ var Migration = class {
5642
6751
 
5643
6752
  // Migrations/MigrationCreator.ts
5644
6753
  import { existsSync as existsSync2, mkdirSync, writeFileSync } from "fs";
5645
- import { join as join4 } from "path";
5646
- import { Str as Str6 } from "@orieljs/support";
6754
+ import { join as join5 } from "path";
6755
+ import { Str as Str8 } from "@orieljs/support";
5647
6756
  var MIGRATION_CREATE_STUB = `import { Migration, Schema } from '{{ importSource }}'
5648
6757
 
5649
6758
  export default class extends Migration {
@@ -5695,13 +6804,13 @@ function guessTable(migration) {
5695
6804
  return void 0;
5696
6805
  }
5697
6806
  function migrationDatePrefix(date = /* @__PURE__ */ new Date()) {
5698
- const pad2 = (value) => String(value).padStart(2, "0");
5699
- return `${date.getUTCFullYear()}_${pad2(date.getUTCMonth() + 1)}_${pad2(date.getUTCDate())}_${pad2(date.getUTCHours())}${pad2(date.getUTCMinutes())}${pad2(date.getUTCSeconds())}`;
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())}`;
5700
6809
  }
5701
6810
  var MigrationCreator = class {
5702
6811
  /** Returns the path of the new file. */
5703
6812
  create(name, path, options = {}) {
5704
- const snake = Str6.snake(name.trim());
6813
+ const snake = Str8.snake(name.trim());
5705
6814
  let table = options.table ?? options.create;
5706
6815
  let create = options.create !== void 0;
5707
6816
  if (table === void 0) {
@@ -5709,7 +6818,7 @@ var MigrationCreator = class {
5709
6818
  if (guessed) ({ table, create } = guessed);
5710
6819
  }
5711
6820
  const stub = table === void 0 ? MIGRATION_STUB : create ? MIGRATION_CREATE_STUB : MIGRATION_UPDATE_STUB;
5712
- const file = join4(path, `${migrationDatePrefix(options.date)}_${snake}.ts`);
6821
+ const file = join5(path, `${migrationDatePrefix(options.date)}_${snake}.ts`);
5713
6822
  if (existsSync2(file)) throw new LogicError(`Migration [${file}] already exists.`);
5714
6823
  mkdirSync(path, { recursive: true });
5715
6824
  writeFileSync(
@@ -5784,8 +6893,9 @@ var MigrationRepository = class {
5784
6893
 
5785
6894
  // Migrations/Migrator.ts
5786
6895
  import { existsSync as existsSync3, readdirSync as readdirSync2 } from "fs";
5787
- import { basename, extname, join as join5 } from "path";
6896
+ import { basename, extname, join as join6 } from "path";
5788
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.";
5789
6899
  var MIGRATION_FILE = /^(?!.*\.d\.[mc]?ts$).+\.(ts|js|mts|mjs)$/;
5790
6900
  var Migrator = class {
5791
6901
  constructor(manager, output = () => void 0) {
@@ -5812,7 +6922,7 @@ var Migrator = class {
5812
6922
  for (const path of paths) {
5813
6923
  if (!existsSync3(path)) continue;
5814
6924
  for (const file of readdirSync2(path)) {
5815
- if (MIGRATION_FILE.test(file)) files.push([basename(file, extname(file)), join5(path, file)]);
6925
+ if (MIGRATION_FILE.test(file)) files.push([basename(file, extname(file)), join6(path, file)]);
5816
6926
  }
5817
6927
  }
5818
6928
  return new Map(files.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
@@ -5911,10 +7021,31 @@ var Migrator = class {
5911
7021
  const run = async () => {
5912
7022
  await migration[method]();
5913
7023
  };
5914
- if (migration.withinTransaction && connection.getDriverName() !== "mysql") await connection.transaction(run);
7024
+ if (connection.getDriverName() === "sqlite") await this.runOnSqlite(connection, migration, run);
7025
+ else if (migration.withinTransaction && connection.getDriverName() !== "mysql") await connection.transaction(run);
5915
7026
  else await run();
5916
7027
  });
5917
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
+ }
5918
7049
  };
5919
7050
 
5920
7051
  // Seeder.ts
@@ -5944,13 +7075,13 @@ var Seeder = class {
5944
7075
 
5945
7076
  // Console/commands.ts
5946
7077
  import { existsSync as existsSync4 } from "fs";
5947
- import { isAbsolute, join as join6, relative as relative2 } from "path";
7078
+ import { isAbsolute, join as join7, relative as relative2 } from "path";
5948
7079
  import { pathToFileURL as pathToFileURL3 } from "url";
5949
7080
 
5950
7081
  // Types/TypeGenerator.ts
5951
7082
  import { mkdir, writeFile } from "fs/promises";
5952
7083
  import { dirname, relative, sep } from "path";
5953
- import { Str as Str7 } from "@orieljs/support";
7084
+ import { Str as Str9 } from "@orieljs/support";
5954
7085
  var INTEGER = /* @__PURE__ */ new Set(["int", "integer", "int2", "int4", "int8", "bigint", "smallint", "mediumint", "tinyint", "serial", "bigserial", "smallserial", "year"]);
5955
7086
  var FLOAT = /* @__PURE__ */ new Set(["float", "float4", "float8", "double", "double precision", "real"]);
5956
7087
  var BOOLEAN = /* @__PURE__ */ new Set(["bool", "boolean"]);
@@ -5960,7 +7091,7 @@ function castType(cast) {
5960
7091
  if (cast === void 0) return void 0;
5961
7092
  if (typeof cast === "string") {
5962
7093
  if (["int", "integer", "float", "double", "real", "timestamp"].includes(cast)) return "number";
5963
- if (cast === "string" || cast.startsWith("decimal:")) return "string";
7094
+ if (cast === "string" || cast === "hashed" || cast.startsWith("decimal:")) return "string";
5964
7095
  if (cast === "bool" || cast === "boolean") return "boolean";
5965
7096
  if (["date", "datetime", "immutable_date", "immutable_datetime"].includes(cast)) return "Date";
5966
7097
  return "unknown";
@@ -5985,7 +7116,7 @@ function accessors(model) {
5985
7116
  for (let proto = model.prototype; proto && proto !== Model.prototype; proto = Object.getPrototypeOf(proto)) {
5986
7117
  for (const key of Object.getOwnPropertyNames(proto)) {
5987
7118
  const match = /^get(.+)Attribute$/.exec(key);
5988
- if (match && typeof Reflect.get(proto, key) === "function" && !found.has(Str7.snake(match[1]))) found.set(Str7.snake(match[1]), key);
7119
+ if (match && typeof Reflect.get(proto, key) === "function" && !found.has(Str9.snake(match[1]))) found.set(Str9.snake(match[1]), key);
5989
7120
  }
5990
7121
  }
5991
7122
  return [...found];
@@ -5995,7 +7126,7 @@ function scopes(model) {
5995
7126
  for (let current = model; current && current !== Model; current = Object.getPrototypeOf(current)) {
5996
7127
  for (const key of Object.getOwnPropertyNames(current)) {
5997
7128
  if (key.startsWith("scope") && key.length > 5 && typeof Reflect.get(current, key) === "function") {
5998
- const name = Str7.lcfirst(key.slice(5));
7129
+ const name = Str9.lcfirst(key.slice(5));
5999
7130
  if (!found.has(name)) found.set(name, key);
6000
7131
  }
6001
7132
  }
@@ -6069,7 +7200,7 @@ var TypeGenerator = class {
6069
7200
 
6070
7201
  // Console/commands.ts
6071
7202
  var text = (value) => typeof value === "string" && value !== "" ? value : void 0;
6072
- var list = (value) => Array.isArray(value) ? value.map(String) : text(value) ? [String(value)] : [];
7203
+ var list2 = (value) => Array.isArray(value) ? value.map(String) : text(value) ? [String(value)] : [];
6073
7204
  var integer = (value) => {
6074
7205
  const number = Number(value ?? 0);
6075
7206
  return Number.isInteger(number) && number > 0 ? number : 0;
@@ -6085,7 +7216,7 @@ function confirmToProceed(context, command) {
6085
7216
  return false;
6086
7217
  }
6087
7218
  function migrationPaths(context, command) {
6088
- const paths = list(command.option("path"));
7219
+ const paths = list2(command.option("path"));
6089
7220
  if (!paths.length) return [context.app.databasePath("migrations")];
6090
7221
  return paths.map((path) => isAbsolute(path) ? path : context.app.basePath(path));
6091
7222
  }
@@ -6094,7 +7225,7 @@ function migrator(context, command) {
6094
7225
  }
6095
7226
  async function runSeeder(context, className, output, database) {
6096
7227
  const name = className.split("\\").pop();
6097
- const file = ["ts", "js", "mts", "mjs"].map((extension) => context.app.databasePath(join6("seeders", `${name}.${extension}`))).find(existsSync4);
7228
+ const file = ["ts", "js", "mts", "mjs"].map((extension) => context.app.databasePath(join7("seeders", `${name}.${extension}`))).find(existsSync4);
6098
7229
  if (!file) throw new LogicError(`Seeder [${name}] not found in ${context.app.databasePath("seeders")}.`);
6099
7230
  const module = await import(pathToFileURL3(file).href);
6100
7231
  const exported = module.default ?? module[name];
@@ -6104,10 +7235,15 @@ async function runSeeder(context, className, output, database) {
6104
7235
  }
6105
7236
  async function generateModelTypes(context) {
6106
7237
  if (!context.models) return void 0;
6107
- const outputFile = context.app.basePath(join6("types", "models.d.ts"));
7238
+ const outputFile = context.app.basePath(join7("types", "models.d.ts"));
6108
7239
  await new TypeGenerator({ outputFile, importSource: context.typesImportSource }).write((await context.models()).all());
6109
7240
  return relative2(context.app.basePath(), outputFile);
6110
7241
  }
7242
+ async function writeModelTypes(context, command) {
7243
+ if (context.app.isProduction() || !existsSync4(context.app.basePath("types"))) return;
7244
+ const written = await generateModelTypes(context);
7245
+ if (written) command.line(`Model types written to ${written}.`);
7246
+ }
6111
7247
  async function seedIfRequested(context, command) {
6112
7248
  const seeder = text(command.option("seeder"));
6113
7249
  if (command.option("seed") !== true && seeder === void 0) return;
@@ -6119,10 +7255,7 @@ function registerMigrationCommands(kernel, context) {
6119
7255
  if (!confirmToProceed(context, command)) return 1;
6120
7256
  await migrator(context, command).run(migrationPaths(context, command), { step: command.option("step") === true });
6121
7257
  await seedIfRequested(context, command);
6122
- if (!context.app.isProduction() && existsSync4(context.app.basePath("types"))) {
6123
- const written = await generateModelTypes(context);
6124
- if (written) command.line(`Model types written to ${written}.`);
6125
- }
7258
+ await writeModelTypes(context, command);
6126
7259
  return 0;
6127
7260
  });
6128
7261
  define(kernel, "migrate:install {--database=}", "Create the migration repository", async (command) => {
@@ -6153,12 +7286,14 @@ function registerMigrationCommands(kernel, context) {
6153
7286
  else await instance.reset(paths);
6154
7287
  await instance.run(paths);
6155
7288
  await seedIfRequested(context, command);
7289
+ await writeModelTypes(context, command);
6156
7290
  return 0;
6157
7291
  });
6158
7292
  define(kernel, "migrate:fresh {--database=} {--force} {--path=*} {--seed} {--seeder=}", "Drop all tables and re-run all migrations", async (command) => {
6159
7293
  if (!confirmToProceed(context, command)) return 1;
6160
7294
  await migrator(context, command).fresh(migrationPaths(context, command));
6161
7295
  await seedIfRequested(context, command);
7296
+ await writeModelTypes(context, command);
6162
7297
  return 0;
6163
7298
  });
6164
7299
  define(kernel, "migrate:status {--database=} {--path=*}", "Show the status of each migration", async (command) => {
@@ -6211,9 +7346,9 @@ function registerModelTypesCommand(kernel, context) {
6211
7346
 
6212
7347
  // ModelRegistry.ts
6213
7348
  import { existsSync as existsSync5, readdirSync as readdirSync3, statSync } from "fs";
6214
- import { join as join7 } from "path";
7349
+ import { join as join8 } from "path";
6215
7350
  import { pathToFileURL as pathToFileURL4 } from "url";
6216
- import { Str as Str8 } from "@orieljs/support";
7351
+ import { Str as Str10 } from "@orieljs/support";
6217
7352
  var MODEL_FILE = /^(?!.*\.d\.[mc]?ts$).+\.(ts|js|mts|mjs)$/;
6218
7353
  var ModelRegistry = class {
6219
7354
  models = /* @__PURE__ */ new Map();
@@ -6239,7 +7374,7 @@ var ModelRegistry = class {
6239
7374
  }
6240
7375
  /** A model by class name or route parameter name: 'Post', 'post', 'blog_post' and 'blogPost' find BlogPost. */
6241
7376
  get(name) {
6242
- return this.models.get(name) ?? this.models.get(Str8.studly(name));
7377
+ return this.models.get(name) ?? this.models.get(Str10.studly(name));
6243
7378
  }
6244
7379
  resolve(name) {
6245
7380
  return this.get(name)?.model;
@@ -6255,7 +7390,7 @@ function listFiles(directory) {
6255
7390
  if (!existsSync5(directory)) return [];
6256
7391
  const files = [];
6257
7392
  for (const entry of readdirSync3(directory).sort()) {
6258
- const path = join7(directory, entry);
7393
+ const path = join8(directory, entry);
6259
7394
  if (statSync(path).isDirectory()) files.push(...listFiles(path));
6260
7395
  else if (MODEL_FILE.test(entry)) files.push(path);
6261
7396
  }
@@ -6723,11 +7858,15 @@ var DatabaseServiceProvider = class extends ServiceProvider {
6723
7858
  Model.clearBootedModels();
6724
7859
  this.mergeConfigFrom(databaseConfigDefaults(this.app), "database");
6725
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
+ });
6726
7864
  this.app.singleton(ModelRegistry);
6727
7865
  this.app.singleton(RouteModelResolver, () => new RouteModelResolverImpl(this.app.make(ModelRegistry)));
6728
7866
  this.app.bind(SchemaBuilderToken, () => this.manager().getSchemaBuilder());
6729
7867
  }
6730
7868
  async boot() {
7869
+ Model.warnOnRelationPropertyAccess(!this.app.isProduction());
6731
7870
  usePaginationResolvers();
6732
7871
  const registry2 = this.app.make(ModelRegistry);
6733
7872
  const classes = this.app.bound(ClassRegistry2) ? this.app.make(ClassRegistry2) : void 0;
@@ -6765,6 +7904,7 @@ export {
6765
7904
  DatabaseNotificationCollection,
6766
7905
  DatabaseNotificationsRelation,
6767
7906
  DatabaseServiceProvider,
7907
+ EloquentCollection,
6768
7908
  Expression,
6769
7909
  Factory,
6770
7910
  Faker,
@@ -6777,6 +7917,8 @@ export {
6777
7917
  HasManyThrough,
6778
7918
  HasOne,
6779
7919
  HasOneOrMany,
7920
+ HasUlids,
7921
+ HasUuids,
6780
7922
  InvalidCastError,
6781
7923
  JoinClause,
6782
7924
  LengthAwarePaginator,
@@ -6834,6 +7976,7 @@ export {
6834
7976
  isDateCast,
6835
7977
  isEquivalent,
6836
7978
  isJsonCast,
7979
+ isTableRebuild,
6837
7980
  loadRelations,
6838
7981
  migrationDatePrefix,
6839
7982
  modelEventName,