@orieljs/database 0.1.0-alpha.1 → 0.1.0-alpha.10

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
  }
@@ -539,14 +548,17 @@ var LengthAwarePaginator = class extends AbstractPaginator {
539
548
  nextPageUrl() {
540
549
  return this.hasMorePages() ? this.url(this.currentPageValue + 1) : null;
541
550
  }
542
- /** The page links Laravel renders: previous, the page window with '...' gaps, next. */
551
+ /**
552
+ * The page links Laravel renders: previous, the page window with '...' gaps, next. The labels are plain text
553
+ * ("« Previous", "Next »"), not Laravel's `«` entities, so a page can print them as text.
554
+ */
543
555
  linkCollection() {
544
- const links = [{ url: this.previousPageUrl(), label: "« Previous", active: false }];
556
+ const links = [{ url: this.previousPageUrl(), label: "\xAB Previous", active: false }];
545
557
  for (const element of this.elements()) {
546
558
  if (element === "...") links.push({ url: null, label: "...", active: false });
547
559
  else for (const [page, url] of element) links.push({ url, label: String(page), active: page === this.currentPageValue });
548
560
  }
549
- links.push({ url: this.nextPageUrl(), label: "Next »", active: false });
561
+ links.push({ url: this.nextPageUrl(), label: "Next \xBB", active: false });
550
562
  return links;
551
563
  }
552
564
  /** Laravel's UrlWindow: the first pages, the slider around the current page and the last pages, with '...' between. */
@@ -611,6 +623,9 @@ var Paginator = class extends AbstractPaginator {
611
623
  hasMorePages() {
612
624
  return this.hasMore;
613
625
  }
626
+ through(callback) {
627
+ return super.through(callback);
628
+ }
614
629
  hasPages() {
615
630
  return this.currentPageValue !== 1 || this.hasMore;
616
631
  }
@@ -677,6 +692,10 @@ var EMPTY = sql2.raw("");
677
692
  var isSqlFragment = (value) => typeof value === "object" && value !== null && typeof value.toOperationNode === "function";
678
693
  var join = (parts, separator = ", ") => sql2.join(parts, sql2.raw(separator));
679
694
  var clauses = (parts) => join(parts.filter((part) => part !== void 0), " ");
695
+ function likeToGlob(pattern) {
696
+ return pattern.replaceAll("*", "[*]").replaceAll("?", "[?]").replaceAll("%", "*").replaceAll("_", "?");
697
+ }
698
+ var SQLITE_DATE_FORMATS = { date: "%Y-%m-%d", time: "%H:%M:%S", day: "%d", month: "%m", year: "%Y" };
680
699
  var Grammar = class {
681
700
  constructor(driver) {
682
701
  this.driver = driver;
@@ -718,7 +737,7 @@ var Grammar = class {
718
737
  return join(columns.map((column) => this.wrap(column)));
719
738
  }
720
739
  compileSelect(query) {
721
- 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("*");
722
741
  return clauses([query.distinctRows ? sql2`select distinct ${columns}` : sql2`select ${columns}`, this.compileComponents(query)]);
723
742
  }
724
743
  /** Everything after the select list: from, joins, where, group by, having, order by, limit/offset, lock. */
@@ -757,6 +776,8 @@ var Grammar = class {
757
776
  }
758
777
  case "null":
759
778
  return sql2`${this.wrap(where.column)} ${sql2.raw(where.not ? "is not null" : "is null")}`;
779
+ case "like":
780
+ return this.compileWhereLike(where);
760
781
  case "between":
761
782
  return sql2`${this.wrap(where.column)} ${sql2.raw(where.not ? "not between" : "between")} ${this.parameter(where.values[0])} and ${this.parameter(where.values[1])}`;
762
783
  case "column":
@@ -767,7 +788,36 @@ var Grammar = class {
767
788
  return sql2`${sql2.raw(where.not ? "not exists" : "exists")} (${this.compileSelect(where.query)})`;
768
789
  case "raw":
769
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}`;
770
807
  }
808
+ return sql2`${sql2.raw(where.part)}(${column}) ${operator} ${value}`;
809
+ }
810
+ /**
811
+ * whereLike() per driver, as Laravel 12's grammars: Postgres compares the column as text with ilike (like when
812
+ * case-sensitive); MySQL uses like (like binary); SQLite uses like, or glob with the pattern translated.
813
+ */
814
+ compileWhereLike(where) {
815
+ const not = where.not ? "not " : "";
816
+ const column = this.wrap(where.column);
817
+ if (this.driver === "pgsql") return sql2`${column}::text ${sql2.raw(`${not}${where.caseSensitive ? "like" : "ilike"}`)} ${this.parameter(where.value)}`;
818
+ if (this.driver === "mysql") return sql2`${column} ${sql2.raw(`${not}${where.caseSensitive ? "like binary" : "like"}`)} ${this.parameter(where.value)}`;
819
+ if (where.caseSensitive) return sql2`${column} ${sql2.raw(`${not}glob`)} ${this.parameter(likeToGlob(where.value))}`;
820
+ return sql2`${column} ${sql2.raw(`${not}like`)} ${this.parameter(where.value)}`;
771
821
  }
772
822
  compileJoin(joinClause) {
773
823
  if (joinClause.joinType === "cross") return sql2`cross join ${this.wrapTable(joinClause.table)}`;
@@ -914,6 +964,19 @@ function keyOf(item, alias) {
914
964
  }
915
965
  return value;
916
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
+ }
917
980
  var isRow = (value) => typeof value === "object" && value !== null && !(value instanceof Expression) && !(value instanceof Builder) && !Array.isArray(value);
918
981
  function columnKey(column) {
919
982
  const alias = /\s+as\s+/i.exec(column);
@@ -1023,6 +1086,60 @@ var Builder = class _Builder {
1023
1086
  this.wheres.push({ type: "between", column, values, not: true, boolean: "and" });
1024
1087
  return this;
1025
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
+ }
1124
+ /**
1125
+ * Laravel's whereLike(): the value is the pattern, `%` and `_` included (`whereLike('title', `%${term}%`)`).
1126
+ * Case-insensitive unless caseSensitive: ilike on Postgres, like on MySQL and SQLite (their like already ignores
1127
+ * case: MySQL through the column's collation, SQLite for ASCII letters). Case-sensitive is like on Postgres,
1128
+ * like binary on MySQL and glob on SQLite.
1129
+ */
1130
+ whereLike(column, value, caseSensitive = false, boolean = "and", not = false) {
1131
+ this.wheres.push({ type: "like", column, value, caseSensitive, not, boolean });
1132
+ return this;
1133
+ }
1134
+ orWhereLike(column, value, caseSensitive = false) {
1135
+ return this.whereLike(column, value, caseSensitive, "or");
1136
+ }
1137
+ whereNotLike(column, value, caseSensitive = false, boolean = "and") {
1138
+ return this.whereLike(column, value, caseSensitive, boolean, true);
1139
+ }
1140
+ orWhereNotLike(column, value, caseSensitive = false) {
1141
+ return this.whereNotLike(column, value, caseSensitive, "or");
1142
+ }
1026
1143
  /** Compares two columns: whereColumn('updated_at', '>', 'created_at'). */
1027
1144
  whereColumn(first, operatorOrSecond, second, boolean = "and") {
1028
1145
  const [operator, other] = second === void 0 ? ["=", operatorOrSecond] : [operatorOrSecond, second];
@@ -1033,12 +1150,12 @@ var Builder = class _Builder {
1033
1150
  orWhereColumn(first, operatorOrSecond, second) {
1034
1151
  return this.whereColumn(first, operatorOrSecond, second, "or");
1035
1152
  }
1036
- whereRaw(sql7, bindings = [], boolean = "and") {
1037
- 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 });
1038
1155
  return this;
1039
1156
  }
1040
- orWhereRaw(sql7, bindings = []) {
1041
- return this.whereRaw(sql7, bindings, "or");
1157
+ orWhereRaw(sql8, bindings = []) {
1158
+ return this.whereRaw(sql8, bindings, "or");
1042
1159
  }
1043
1160
  whereExists(query, boolean = "and", not = false) {
1044
1161
  const sub = query instanceof _Builder ? query : this.subQuery(query);
@@ -1089,8 +1206,8 @@ var Builder = class _Builder {
1089
1206
  this.havings.push({ column, operator, value: operand, boolean });
1090
1207
  return this;
1091
1208
  }
1092
- havingRaw(sql7, bindings = [], boolean = "and") {
1093
- 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 });
1094
1211
  return this;
1095
1212
  }
1096
1213
  orderBy(column, direction = "asc") {
@@ -1112,8 +1229,8 @@ var Builder = class _Builder {
1112
1229
  this.orders.push({ raw: this.grammar.compileRandom() });
1113
1230
  return this;
1114
1231
  }
1115
- orderByRaw(sql7, bindings = []) {
1116
- this.orders.push({ raw: new Expression(sql7, bindings) });
1232
+ orderByRaw(sql8, bindings = []) {
1233
+ this.orders.push({ raw: new Expression(sql8, bindings) });
1117
1234
  return this;
1118
1235
  }
1119
1236
  /** Removes existing orders, optionally adding a new one. */
@@ -1146,10 +1263,16 @@ var Builder = class _Builder {
1146
1263
  this.lockMode = "share";
1147
1264
  return this;
1148
1265
  }
1149
- /** Calls callback(this, value) when value is truthy (or the default callback otherwise). */
1150
1266
  when(value, callback, otherwise) {
1151
- if (value) callback(this, value);
1152
- else otherwise?.(this, value);
1267
+ const resolved = typeof value === "function" ? value(this) : value;
1268
+ if (resolved) callback(this, resolved);
1269
+ else otherwise?.(this, resolved);
1270
+ return this;
1271
+ }
1272
+ unless(value, callback, otherwise) {
1273
+ const resolved = typeof value === "function" ? value(this) : value;
1274
+ if (!resolved) callback(this, resolved);
1275
+ else otherwise?.(this, resolved);
1153
1276
  return this;
1154
1277
  }
1155
1278
  tap(callback) {
@@ -1158,7 +1281,11 @@ var Builder = class _Builder {
1158
1281
  }
1159
1282
  // ---------------------------------------------------------------- reading
1160
1283
  async get() {
1161
- 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);
1162
1289
  }
1163
1290
  /** The raw rows, without a Collection around them. */
1164
1291
  async runSelect() {
@@ -1313,7 +1440,7 @@ var Builder = class _Builder {
1313
1440
  for (let page = 1; ; page++) {
1314
1441
  const results = await this.clone().forPage(page, count).runSelect();
1315
1442
  if (!results.length) return true;
1316
- if (await callback(new Collection3(results), page) === false) return false;
1443
+ if (await callback(this.newCollection(results), page) === false) return false;
1317
1444
  if (results.length < count) return true;
1318
1445
  }
1319
1446
  }
@@ -1325,7 +1452,7 @@ var Builder = class _Builder {
1325
1452
  for (let page = 1; ; page++) {
1326
1453
  const results = await this.clone().forPageAfterId(count, lastId, key).runSelect();
1327
1454
  if (!results.length) return true;
1328
- if (await callback(new Collection3(results), page) === false) return false;
1455
+ if (await callback(this.newCollection(results), page) === false) return false;
1329
1456
  if (results.length < count) return true;
1330
1457
  lastId = keyOf(results.at(-1), aliasName);
1331
1458
  }
@@ -1456,6 +1583,13 @@ var Builder = class _Builder {
1456
1583
  this.wheres.push({ type: "basic", column: ref, operator, value, boolean });
1457
1584
  return this;
1458
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
+ }
1459
1593
  pushNull(column, not, boolean) {
1460
1594
  this.wheres.push({ type: "null", column, not, boolean });
1461
1595
  return this;
@@ -1479,10 +1613,10 @@ var JoinClause = class extends Builder {
1479
1613
 
1480
1614
  // Connection.ts
1481
1615
  import { AsyncLocalStorage } from "async_hooks";
1482
- import { Kysely, sql as sql6 } from "kysely";
1616
+ import { Kysely, sql as sql7 } from "kysely";
1483
1617
 
1484
1618
  // Schema/Builder.ts
1485
- import { sql as sql5 } from "kysely";
1619
+ import { sql as sql6 } from "kysely";
1486
1620
 
1487
1621
  // Schema/ColumnDefinition.ts
1488
1622
  var ColumnDefinition = class {
@@ -1545,6 +1679,15 @@ var ColumnDefinition = class {
1545
1679
  this.attributes.default = new Expression("CURRENT_TIMESTAMP");
1546
1680
  return this;
1547
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
+ }
1548
1691
  /** MySQL only: on update CURRENT_TIMESTAMP. */
1549
1692
  useCurrentOnUpdate() {
1550
1693
  this.attributes.onUpdate = new Expression("CURRENT_TIMESTAMP");
@@ -1788,8 +1931,8 @@ var Blueprint = class {
1788
1931
  }
1789
1932
  /** t.foreign('user_id').references('id').on('users') */
1790
1933
  foreign(columns, name) {
1791
- const list2 = [columns].flat();
1792
- 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));
1793
1936
  this.commands.push({ name: "foreign", foreign });
1794
1937
  return foreign;
1795
1938
  }
@@ -1810,8 +1953,10 @@ var Blueprint = class {
1810
1953
  dropIndex(index) {
1811
1954
  this.commands.push({ name: "dropIndex", index: this.indexNameFor("index", index) });
1812
1955
  }
1956
+ /** By name, or by columns (the conventional name; SQLite needs the columns, it doesn't keep foreign key names). */
1813
1957
  dropForeign(index) {
1814
- 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 } : {} });
1815
1960
  }
1816
1961
  /** Drops the foreign key on the column, then the column. */
1817
1962
  dropConstrainedForeignId(column) {
@@ -1841,6 +1986,14 @@ var Blueprint = class {
1841
1986
  this.commands.push({ name: "dropIfExists" });
1842
1987
  }
1843
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
+ }
1844
1997
  /** Laravel's default index name: {table}_{columns}_{type}, lowercased, with - and . replaced by _. */
1845
1998
  createIndexName(type, columns) {
1846
1999
  return `${this.table}_${columns.join("_")}_${type}`.toLowerCase().replace(/[-.]/g, "_");
@@ -1859,8 +2012,8 @@ var Blueprint = class {
1859
2012
  return commands;
1860
2013
  }
1861
2014
  indexCommand(type, columns, name) {
1862
- const list2 = [columns].flat();
1863
- 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) });
1864
2017
  }
1865
2018
  indexNameFor(type, index) {
1866
2019
  return Array.isArray(index) ? this.createIndexName(type, index) : index;
@@ -1869,6 +2022,8 @@ var Blueprint = class {
1869
2022
 
1870
2023
  // Schema/Grammar.ts
1871
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";
1872
2027
  var join2 = (parts, separator = ", ") => sql4.join(parts, sql4.raw(separator));
1873
2028
  var columnList = (columns) => join2(columns.map((column) => sql4.id(column)));
1874
2029
  var SchemaGrammar = class {
@@ -1881,28 +2036,40 @@ var SchemaGrammar = class {
1881
2036
  if (driver === "mysql") return new MySqlSchemaGrammar(config);
1882
2037
  return new SqliteSchemaGrammar(config);
1883
2038
  }
1884
- /** 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
+ */
1885
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) {
1886
2052
  const statements = [];
1887
2053
  const commands = [...blueprint.commands, ...blueprint.fluentIndexCommands()];
1888
2054
  const handled = /* @__PURE__ */ new Set();
1889
2055
  if (blueprint.creating) {
1890
2056
  statements.push(this.compileCreate(blueprint, commands, handled));
1891
- } else if (blueprint.columns.length) {
1892
- 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));
1893
2060
  }
1894
2061
  for (const command of commands) {
1895
2062
  if (command.name === "create" || handled.has(command)) continue;
1896
2063
  statements.push(...this.compileCommand(blueprint, command));
1897
2064
  }
1898
2065
  if (blueprint.creating || blueprint.columns.length) statements.push(...this.compileComments(blueprint));
1899
- return statements;
2066
+ return mergeRebuilds(statements);
1900
2067
  }
1901
2068
  compileCreate(blueprint, _commands, _handled) {
1902
2069
  return sql4`create table ${sql4.id(blueprint.table)} (${join2(blueprint.columns.map((column) => this.columnDefinition(column)))})`;
1903
2070
  }
1904
2071
  compileAdd(blueprint, _commands, _handled) {
1905
- 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)}`);
1906
2073
  }
1907
2074
  compileCommand(blueprint, command) {
1908
2075
  const table = sql4.id(blueprint.table);
@@ -1976,7 +2143,8 @@ var SchemaGrammar = class {
1976
2143
  if (!foreign.referencedTable) {
1977
2144
  throw new LogicError(`Foreign key [${foreign.indexName}] has no referenced table: call on('table') or constrained().`);
1978
2145
  }
1979
- 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}`];
1980
2148
  if (foreign.deleteAction) parts.push(sql4.raw(`on delete ${foreign.deleteAction}`));
1981
2149
  if (foreign.updateAction) parts.push(sql4.raw(`on update ${foreign.updateAction}`));
1982
2150
  return join2(parts, " ");
@@ -2004,9 +2172,21 @@ var SchemaGrammar = class {
2004
2172
  }
2005
2173
  };
2006
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
+ }
2007
2187
  var SqliteSchemaGrammar = class extends SchemaGrammar {
2008
2188
  driver = "sqlite";
2009
- /** 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). */
2010
2190
  compileCreate(blueprint, commands, handled) {
2011
2191
  const parts = blueprint.columns.map((column) => this.columnDefinition(column));
2012
2192
  for (const command of commands) {
@@ -2022,7 +2202,7 @@ var SqliteSchemaGrammar = class extends SchemaGrammar {
2022
2202
  }
2023
2203
  /** New columns may carry an inline `references` clause (the only foreign key SQLite can add later). */
2024
2204
  compileAdd(blueprint, commands, handled) {
2025
- return blueprint.columns.map((column) => {
2205
+ return blueprint.addedColumns().map((column) => {
2026
2206
  const foreign = commands.find(
2027
2207
  (command) => command.name === "foreign" && command.foreign.columns.length === 1 && command.foreign.columns[0] === column.name
2028
2208
  );
@@ -2034,17 +2214,27 @@ var SqliteSchemaGrammar = class extends SchemaGrammar {
2034
2214
  return sql4`alter table ${sql4.id(blueprint.table)} add column ${definition}`;
2035
2215
  });
2036
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
+ */
2037
2221
  compileCommand(blueprint, command) {
2038
- const unsupported = {
2039
- primary: "adding a primary key to an existing table",
2040
- foreign: "adding a foreign key to an existing column",
2041
- dropPrimary: "dropping a primary key",
2042
- dropForeign: "dropping a foreign key"
2043
- };
2044
- const action = unsupported[command.name];
2045
- 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
+ }
2046
2228
  return super.compileCommand(blueprint, command);
2047
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
+ }
2048
2238
  compileUnique(blueprint, index, columns) {
2049
2239
  return sql4`create unique index ${sql4.id(index)} on ${sql4.id(blueprint.table)} (${columnList(columns)})`;
2050
2240
  }
@@ -2116,6 +2306,37 @@ var SqliteSchemaGrammar = class extends SchemaGrammar {
2116
2306
  };
2117
2307
  });
2118
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
+ }
2119
2340
  compileEnableForeignKeyConstraints() {
2120
2341
  return sql4.raw("PRAGMA foreign_keys = ON");
2121
2342
  }
@@ -2123,10 +2344,31 @@ var SqliteSchemaGrammar = class extends SchemaGrammar {
2123
2344
  return sql4.raw("PRAGMA foreign_keys = OFF");
2124
2345
  }
2125
2346
  };
2347
+ var POSTGRES_ACTIONS = { a: "no action", r: "restrict", c: "cascade", n: "set null", d: "set default" };
2126
2348
  var PostgresSchemaGrammar = class extends SchemaGrammar {
2127
2349
  driver = "pgsql";
2350
+ /** A changed column's comment is set again, or cleared (`is NULL`) when the new definition has none (Laravel 11+). */
2128
2351
  compileComments(blueprint) {
2129
- 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}`))}`];
2130
2372
  }
2131
2373
  type(column) {
2132
2374
  const { type, autoIncrement, length, total, places, precision } = column.attributes;
@@ -2205,6 +2447,52 @@ var PostgresSchemaGrammar = class extends SchemaGrammar {
2205
2447
  };
2206
2448
  });
2207
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
+ }
2208
2496
  compileEnableForeignKeyConstraints() {
2209
2497
  return sql4.raw("SET CONSTRAINTS ALL IMMEDIATE");
2210
2498
  }
@@ -2220,7 +2508,11 @@ var MySqlSchemaGrammar = class extends SchemaGrammar {
2220
2508
  return sql4`${super.compileCreate(blueprint, commands, handled)} default character set ${sql4.raw(charset.replace(/[^\w]/g, ""))} collate ${sql4.lit(collation)}`;
2221
2509
  }
2222
2510
  compileAdd(blueprint) {
2223
- 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)}`];
2224
2516
  }
2225
2517
  compileUnique(blueprint, index, columns) {
2226
2518
  return sql4`alter table ${sql4.id(blueprint.table)} add unique ${sql4.id(index)}(${columnList(columns)})`;
@@ -2293,13 +2585,14 @@ var MySqlSchemaGrammar = class extends SchemaGrammar {
2293
2585
  }
2294
2586
  }
2295
2587
  modifiers(column) {
2296
- 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";
2297
2590
  return present([
2298
2591
  unsigned ? sql4.raw(" unsigned") : void 0,
2299
2592
  this.nullable(column),
2300
2593
  this.default(column),
2301
2594
  onUpdate ? sql4` on update ${this.defaultValue(onUpdate)}` : void 0,
2302
- autoIncrement ? sql4.raw(" auto_increment primary key") : void 0,
2595
+ autoIncrement ? sql4.raw(increment) : void 0,
2303
2596
  comment === void 0 ? void 0 : sql4` comment ${sql4.lit(comment)}`,
2304
2597
  after === void 0 ? void 0 : sql4` after ${sql4.id(after)}`,
2305
2598
  first ? sql4.raw(" first") : void 0
@@ -2322,6 +2615,37 @@ var MySqlSchemaGrammar = class extends SchemaGrammar {
2322
2615
  auto_increment: Number(row.auto_increment) === 1
2323
2616
  }));
2324
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
+ }
2325
2649
  compileEnableForeignKeyConstraints() {
2326
2650
  return sql4.raw("SET FOREIGN_KEY_CHECKS=1");
2327
2651
  }
@@ -2330,6 +2654,235 @@ var MySqlSchemaGrammar = class extends SchemaGrammar {
2330
2654
  }
2331
2655
  };
2332
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
+
2333
2886
  // Schema/Builder.ts
2334
2887
  var SchemaBuilder = class _SchemaBuilder {
2335
2888
  constructor(db, resolveConnection) {
@@ -2368,9 +2921,15 @@ var SchemaBuilder = class _SchemaBuilder {
2368
2921
  async rename(from, to) {
2369
2922
  await this.run([this.grammar.compileRename(from, to)]);
2370
2923
  }
2371
- /** 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
+ */
2372
2928
  async build(blueprint) {
2373
- 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
+ }
2374
2933
  }
2375
2934
  /** The table names of the connection's database (or current schema on Postgres). */
2376
2935
  async getTables() {
@@ -2395,6 +2954,31 @@ var SchemaBuilder = class _SchemaBuilder {
2395
2954
  const existing = (await this.getColumnListing(table)).map((name) => name.toLowerCase());
2396
2955
  return columns.every((column) => existing.includes(column.toLowerCase()));
2397
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
+ }
2398
2982
  async enableForeignKeyConstraints() {
2399
2983
  await this.run([this.grammar.compileEnableForeignKeyConstraints()]);
2400
2984
  }
@@ -2421,7 +3005,7 @@ var SchemaBuilder = class _SchemaBuilder {
2421
3005
  const tables = await this.getTables();
2422
3006
  if (!tables.length) return;
2423
3007
  if (this.db.getDriverName() === "pgsql") {
2424
- 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`]);
2425
3009
  return;
2426
3010
  }
2427
3011
  await this.withoutForeignKeyConstraints(async () => {
@@ -2567,16 +3151,16 @@ var Connection = class {
2567
3151
  const parent = this.current();
2568
3152
  if (!parent) return { trx: await this.db.startTransaction().execute(), level: 1 };
2569
3153
  const level = parent.level + 1;
2570
- await sql6.raw(`SAVEPOINT trans${level}`).execute(parent.trx);
3154
+ await sql7.raw(`SAVEPOINT trans${level}`).execute(parent.trx);
2571
3155
  return { trx: parent.trx, level };
2572
3156
  }
2573
3157
  async close(frame, action) {
2574
3158
  if (frame.level === 1) {
2575
3159
  await (action === "commit" ? frame.trx.commit() : frame.trx.rollback()).execute();
2576
3160
  } else if (action === "commit") {
2577
- await sql6.raw(`RELEASE SAVEPOINT trans${frame.level}`).execute(frame.trx);
3161
+ await sql7.raw(`RELEASE SAVEPOINT trans${frame.level}`).execute(frame.trx);
2578
3162
  } else {
2579
- 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);
2580
3164
  }
2581
3165
  }
2582
3166
  };
@@ -2740,10 +3324,10 @@ var Schema = facade(SchemaBuilderToken);
2740
3324
 
2741
3325
  // Eloquent/Model.ts
2742
3326
  import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
2743
- import { DatabaseManager as DatabaseManager2 } from "@orieljs/contracts";
2744
- import { Collection as Collection11 } from "@orieljs/collections";
3327
+ import { DatabaseManager as DatabaseManager2, Hasher } from "@orieljs/contracts";
3328
+ import { Collection as Collection10 } from "@orieljs/collections";
2745
3329
  import { currentContainer as currentContainer3, inject } from "@orieljs/container";
2746
- import { Str as Str5 } from "@orieljs/support";
3330
+ import { Str as Str6 } from "@orieljs/support";
2747
3331
 
2748
3332
  // Eloquent/Builder.ts
2749
3333
  import { Collection as Collection4 } from "@orieljs/collections";
@@ -2787,6 +3371,8 @@ var Builder2 = class extends Builder {
2787
3371
  scopes = /* @__PURE__ */ new Map();
2788
3372
  removedScopes = [];
2789
3373
  eagerLoad = /* @__PURE__ */ new Map();
3374
+ /** Casts for the selected columns (withCasts()), merged into every model this query hydrates. */
3375
+ selectCasts = {};
2790
3376
  constructor(model) {
2791
3377
  super(model.getConnection(), model.getTable());
2792
3378
  this.model = model;
@@ -2880,6 +3466,48 @@ var Builder2 = class extends Builder {
2880
3466
  whereBetween(column, values) {
2881
3467
  return super.whereBetween(column, values);
2882
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
+ }
3499
+ whereLike(column, value, caseSensitive = false, boolean = "and", not = false) {
3500
+ return super.whereLike(column, value, caseSensitive, boolean, not);
3501
+ }
3502
+ orWhereLike(column, value, caseSensitive = false) {
3503
+ return super.orWhereLike(column, value, caseSensitive);
3504
+ }
3505
+ whereNotLike(column, value, caseSensitive = false, boolean = "and") {
3506
+ return super.whereNotLike(column, value, caseSensitive, boolean);
3507
+ }
3508
+ orWhereNotLike(column, value, caseSensitive = false) {
3509
+ return super.orWhereNotLike(column, value, caseSensitive);
3510
+ }
2883
3511
  orderBy(column, direction = "asc") {
2884
3512
  return super.orderBy(column, direction);
2885
3513
  }
@@ -2903,11 +3531,25 @@ var Builder2 = class extends Builder {
2903
3531
  return super.where(this.model.getQualifiedKeyName(), "!=", id);
2904
3532
  }
2905
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
+ }
2906
3548
  /** Runs the query, hydrates models, fires their retrieved events and eager loads the with() relations. */
2907
3549
  async runSelect() {
2908
3550
  const query = this.applyScopes();
2909
3551
  const rows = await Builder.prototype.runSelect.call(query);
2910
- const models = this.hydrate(rows);
3552
+ const models = query.hydrate(rows);
2911
3553
  if (models.length && this.model.hasModelListeners("retrieved")) {
2912
3554
  for (const model of models) await model.fireModelEvent("retrieved", false);
2913
3555
  }
@@ -2988,17 +3630,66 @@ var Builder2 = class extends Builder {
2988
3630
  * withCount('comments as approved_count'). Global scopes of the related model (soft deletes) apply.
2989
3631
  */
2990
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;
2991
3664
  if (!this.columns.length) this.columns = [`${this.model.getTable()}.*`];
2992
- for (const [spec, constraint] of this.normalizeRelationSpecs(relations)) {
2993
- const [name = "", alias] = spec.split(/\s+as\s+/i);
2994
- const relation = this.getRelation(name.trim());
2995
- 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]);
2996
3672
  query.wheres.push(...relation.wheres);
2997
3673
  if (constraint) query.callScope((q) => constraint(q));
2998
- 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
+ }
2999
3685
  }
3000
3686
  return this;
3001
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
+ }
3002
3693
  /**
3003
3694
  * Rows that have related rows: has('comments'), has('comments', '>=', 3), has('comments.author').
3004
3695
  * Uses `exists (…)` for the common "at least one"/"none" cases and a count subquery otherwise.
@@ -3054,7 +3745,11 @@ var Builder2 = class extends Builder {
3054
3745
  }
3055
3746
  /** Models from raw rows, marked as existing. */
3056
3747
  hydrate(rows) {
3057
- 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
+ });
3058
3753
  }
3059
3754
  async aggregate(fn, column) {
3060
3755
  return Builder.prototype.aggregate.call(this.applyScopes(), fn, column);
@@ -3069,12 +3764,19 @@ var Builder2 = class extends Builder {
3069
3764
  const key = column.includes(".") ? column.slice(column.lastIndexOf(".") + 1) : column;
3070
3765
  return new Collection4(rows.map((row) => this.model.newInstance().setRawAttributes({ [key]: row[key] }).getAttribute(key)));
3071
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. */
3072
3772
  async find(id) {
3773
+ if (this.isMalformedKey(id)) return void 0;
3073
3774
  return this.clone().whereKey(id).first();
3074
3775
  }
3075
3776
  async findMany(ids) {
3076
- if (!ids.length) return new Collection4();
3077
- 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();
3078
3780
  }
3079
3781
  async findOrFail(id) {
3080
3782
  if (Array.isArray(id)) {
@@ -3196,6 +3898,7 @@ var Builder2 = class extends Builder {
3196
3898
  copy.scopes = new Map(this.scopes);
3197
3899
  copy.removedScopes = [...this.removedScopes];
3198
3900
  copy.eagerLoad = new Map(this.eagerLoad);
3901
+ copy.selectCasts = { ...this.selectCasts };
3199
3902
  return new Proxy(copy, handler);
3200
3903
  }
3201
3904
  /** Nested where groups get a builder of the same model (without global scopes), so local scopes work inside them. */
@@ -3220,6 +3923,7 @@ import { Collection as Collection5 } from "@orieljs/collections";
3220
3923
  var JSON_CASTS = /* @__PURE__ */ new Set(["array", "json", "object", "collection"]);
3221
3924
  var DATE_CASTS = /* @__PURE__ */ new Set(["date", "datetime", "immutable_date", "immutable_datetime"]);
3222
3925
  var PRIMITIVE_CASTS = /* @__PURE__ */ new Set(["int", "integer", "float", "double", "real", "string", "bool", "boolean", "timestamp"]);
3926
+ var HASHED_CAST = "hashed";
3223
3927
  var isCustom = (cast) => typeof cast === "object" && typeof cast.get === "function" && typeof cast.set === "function";
3224
3928
  var isCustomClass = (cast) => typeof cast === "function";
3225
3929
  var isEnum = (cast) => typeof cast === "object" && !isCustom(cast);
@@ -3235,8 +3939,9 @@ function enumValues(cast) {
3235
3939
  }
3236
3940
  var isJsonCast = (cast) => typeof cast === "string" && JSON_CASTS.has(cast);
3237
3941
  var isDateCast = (cast) => typeof cast === "string" && DATE_CASTS.has(cast);
3942
+ var isHashedCast = (cast) => cast === HASHED_CAST;
3238
3943
  var decimalPlaces = (cast) => cast.startsWith("decimal:") ? Number(cast.slice(8)) : void 0;
3239
- 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);
3240
3945
  function assertBuiltInCast(cast, key, className) {
3241
3946
  if (!isBuiltInCast(cast)) throw new InvalidCastError(className, key, cast);
3242
3947
  }
@@ -3325,12 +4030,207 @@ function isEquivalent(cast, current, original, model, key, className) {
3325
4030
  return numeric(current) && numeric(original) && Number(current) === Number(original);
3326
4031
  }
3327
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
+
3328
4228
  // Eloquent/Factories/Factory.ts
3329
4229
  import { existsSync, readdirSync } from "fs";
3330
- import { join as join3 } from "path";
4230
+ import { join as join4 } from "path";
3331
4231
  import { pathToFileURL } from "url";
3332
- import { Collection as Collection8 } from "@orieljs/collections";
3333
- import { Str as Str4 } from "@orieljs/support";
4232
+ import { Collection as Collection9 } from "@orieljs/collections";
4233
+ import { Str as Str5 } from "@orieljs/support";
3334
4234
 
3335
4235
  // Eloquent/Relations/BelongsTo.ts
3336
4236
  import { Str as Str3 } from "@orieljs/support";
@@ -3495,7 +4395,7 @@ var BelongsTo = class extends Relation {
3495
4395
  };
3496
4396
 
3497
4397
  // Eloquent/Relations/BelongsToMany.ts
3498
- import { Collection as Collection6 } from "@orieljs/collections";
4398
+ import { Collection as Collection7 } from "@orieljs/collections";
3499
4399
  var BelongsToMany = class extends Relation {
3500
4400
  constructor(related, parent, table, foreignPivotKey, relatedPivotKey, parentKey, relatedKey) {
3501
4401
  super(related, parent);
@@ -3563,10 +4463,10 @@ var BelongsToMany = class extends Relation {
3563
4463
  }
3564
4464
  async getResults() {
3565
4465
  const key = this.getParentKey();
3566
- return key === null || key === void 0 ? new Collection6() : this.get();
4466
+ return key === null || key === void 0 ? this.getRelated().newCollection() : this.get();
3567
4467
  }
3568
4468
  initRelation(models, relation) {
3569
- for (const model of models) model.setRelation(relation, new Collection6());
4469
+ for (const model of models) model.setRelation(relation, this.getRelated().newCollection());
3570
4470
  return models;
3571
4471
  }
3572
4472
  match(models, results, relation) {
@@ -3577,7 +4477,7 @@ var BelongsToMany = class extends Relation {
3577
4477
  if (group) group.push(result);
3578
4478
  else dictionary.set(key, [result]);
3579
4479
  }
3580
- 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))) ?? []));
3581
4481
  return models;
3582
4482
  }
3583
4483
  getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
@@ -3593,9 +4493,9 @@ var BelongsToMany = class extends Relation {
3593
4493
  async detach(ids) {
3594
4494
  const query = this.newPivotQuery().where(this.foreignPivotKey, "=", this.getParentKey());
3595
4495
  if (ids !== void 0) {
3596
- const list2 = [...this.parseIds(ids).keys()];
3597
- if (!list2.length) return 0;
3598
- query.whereIn(this.relatedPivotKey, list2);
4496
+ const list3 = [...this.parseIds(ids).keys()];
4497
+ if (!list3.length) return 0;
4498
+ query.whereIn(this.relatedPivotKey, list3);
3599
4499
  }
3600
4500
  return query.delete();
3601
4501
  }
@@ -3699,7 +4599,7 @@ var BelongsToMany = class extends Relation {
3699
4599
  /** ids → Map(id → extra pivot attributes). Models become their related key. */
3700
4600
  parseIds(ids) {
3701
4601
  const parsed = /* @__PURE__ */ new Map();
3702
- if (ids instanceof Collection6) ids = ids.all();
4602
+ if (ids instanceof Collection7) ids = ids.all();
3703
4603
  if (Array.isArray(ids)) {
3704
4604
  for (const id of ids) parsed.set(this.idOf(id), {});
3705
4605
  } else if (ids !== null && typeof ids === "object" && !this.isModel(ids)) {
@@ -3722,6 +4622,7 @@ var BelongsToMany = class extends Relation {
3722
4622
  };
3723
4623
 
3724
4624
  // Eloquent/Relations/HasOneOrMany.ts
4625
+ import { Str as Str4 } from "@orieljs/support";
3725
4626
  var HasOneOrMany = class extends Relation {
3726
4627
  /**
3727
4628
  * @param foreignKey the qualified foreign key on the related table ('comments.post_id')
@@ -3738,6 +4639,8 @@ var HasOneOrMany = class extends Relation {
3738
4639
  foreignKey;
3739
4640
  localKey;
3740
4641
  morph;
4642
+ /** The relation on each related model that chaperone() points back at the parent. */
4643
+ inverseRelationship;
3741
4644
  /** 'post_id' */
3742
4645
  getForeignKeyName() {
3743
4646
  return this.foreignKey.slice(this.foreignKey.lastIndexOf(".") + 1);
@@ -3759,6 +4662,61 @@ var HasOneOrMany = class extends Relation {
3759
4662
  getMorphClass() {
3760
4663
  return this.morph?.value;
3761
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
+ }
3762
4720
  addConstraints() {
3763
4721
  this.where(this.foreignKey, "=", this.getParentKey());
3764
4722
  this.whereNotNull(this.foreignKey);
@@ -3792,7 +4750,7 @@ var HasOneOrMany = class extends Relation {
3792
4750
  setForeignAttributes(model) {
3793
4751
  model.setAttribute(this.getForeignKeyName(), this.getParentKey());
3794
4752
  if (this.morph) model.setAttribute(this.getMorphType(), this.morph.value);
3795
- return model;
4753
+ return this.applyInverseRelationToModel(model);
3796
4754
  }
3797
4755
  async saveMany(models) {
3798
4756
  const saved = [];
@@ -3812,7 +4770,7 @@ var HasOneOrMany = class extends Relation {
3812
4770
  };
3813
4771
 
3814
4772
  // Eloquent/Relations/MorphTo.ts
3815
- import { Collection as Collection7 } from "@orieljs/collections";
4773
+ import { Collection as Collection8 } from "@orieljs/collections";
3816
4774
  var MorphTo = class extends BelongsTo {
3817
4775
  /**
3818
4776
  * @param related an instance of the current type's class (the child's own class when the type is empty)
@@ -3874,7 +4832,7 @@ var MorphTo = class extends BelongsTo {
3874
4832
  results.push(result);
3875
4833
  }
3876
4834
  }
3877
- return new Collection7(results);
4835
+ return new Collection8(results);
3878
4836
  }
3879
4837
  match(models, results, relation) {
3880
4838
  for (const result of results) {
@@ -3947,13 +4905,13 @@ var Factory = class _Factory {
3947
4905
  }
3948
4906
  /** Creates related models for each created model: has(Post.factory().count(3)) (relationship default: 'posts'). */
3949
4907
  has(factory, relationship, pivot = {}) {
3950
- 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));
3951
4909
  return this.newInstance({ hasRelations: [...this.hasRelations, { factory, relationship: name, pivot }] });
3952
4910
  }
3953
4911
  /** Sets a belongsTo parent: for(User.factory()) or for(user) (relationship default: 'user'). Created once. */
3954
4912
  for(parent, relationship) {
3955
4913
  const cls = parent instanceof Model ? parent.constructor : new parent.model().constructor;
3956
- 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) }] });
3957
4915
  }
3958
4916
  afterMaking(callback) {
3959
4917
  return this.newInstance({ afterMakingCallbacks: [...this.afterMakingCallbacks, callback] });
@@ -3990,10 +4948,10 @@ var Factory = class _Factory {
3990
4948
  }
3991
4949
  /** One model per record (or `count` models). */
3992
4950
  async createMany(records) {
3993
- const list2 = typeof records === "number" ? Array.from({ length: records }, () => ({})) : records;
4951
+ const list3 = typeof records === "number" ? Array.from({ length: records }, () => ({})) : records;
3994
4952
  const created = [];
3995
- for (const record of list2) created.push(await this.createOne(record));
3996
- return new Collection8(created);
4953
+ for (const record of list3) created.push(await this.createOne(record));
4954
+ return new Collection9(created);
3997
4955
  }
3998
4956
  newInstance(changes) {
3999
4957
  const copy = Object.create(Object.getPrototypeOf(this));
@@ -4039,7 +4997,7 @@ var Factory = class _Factory {
4039
4997
  const relation = this.relationOn(model, relationship);
4040
4998
  if (relation instanceof BelongsToMany) {
4041
4999
  const related = await factory.create();
4042
- await relation.attach(related instanceof Collection8 ? related.all() : related, pivot);
5000
+ await relation.attach(related instanceof Collection9 ? related.all() : related, pivot);
4043
5001
  } else if (relation instanceof HasOneOrMany) {
4044
5002
  const foreign = { [relation.getForeignKeyName()]: relation.getParentKey() };
4045
5003
  if (relation.morph) foreign[relation.getMorphType()] = relation.getMorphClass();
@@ -4053,14 +5011,14 @@ var Factory = class _Factory {
4053
5011
  return model.getRelationInstance(relationship);
4054
5012
  }
4055
5013
  result(models) {
4056
- return this.countValue === void 0 ? models[0] : new Collection8(models);
5014
+ return this.countValue === void 0 ? models[0] : new Collection9(models);
4057
5015
  }
4058
5016
  };
4059
5017
  async function discoverFactories(path) {
4060
5018
  if (!existsSync(path)) return;
4061
5019
  for (const file of readdirSync(path).sort()) {
4062
5020
  if (!/\.(ts|js|mts|mjs)$/.test(file) || /\.d\.[mc]?ts$/.test(file)) continue;
4063
- const module = await import(pathToFileURL(join3(path, file)).href);
5021
+ const module = await import(pathToFileURL(join4(path, file)).href);
4064
5022
  for (const exported of Object.values(module)) {
4065
5023
  if (typeof exported === "function" && exported.prototype instanceof Factory) {
4066
5024
  Factory.register(exported);
@@ -4111,27 +5069,26 @@ function modelEventsMuted() {
4111
5069
  }
4112
5070
 
4113
5071
  // Eloquent/Relations/HasMany.ts
4114
- import { Collection as Collection9 } from "@orieljs/collections";
4115
5072
  var HasMany = class extends HasOneOrMany {
4116
5073
  async getResults() {
4117
5074
  const key = this.getParentKey();
4118
- return key === null || key === void 0 ? new Collection9() : this.get();
5075
+ return key === null || key === void 0 ? this.getRelated().newCollection() : this.get();
4119
5076
  }
4120
5077
  initRelation(models, relation) {
4121
- for (const model of models) model.setRelation(relation, new Collection9());
5078
+ for (const model of models) model.setRelation(relation, this.getRelated().newCollection());
4122
5079
  return models;
4123
5080
  }
4124
5081
  match(models, results, relation) {
4125
5082
  const dictionary = this.buildDictionary(results);
4126
5083
  for (const model of models) {
4127
- 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));
4128
5086
  }
4129
5087
  return models;
4130
5088
  }
4131
5089
  };
4132
5090
 
4133
5091
  // Eloquent/Relations/HasManyThrough.ts
4134
- import { Collection as Collection10 } from "@orieljs/collections";
4135
5092
  var THROUGH_KEY = "laravel_through_key";
4136
5093
  var HasManyThrough = class extends Relation {
4137
5094
  /**
@@ -4197,13 +5154,13 @@ var HasManyThrough = class extends Relation {
4197
5154
  }
4198
5155
  async getResults() {
4199
5156
  const key = this.parent.getAttribute(this.localKey);
4200
- return key === null || key === void 0 ? new Collection10() : this.get();
5157
+ return key === null || key === void 0 ? this.getRelated().newCollection() : this.get();
4201
5158
  }
4202
5159
  async getEager() {
4203
5160
  return this.get();
4204
5161
  }
4205
5162
  initRelation(models, relation) {
4206
- for (const model of models) model.setRelation(relation, new Collection10());
5163
+ for (const model of models) model.setRelation(relation, this.getRelated().newCollection());
4207
5164
  return models;
4208
5165
  }
4209
5166
  match(models, results, relation) {
@@ -4214,7 +5171,7 @@ var HasManyThrough = class extends Relation {
4214
5171
  if (group) group.push(result);
4215
5172
  else dictionary.set(key, [result]);
4216
5173
  }
4217
- 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))) ?? []));
4218
5175
  return models;
4219
5176
  }
4220
5177
  getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
@@ -4238,7 +5195,7 @@ var HasOne = class extends HasOneOrMany {
4238
5195
  match(models, results, relation) {
4239
5196
  const dictionary = this.buildDictionary(results);
4240
5197
  for (const model of models) {
4241
- 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));
4242
5199
  }
4243
5200
  return models;
4244
5201
  }
@@ -4265,7 +5222,13 @@ var MorphOne = class extends HasOne {
4265
5222
  // Eloquent/Model.ts
4266
5223
  var handler2 = {
4267
5224
  get(target, key, receiver) {
4268
- 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
+ }
4269
5232
  return receiver.getAttribute(key);
4270
5233
  },
4271
5234
  set(target, key, value, receiver) {
@@ -4274,6 +5237,35 @@ var handler2 = {
4274
5237
  return true;
4275
5238
  }
4276
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
+ }
4277
5269
  var bootedModels = /* @__PURE__ */ new Set();
4278
5270
  var prototypes = /* @__PURE__ */ new Map();
4279
5271
  var unguardedGlobally = { value: false };
@@ -4287,7 +5279,7 @@ function installScopeProxies(cls) {
4287
5279
  for (const key of Object.getOwnPropertyNames(current)) {
4288
5280
  if (!key.startsWith("scope") || key.length <= 5) continue;
4289
5281
  if (typeof Reflect.get(current, key) !== "function") continue;
4290
- const name = Str5.lcfirst(key.slice(5));
5282
+ const name = Str6.lcfirst(key.slice(5));
4291
5283
  if (name in cls) continue;
4292
5284
  Object.defineProperty(cls, name, {
4293
5285
  configurable: true,
@@ -4304,6 +5296,12 @@ function methodOf(model, name) {
4304
5296
  const value = Reflect.get(Object.getPrototypeOf(model), name);
4305
5297
  return typeof value === "function" ? value : void 0;
4306
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();
4307
5305
  function serializeDate(date) {
4308
5306
  return date.toISOString().replace(/\.(\d{3})Z$/, ".$1000Z");
4309
5307
  }
@@ -4348,6 +5346,8 @@ var Model = class _Model {
4348
5346
  relations = {};
4349
5347
  /** Decoded json/array/object/collection values, so in-place changes are seen by save(). */
4350
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();
4351
5351
  constructor() {
4352
5352
  ;
4353
5353
  this.constructor.bootIfNotBooted();
@@ -4481,6 +5481,18 @@ var Model = class _Model {
4481
5481
  }
4482
5482
  }
4483
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
+ }
4484
5496
  /** Runs fn with model events off, for this async context only. */
4485
5497
  static withoutEvents(fn) {
4486
5498
  return withoutModelEvents(fn);
@@ -4494,6 +5506,14 @@ var Model = class _Model {
4494
5506
  const query = this.query();
4495
5507
  return Reflect.apply(query.where, query, args);
4496
5508
  }
5509
+ static when(...args) {
5510
+ const query = this.query();
5511
+ return Reflect.apply(query.when, query, args);
5512
+ }
5513
+ static unless(...args) {
5514
+ const query = this.query();
5515
+ return Reflect.apply(query.unless, query, args);
5516
+ }
4497
5517
  static whereKey(id) {
4498
5518
  return this.query().whereKey(id);
4499
5519
  }
@@ -4512,11 +5532,34 @@ var Model = class _Model {
4512
5532
  static whereBetween(column, values) {
4513
5533
  return this.query().whereBetween(column, values);
4514
5534
  }
5535
+ /** Post.whereLike('title', `%${term}%`): case-insensitive unless caseSensitive (see the query builder's whereLike()). */
5536
+ static whereLike(column, value, caseSensitive = false) {
5537
+ return this.query().whereLike(column, value, caseSensitive);
5538
+ }
5539
+ static whereNotLike(column, value, caseSensitive = false) {
5540
+ return this.query().whereNotLike(column, value, caseSensitive);
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
+ }
4515
5558
  static whereColumn(first, operatorOrSecond, second) {
4516
5559
  return this.query().whereColumn(first, operatorOrSecond, second);
4517
5560
  }
4518
- static whereRaw(sql7, bindings = []) {
4519
- return this.query().whereRaw(sql7, bindings);
5561
+ static whereRaw(sql8, bindings = []) {
5562
+ return this.query().whereRaw(sql8, bindings);
4520
5563
  }
4521
5564
  static select(...columns) {
4522
5565
  return this.query().select(...columns);
@@ -4552,6 +5595,25 @@ var Model = class _Model {
4552
5595
  static withCount(...relations) {
4553
5596
  return this.query().withCount(...relations);
4554
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
+ }
4555
5617
  static has(relation, operator = ">=", count = 1) {
4556
5618
  return this.query().has(relation, operator, count);
4557
5619
  }
@@ -4697,8 +5759,8 @@ var Model = class _Model {
4697
5759
  /** Guarded names match case-insensitively: SQLite and MySQL column names are case-insensitive. */
4698
5760
  isGuarded(key) {
4699
5761
  if (this.guarded.length === 0) return false;
4700
- const lower = key.toLowerCase();
4701
- return this.guarded.some((guarded) => guarded === "*" || guarded.toLowerCase() === lower);
5762
+ const lower2 = key.toLowerCase();
5763
+ return this.guarded.some((guarded) => guarded === "*" || guarded.toLowerCase() === lower2);
4702
5764
  }
4703
5765
  totallyGuarded() {
4704
5766
  return !_Model.isUnguarded() && this.fillable.length === 0 && this.guarded.length === 1 && this.guarded[0] === "*";
@@ -4733,6 +5795,10 @@ var Model = class _Model {
4733
5795
  const cast = this.getCasts()[key];
4734
5796
  this.castCache.delete(key);
4735
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
+ }
4736
5802
  return this;
4737
5803
  }
4738
5804
  hasGetMutator(key) {
@@ -4744,7 +5810,7 @@ var Model = class _Model {
4744
5810
  /** Every cast, including the implied ones: the incrementing key (int) and the timestamp columns (datetime). */
4745
5811
  getCasts() {
4746
5812
  const implied = {};
4747
- if (this.incrementing) implied[this.getKeyName()] = this.keyType === "int" ? "int" : "string";
5813
+ if (this.getIncrementing()) implied[this.getKeyName()] = this.getKeyType() === "int" ? "int" : "string";
4748
5814
  if (this.usesTimestamps()) {
4749
5815
  const created = this.getCreatedAtColumn();
4750
5816
  const updated = this.getUpdatedAtColumn();
@@ -4754,6 +5820,11 @@ var Model = class _Model {
4754
5820
  if (this.softDeletes) implied[this.getDeletedAtColumn()] = "datetime";
4755
5821
  return { ...implied, ...this.casts };
4756
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
+ }
4757
5828
  hasCast(key, types) {
4758
5829
  const cast = this.getCasts()[key];
4759
5830
  if (cast === void 0) return false;
@@ -4768,6 +5839,7 @@ var Model = class _Model {
4768
5839
  setRawAttributes(attributes, sync = false) {
4769
5840
  this.attributes = { ...attributes };
4770
5841
  this.castCache.clear();
5842
+ this.pendingHashes.clear();
4771
5843
  if (sync) this.syncOriginal();
4772
5844
  return this;
4773
5845
  }
@@ -4855,7 +5927,7 @@ var Model = class _Model {
4855
5927
  }
4856
5928
  }
4857
5929
  mutatorFor(kind, key) {
4858
- return methodOf(this, `${kind}${Str5.studly(key)}Attribute`);
5930
+ return methodOf(this, `${kind}${Str6.studly(key)}Attribute`);
4859
5931
  }
4860
5932
  // ---------------------------------------------------------------- keys, table and naming
4861
5933
  getKeyName() {
@@ -4867,11 +5939,34 @@ var Model = class _Model {
4867
5939
  getIncrementing() {
4868
5940
  return this.incrementing;
4869
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
+ }
4870
5965
  getKey() {
4871
5966
  return this.getAttribute(this.getKeyName());
4872
5967
  }
4873
5968
  getTable() {
4874
- return this.table ?? Str5.snake(Str5.plural(this.constructor.name));
5969
+ return this.table ?? Str6.snake(Str6.plural(this.constructor.name));
4875
5970
  }
4876
5971
  getConnectionName() {
4877
5972
  return this.connection;
@@ -4888,7 +5983,7 @@ var Model = class _Model {
4888
5983
  }
4889
5984
  /** The conventional foreign key pointing at this model: user_id for User. */
4890
5985
  getForeignKey() {
4891
- return `${Str5.snake(this.constructor.name)}_${this.getKeyName()}`;
5986
+ return `${Str6.snake(this.constructor.name)}_${this.getKeyName()}`;
4892
5987
  }
4893
5988
  getRouteKeyName() {
4894
5989
  return this.getKeyName();
@@ -4898,11 +5993,13 @@ var Model = class _Model {
4898
5993
  }
4899
5994
  /**
4900
5995
  * The model a route parameter value points at: where <field or route key> = value (global scopes apply, so a
4901
- * 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.
4902
5998
  */
4903
5999
  async resolveRouteBinding(value, field) {
4904
6000
  const column = field ?? this.getRouteKeyName();
4905
- 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;
4906
6003
  return this.resolveRouteBindingQuery(this.newQuery(), value, column).first();
4907
6004
  }
4908
6005
  /** Override to customize the binding query (Laravel's resolveRouteBindingQuery()). */
@@ -5000,6 +6097,7 @@ var Model = class _Model {
5000
6097
  */
5001
6098
  async save() {
5002
6099
  const query = this.newModelQuery();
6100
+ await this.hashPendingAttributes();
5003
6101
  if (await this.fireModelEvent("saving") === false) return false;
5004
6102
  let saved;
5005
6103
  if (this.exists) saved = this.isDirty() ? await this.performUpdate(query) : true;
@@ -5007,6 +6105,28 @@ var Model = class _Model {
5007
6105
  if (saved) await this.finishSave();
5008
6106
  return saved;
5009
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
+ }
5010
6130
  /** Fills and saves an existing model. */
5011
6131
  async update(attributes = {}) {
5012
6132
  if (!this.exists) return false;
@@ -5120,8 +6240,10 @@ var Model = class _Model {
5120
6240
  if (!this.exists && created && !this.isDirty(created)) this.setAttribute(created, time);
5121
6241
  }
5122
6242
  async performInsert(query) {
6243
+ if (this.usesUniqueIds()) this.setUniqueIds();
5123
6244
  if (await this.fireModelEvent("creating") === false) return false;
5124
6245
  if (this.usesTimestamps()) this.updateTimestamps();
6246
+ await this.hashPendingAttributes();
5125
6247
  const attributes = this.getAttributes();
5126
6248
  if (this.getIncrementing()) {
5127
6249
  const id = await query.insertGetId(attributes, this.getKeyName());
@@ -5138,6 +6260,7 @@ var Model = class _Model {
5138
6260
  async performUpdate(query) {
5139
6261
  if (await this.fireModelEvent("updating") === false) return false;
5140
6262
  if (this.usesTimestamps()) this.updateTimestamps();
6263
+ await this.hashPendingAttributes();
5141
6264
  const dirty = this.getDirty();
5142
6265
  if (Object.keys(dirty).length) {
5143
6266
  await this.setKeysForSaveQuery(query).update(dirty);
@@ -5235,7 +6358,7 @@ var Model = class _Model {
5235
6358
  */
5236
6359
  belongsToMany(related, table, foreignPivotKey, relatedPivotKey, parentKey, relatedKey) {
5237
6360
  const instance = this.newRelatedInstance(related);
5238
- 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();
5239
6362
  const relation = new BelongsToMany(
5240
6363
  instance,
5241
6364
  this,
@@ -5303,6 +6426,10 @@ var Model = class _Model {
5303
6426
  if (!instance.getConnectionName()) instance.setConnection(this.getConnectionName());
5304
6427
  return instance;
5305
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
+ }
5306
6433
  /** Calls the relation method `name` (post.comments()) and checks that it returns a relation. */
5307
6434
  getRelationInstance(name) {
5308
6435
  if (name in _Model.prototype) throw new RelationNotFoundError(this.constructor.name, name);
@@ -5314,7 +6441,7 @@ var Model = class _Model {
5314
6441
  }
5315
6442
  /**
5316
6443
  * A loaded relation, typed from the relation method: post.getRelation('author') is User | null,
5317
- * 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
5318
6445
  * (JavaScript can't lazy-load synchronously: use with(), load() or post.comments().get()).
5319
6446
  */
5320
6447
  getRelation(name) {
@@ -5323,23 +6450,48 @@ var Model = class _Model {
5323
6450
  }
5324
6451
  /** Eager loads relations onto this model: await post.load('comments.author'). */
5325
6452
  async load(...relations) {
5326
- await this.newQueryWithoutRelationships().with(...relations).eagerLoadRelations([this]);
6453
+ await this.newCollection([this]).load(...relations);
5327
6454
  return this;
5328
6455
  }
5329
6456
  /** Loads only the relations that aren't loaded yet (nested paths are followed into loaded relations). */
5330
6457
  async loadMissing(...relations) {
5331
- await loadMissingOn([this], relations);
6458
+ await this.newCollection([this]).loadMissing(...relations);
5332
6459
  return this;
5333
6460
  }
5334
6461
  /** Loads <relation>_count attributes: await post.loadCount('comments'). */
5335
6462
  async loadCount(...relations) {
5336
- const row = await this.newQueryWithoutRelationships().whereKey(this.getKey()).select(this.getKeyName()).withCount(...relations).first();
5337
- if (row) {
5338
- const counts = Object.fromEntries(Object.entries(row.getAttributes()).filter(([key]) => key !== this.getKeyName()));
5339
- this.forceFill(counts).syncOriginalAttributes(...Object.keys(counts));
5340
- }
6463
+ await this.newCollection([this]).loadCount(...relations);
5341
6464
  return this;
5342
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
+ }
5343
6495
  // ---------------------------------------------------------------- relations storage
5344
6496
  /** Stores a loaded relation (eager loading and load() use this). */
5345
6497
  setRelation(name, value) {
@@ -5397,9 +6549,18 @@ var Model = class _Model {
5397
6549
  this.appends = [.../* @__PURE__ */ new Set([...this.appends, ...attributes.flat()])];
5398
6550
  return this;
5399
6551
  }
5400
- /** 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
+ */
5401
6556
  toArray() {
5402
- 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
+ }
5403
6564
  }
5404
6565
  toJSON() {
5405
6566
  return this.toArray();
@@ -5422,10 +6583,10 @@ var Model = class _Model {
5422
6583
  relationsToArray() {
5423
6584
  const result = {};
5424
6585
  for (const [name, value] of Object.entries(this.relations)) {
5425
- const key = Str5.snake(name);
6586
+ const key = Str6.snake(name);
5426
6587
  if (!this.isArrayableKey(key)) continue;
5427
6588
  if (value === null || value === void 0) result[key] = null;
5428
- else if (value instanceof Collection11) result[key] = value.toArray();
6589
+ else if (value instanceof Collection10) result[key] = value.toArray();
5429
6590
  else if (typeof value.toArray === "function") result[key] = value.toArray();
5430
6591
  else result[key] = value;
5431
6592
  }
@@ -5433,7 +6594,7 @@ var Model = class _Model {
5433
6594
  }
5434
6595
  serializeValue(value) {
5435
6596
  if (value instanceof Date) return serializeDate(value);
5436
- if (value instanceof Collection11) return value.toArray();
6597
+ if (value instanceof Collection10) return value.toArray();
5437
6598
  return value;
5438
6599
  }
5439
6600
  isArrayableKey(key) {
@@ -5446,24 +6607,10 @@ var Model = class _Model {
5446
6607
  };
5447
6608
  setModelBaseClass(Model);
5448
6609
  async function loadRelations(models, ...relations) {
5449
- const list2 = [...models];
5450
- if (!list2.length) return list2;
5451
- await list2[0].newQueryWithoutRelationships().with(...relations).eagerLoadRelations(list2);
5452
- return list2;
5453
- }
5454
- async function loadMissingOn(models, paths) {
5455
- for (const path of paths) {
5456
- const [head = "", ...rest] = path.split(".");
5457
- const missing = models.filter((model) => !model.relationLoaded(head));
5458
- if (missing.length) await loadRelations(missing, path);
5459
- if (!rest.length) continue;
5460
- const related = models.flatMap((model) => {
5461
- const value = model.getRelations()[head];
5462
- if (value instanceof Collection11) return value.all();
5463
- return value instanceof Model ? [value] : [];
5464
- });
5465
- if (related.length) await loadMissingOn(related, [rest.join(".")]);
5466
- }
6610
+ const list3 = [...models];
6611
+ if (!list3.length) return list3;
6612
+ await list3[0].newQueryWithoutRelationships().with(...relations).eagerLoadRelations(list3);
6613
+ return list3;
5467
6614
  }
5468
6615
  var Pivot = class extends Model {
5469
6616
  guarded = [];
@@ -5471,6 +6618,129 @@ var Pivot = class extends Model {
5471
6618
  timestamps = false;
5472
6619
  };
5473
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
+
6652
+ // Eloquent/DatabaseNotification.ts
6653
+ var DatabaseNotification = class extends HasUuids(Model) {
6654
+ table = "notifications";
6655
+ keyType = "string";
6656
+ incrementing = false;
6657
+ guarded = [];
6658
+ casts = { data: "array", read_at: "datetime" };
6659
+ /** The model the notification was sent to. */
6660
+ notifiable() {
6661
+ return this.morphTo("notifiable");
6662
+ }
6663
+ /** Sets read_at to now and saves, unless it is already read. */
6664
+ async markAsRead() {
6665
+ if (this.unread()) await this.forceFill({ read_at: this.freshTimestamp() }).save();
6666
+ }
6667
+ /** Clears read_at and saves, unless it is already unread. */
6668
+ async markAsUnread() {
6669
+ if (this.read()) await this.forceFill({ read_at: null }).save();
6670
+ }
6671
+ read() {
6672
+ return this.read_at !== null && this.read_at !== void 0;
6673
+ }
6674
+ unread() {
6675
+ return !this.read();
6676
+ }
6677
+ /** Queries of notifications return a DatabaseNotificationCollection (markAsRead() on all of them). */
6678
+ newCollection(models = []) {
6679
+ return new DatabaseNotificationCollection(models);
6680
+ }
6681
+ /** `query.read()`: only read notifications. */
6682
+ static scopeRead(query) {
6683
+ return query.whereNotNull("read_at");
6684
+ }
6685
+ /** `query.unread()`: only unread notifications. */
6686
+ static scopeUnread(query) {
6687
+ return query.whereNull("read_at");
6688
+ }
6689
+ };
6690
+ var DatabaseNotificationCollection = class extends EloquentCollection {
6691
+ /** Marks every notification as read (one save each, as in Laravel). */
6692
+ async markAsRead() {
6693
+ for (const notification of this.all()) await notification.markAsRead();
6694
+ }
6695
+ /** Marks every notification as unread. */
6696
+ async markAsUnread() {
6697
+ for (const notification of this.all()) await notification.markAsUnread();
6698
+ }
6699
+ };
6700
+ var DatabaseNotificationsRelation = class extends MorphMany {
6701
+ async get() {
6702
+ return new DatabaseNotificationCollection(await this.runSelect());
6703
+ }
6704
+ async getResults() {
6705
+ const key = this.getParentKey();
6706
+ return key === null || key === void 0 ? new DatabaseNotificationCollection() : this.get();
6707
+ }
6708
+ initRelation(models, relation) {
6709
+ for (const model of models) model.setRelation(relation, new DatabaseNotificationCollection());
6710
+ return models;
6711
+ }
6712
+ match(models, results, relation) {
6713
+ const dictionary = this.buildDictionary(results);
6714
+ for (const model of models) {
6715
+ model.setRelation(relation, new DatabaseNotificationCollection(dictionary.get(String(model.getAttribute(this.localKey))) ?? []));
6716
+ }
6717
+ return models;
6718
+ }
6719
+ };
6720
+
6721
+ // Eloquent/HasDatabaseNotifications.ts
6722
+ function HasDatabaseNotifications(Base) {
6723
+ class WithDatabaseNotifications extends Base {
6724
+ notifications() {
6725
+ const related = this.newRelatedInstance(DatabaseNotification);
6726
+ return new DatabaseNotificationsRelation(
6727
+ related,
6728
+ this,
6729
+ related.qualifyColumn("notifiable_type"),
6730
+ related.qualifyColumn("notifiable_id"),
6731
+ this.getKeyName()
6732
+ ).latest();
6733
+ }
6734
+ readNotifications() {
6735
+ return this.notifications().whereNotNull("read_at");
6736
+ }
6737
+ unreadNotifications() {
6738
+ return this.notifications().whereNull("read_at");
6739
+ }
6740
+ }
6741
+ return WithDatabaseNotifications;
6742
+ }
6743
+
5474
6744
  // Migrations/Migration.ts
5475
6745
  var Migration = class {
5476
6746
  /** The connection to run on (default: the default connection). */
@@ -5481,8 +6751,8 @@ var Migration = class {
5481
6751
 
5482
6752
  // Migrations/MigrationCreator.ts
5483
6753
  import { existsSync as existsSync2, mkdirSync, writeFileSync } from "fs";
5484
- import { join as join4 } from "path";
5485
- import { Str as Str6 } from "@orieljs/support";
6754
+ import { join as join5 } from "path";
6755
+ import { Str as Str8 } from "@orieljs/support";
5486
6756
  var MIGRATION_CREATE_STUB = `import { Migration, Schema } from '{{ importSource }}'
5487
6757
 
5488
6758
  export default class extends Migration {
@@ -5534,13 +6804,13 @@ function guessTable(migration) {
5534
6804
  return void 0;
5535
6805
  }
5536
6806
  function migrationDatePrefix(date = /* @__PURE__ */ new Date()) {
5537
- const pad2 = (value) => String(value).padStart(2, "0");
5538
- 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())}`;
5539
6809
  }
5540
6810
  var MigrationCreator = class {
5541
6811
  /** Returns the path of the new file. */
5542
6812
  create(name, path, options = {}) {
5543
- const snake = Str6.snake(name.trim());
6813
+ const snake = Str8.snake(name.trim());
5544
6814
  let table = options.table ?? options.create;
5545
6815
  let create = options.create !== void 0;
5546
6816
  if (table === void 0) {
@@ -5548,7 +6818,7 @@ var MigrationCreator = class {
5548
6818
  if (guessed) ({ table, create } = guessed);
5549
6819
  }
5550
6820
  const stub = table === void 0 ? MIGRATION_STUB : create ? MIGRATION_CREATE_STUB : MIGRATION_UPDATE_STUB;
5551
- const file = join4(path, `${migrationDatePrefix(options.date)}_${snake}.ts`);
6821
+ const file = join5(path, `${migrationDatePrefix(options.date)}_${snake}.ts`);
5552
6822
  if (existsSync2(file)) throw new LogicError(`Migration [${file}] already exists.`);
5553
6823
  mkdirSync(path, { recursive: true });
5554
6824
  writeFileSync(
@@ -5623,8 +6893,9 @@ var MigrationRepository = class {
5623
6893
 
5624
6894
  // Migrations/Migrator.ts
5625
6895
  import { existsSync as existsSync3, readdirSync as readdirSync2 } from "fs";
5626
- import { basename, extname, join as join5 } from "path";
6896
+ import { basename, extname, join as join6 } from "path";
5627
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.";
5628
6899
  var MIGRATION_FILE = /^(?!.*\.d\.[mc]?ts$).+\.(ts|js|mts|mjs)$/;
5629
6900
  var Migrator = class {
5630
6901
  constructor(manager, output = () => void 0) {
@@ -5651,7 +6922,7 @@ var Migrator = class {
5651
6922
  for (const path of paths) {
5652
6923
  if (!existsSync3(path)) continue;
5653
6924
  for (const file of readdirSync2(path)) {
5654
- 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)]);
5655
6926
  }
5656
6927
  }
5657
6928
  return new Map(files.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
@@ -5750,10 +7021,31 @@ var Migrator = class {
5750
7021
  const run = async () => {
5751
7022
  await migration[method]();
5752
7023
  };
5753
- 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);
5754
7026
  else await run();
5755
7027
  });
5756
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
+ }
5757
7049
  };
5758
7050
 
5759
7051
  // Seeder.ts
@@ -5783,13 +7075,13 @@ var Seeder = class {
5783
7075
 
5784
7076
  // Console/commands.ts
5785
7077
  import { existsSync as existsSync4 } from "fs";
5786
- import { isAbsolute, join as join6, relative as relative2 } from "path";
7078
+ import { isAbsolute, join as join7, relative as relative2 } from "path";
5787
7079
  import { pathToFileURL as pathToFileURL3 } from "url";
5788
7080
 
5789
7081
  // Types/TypeGenerator.ts
5790
7082
  import { mkdir, writeFile } from "fs/promises";
5791
7083
  import { dirname, relative, sep } from "path";
5792
- import { Str as Str7 } from "@orieljs/support";
7084
+ import { Str as Str9 } from "@orieljs/support";
5793
7085
  var INTEGER = /* @__PURE__ */ new Set(["int", "integer", "int2", "int4", "int8", "bigint", "smallint", "mediumint", "tinyint", "serial", "bigserial", "smallserial", "year"]);
5794
7086
  var FLOAT = /* @__PURE__ */ new Set(["float", "float4", "float8", "double", "double precision", "real"]);
5795
7087
  var BOOLEAN = /* @__PURE__ */ new Set(["bool", "boolean"]);
@@ -5799,7 +7091,7 @@ function castType(cast) {
5799
7091
  if (cast === void 0) return void 0;
5800
7092
  if (typeof cast === "string") {
5801
7093
  if (["int", "integer", "float", "double", "real", "timestamp"].includes(cast)) return "number";
5802
- if (cast === "string" || cast.startsWith("decimal:")) return "string";
7094
+ if (cast === "string" || cast === "hashed" || cast.startsWith("decimal:")) return "string";
5803
7095
  if (cast === "bool" || cast === "boolean") return "boolean";
5804
7096
  if (["date", "datetime", "immutable_date", "immutable_datetime"].includes(cast)) return "Date";
5805
7097
  return "unknown";
@@ -5824,7 +7116,7 @@ function accessors(model) {
5824
7116
  for (let proto = model.prototype; proto && proto !== Model.prototype; proto = Object.getPrototypeOf(proto)) {
5825
7117
  for (const key of Object.getOwnPropertyNames(proto)) {
5826
7118
  const match = /^get(.+)Attribute$/.exec(key);
5827
- 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);
5828
7120
  }
5829
7121
  }
5830
7122
  return [...found];
@@ -5834,7 +7126,7 @@ function scopes(model) {
5834
7126
  for (let current = model; current && current !== Model; current = Object.getPrototypeOf(current)) {
5835
7127
  for (const key of Object.getOwnPropertyNames(current)) {
5836
7128
  if (key.startsWith("scope") && key.length > 5 && typeof Reflect.get(current, key) === "function") {
5837
- const name = Str7.lcfirst(key.slice(5));
7129
+ const name = Str9.lcfirst(key.slice(5));
5838
7130
  if (!found.has(name)) found.set(name, key);
5839
7131
  }
5840
7132
  }
@@ -5908,7 +7200,7 @@ var TypeGenerator = class {
5908
7200
 
5909
7201
  // Console/commands.ts
5910
7202
  var text = (value) => typeof value === "string" && value !== "" ? value : void 0;
5911
- 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)] : [];
5912
7204
  var integer = (value) => {
5913
7205
  const number = Number(value ?? 0);
5914
7206
  return Number.isInteger(number) && number > 0 ? number : 0;
@@ -5924,7 +7216,7 @@ function confirmToProceed(context, command) {
5924
7216
  return false;
5925
7217
  }
5926
7218
  function migrationPaths(context, command) {
5927
- const paths = list(command.option("path"));
7219
+ const paths = list2(command.option("path"));
5928
7220
  if (!paths.length) return [context.app.databasePath("migrations")];
5929
7221
  return paths.map((path) => isAbsolute(path) ? path : context.app.basePath(path));
5930
7222
  }
@@ -5933,7 +7225,7 @@ function migrator(context, command) {
5933
7225
  }
5934
7226
  async function runSeeder(context, className, output, database) {
5935
7227
  const name = className.split("\\").pop();
5936
- 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);
5937
7229
  if (!file) throw new LogicError(`Seeder [${name}] not found in ${context.app.databasePath("seeders")}.`);
5938
7230
  const module = await import(pathToFileURL3(file).href);
5939
7231
  const exported = module.default ?? module[name];
@@ -5943,10 +7235,15 @@ async function runSeeder(context, className, output, database) {
5943
7235
  }
5944
7236
  async function generateModelTypes(context) {
5945
7237
  if (!context.models) return void 0;
5946
- const outputFile = context.app.basePath(join6("types", "models.d.ts"));
7238
+ const outputFile = context.app.basePath(join7("types", "models.d.ts"));
5947
7239
  await new TypeGenerator({ outputFile, importSource: context.typesImportSource }).write((await context.models()).all());
5948
7240
  return relative2(context.app.basePath(), outputFile);
5949
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
+ }
5950
7247
  async function seedIfRequested(context, command) {
5951
7248
  const seeder = text(command.option("seeder"));
5952
7249
  if (command.option("seed") !== true && seeder === void 0) return;
@@ -5958,10 +7255,7 @@ function registerMigrationCommands(kernel, context) {
5958
7255
  if (!confirmToProceed(context, command)) return 1;
5959
7256
  await migrator(context, command).run(migrationPaths(context, command), { step: command.option("step") === true });
5960
7257
  await seedIfRequested(context, command);
5961
- if (!context.app.isProduction() && existsSync4(context.app.basePath("types"))) {
5962
- const written = await generateModelTypes(context);
5963
- if (written) command.line(`Model types written to ${written}.`);
5964
- }
7258
+ await writeModelTypes(context, command);
5965
7259
  return 0;
5966
7260
  });
5967
7261
  define(kernel, "migrate:install {--database=}", "Create the migration repository", async (command) => {
@@ -5992,12 +7286,14 @@ function registerMigrationCommands(kernel, context) {
5992
7286
  else await instance.reset(paths);
5993
7287
  await instance.run(paths);
5994
7288
  await seedIfRequested(context, command);
7289
+ await writeModelTypes(context, command);
5995
7290
  return 0;
5996
7291
  });
5997
7292
  define(kernel, "migrate:fresh {--database=} {--force} {--path=*} {--seed} {--seeder=}", "Drop all tables and re-run all migrations", async (command) => {
5998
7293
  if (!confirmToProceed(context, command)) return 1;
5999
7294
  await migrator(context, command).fresh(migrationPaths(context, command));
6000
7295
  await seedIfRequested(context, command);
7296
+ await writeModelTypes(context, command);
6001
7297
  return 0;
6002
7298
  });
6003
7299
  define(kernel, "migrate:status {--database=} {--path=*}", "Show the status of each migration", async (command) => {
@@ -6050,9 +7346,9 @@ function registerModelTypesCommand(kernel, context) {
6050
7346
 
6051
7347
  // ModelRegistry.ts
6052
7348
  import { existsSync as existsSync5, readdirSync as readdirSync3, statSync } from "fs";
6053
- import { join as join7 } from "path";
7349
+ import { join as join8 } from "path";
6054
7350
  import { pathToFileURL as pathToFileURL4 } from "url";
6055
- import { Str as Str8 } from "@orieljs/support";
7351
+ import { Str as Str10 } from "@orieljs/support";
6056
7352
  var MODEL_FILE = /^(?!.*\.d\.[mc]?ts$).+\.(ts|js|mts|mjs)$/;
6057
7353
  var ModelRegistry = class {
6058
7354
  models = /* @__PURE__ */ new Map();
@@ -6078,7 +7374,7 @@ var ModelRegistry = class {
6078
7374
  }
6079
7375
  /** A model by class name or route parameter name: 'Post', 'post', 'blog_post' and 'blogPost' find BlogPost. */
6080
7376
  get(name) {
6081
- return this.models.get(name) ?? this.models.get(Str8.studly(name));
7377
+ return this.models.get(name) ?? this.models.get(Str10.studly(name));
6082
7378
  }
6083
7379
  resolve(name) {
6084
7380
  return this.get(name)?.model;
@@ -6094,7 +7390,7 @@ function listFiles(directory) {
6094
7390
  if (!existsSync5(directory)) return [];
6095
7391
  const files = [];
6096
7392
  for (const entry of readdirSync3(directory).sort()) {
6097
- const path = join7(directory, entry);
7393
+ const path = join8(directory, entry);
6098
7394
  if (statSync(path).isDirectory()) files.push(...listFiles(path));
6099
7395
  else if (MODEL_FILE.test(entry)) files.push(path);
6100
7396
  }
@@ -6476,9 +7772,10 @@ import {
6476
7772
  ConsoleKernel,
6477
7773
  DatabaseManager as DatabaseManager3,
6478
7774
  HttpRequest,
7775
+ PaginationState,
6479
7776
  RouteModelResolver
6480
7777
  } from "@orieljs/contracts";
6481
- import { currentContainer as currentContainer4 } from "@orieljs/container";
7778
+ import { BindingResolutionError, currentContainer as currentContainer4 } from "@orieljs/container";
6482
7779
  import { ServiceProvider } from "@orieljs/support";
6483
7780
  var env = (key, fallback) => {
6484
7781
  const value = process.env[key];
@@ -6535,9 +7832,21 @@ function currentRequest() {
6535
7832
  return void 0;
6536
7833
  }
6537
7834
  }
7835
+ function paginationState() {
7836
+ const container = currentContainer4();
7837
+ if (!container?.bound(PaginationState)) return void 0;
7838
+ try {
7839
+ return container.make(PaginationState);
7840
+ } catch (error) {
7841
+ if (error instanceof BindingResolutionError) return void 0;
7842
+ throw error;
7843
+ }
7844
+ }
6538
7845
  function usePaginationResolvers() {
6539
- AbstractPaginator.currentPathResolver = () => currentRequest()?.url() ?? "/";
7846
+ AbstractPaginator.currentPathResolver = () => paginationState()?.currentPath() ?? currentRequest()?.url() ?? "/";
6540
7847
  AbstractPaginator.currentPageResolver = (pageName) => {
7848
+ const state = paginationState()?.currentPage(pageName);
7849
+ if (state !== void 0) return state;
6541
7850
  const page = Number(currentRequest()?.input(pageName));
6542
7851
  return Number.isInteger(page) && page >= 1 ? page : 1;
6543
7852
  };
@@ -6549,11 +7858,15 @@ var DatabaseServiceProvider = class extends ServiceProvider {
6549
7858
  Model.clearBootedModels();
6550
7859
  this.mergeConfigFrom(databaseConfigDefaults(this.app), "database");
6551
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
+ });
6552
7864
  this.app.singleton(ModelRegistry);
6553
7865
  this.app.singleton(RouteModelResolver, () => new RouteModelResolverImpl(this.app.make(ModelRegistry)));
6554
7866
  this.app.bind(SchemaBuilderToken, () => this.manager().getSchemaBuilder());
6555
7867
  }
6556
7868
  async boot() {
7869
+ Model.warnOnRelationPropertyAccess(!this.app.isProduction());
6557
7870
  usePaginationResolvers();
6558
7871
  const registry2 = this.app.make(ModelRegistry);
6559
7872
  const classes = this.app.bound(ClassRegistry2) ? this.app.make(ClassRegistry2) : void 0;
@@ -6587,7 +7900,11 @@ export {
6587
7900
  DatabaseConfigError,
6588
7901
  DatabaseError,
6589
7902
  DatabaseManagerImpl,
7903
+ DatabaseNotification,
7904
+ DatabaseNotificationCollection,
7905
+ DatabaseNotificationsRelation,
6590
7906
  DatabaseServiceProvider,
7907
+ EloquentCollection,
6591
7908
  Expression,
6592
7909
  Factory,
6593
7910
  Faker,
@@ -6595,10 +7912,13 @@ export {
6595
7912
  ForeignIdColumnDefinition,
6596
7913
  ForeignKeyDefinition,
6597
7914
  Grammar,
7915
+ HasDatabaseNotifications,
6598
7916
  HasMany,
6599
7917
  HasManyThrough,
6600
7918
  HasOne,
6601
7919
  HasOneOrMany,
7920
+ HasUlids,
7921
+ HasUuids,
6602
7922
  InvalidCastError,
6603
7923
  JoinClause,
6604
7924
  LengthAwarePaginator,
@@ -6656,6 +7976,7 @@ export {
6656
7976
  isDateCast,
6657
7977
  isEquivalent,
6658
7978
  isJsonCast,
7979
+ isTableRebuild,
6659
7980
  loadRelations,
6660
7981
  migrationDatePrefix,
6661
7982
  modelEventName,