@orieljs/database 0.1.0-alpha.4 → 0.1.0-alpha.6

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
@@ -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,9 @@ 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
+ }
680
698
  var Grammar = class {
681
699
  constructor(driver) {
682
700
  this.driver = driver;
@@ -757,6 +775,8 @@ var Grammar = class {
757
775
  }
758
776
  case "null":
759
777
  return sql2`${this.wrap(where.column)} ${sql2.raw(where.not ? "is not null" : "is null")}`;
778
+ case "like":
779
+ return this.compileWhereLike(where);
760
780
  case "between":
761
781
  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
782
  case "column":
@@ -769,6 +789,18 @@ var Grammar = class {
769
789
  return rawWithBindings(where.sql, where.bindings.map((value) => this.prepare(value)));
770
790
  }
771
791
  }
792
+ /**
793
+ * whereLike() per driver, as Laravel 12's grammars: Postgres compares the column as text with ilike (like when
794
+ * case-sensitive); MySQL uses like (like binary); SQLite uses like, or glob with the pattern translated.
795
+ */
796
+ compileWhereLike(where) {
797
+ const not = where.not ? "not " : "";
798
+ const column = this.wrap(where.column);
799
+ if (this.driver === "pgsql") return sql2`${column}::text ${sql2.raw(`${not}${where.caseSensitive ? "like" : "ilike"}`)} ${this.parameter(where.value)}`;
800
+ if (this.driver === "mysql") return sql2`${column} ${sql2.raw(`${not}${where.caseSensitive ? "like binary" : "like"}`)} ${this.parameter(where.value)}`;
801
+ if (where.caseSensitive) return sql2`${column} ${sql2.raw(`${not}glob`)} ${this.parameter(likeToGlob(where.value))}`;
802
+ return sql2`${column} ${sql2.raw(`${not}like`)} ${this.parameter(where.value)}`;
803
+ }
772
804
  compileJoin(joinClause) {
773
805
  if (joinClause.joinType === "cross") return sql2`cross join ${this.wrapTable(joinClause.table)}`;
774
806
  return sql2`${sql2.raw(joinClause.joinType)} join ${this.wrapTable(joinClause.table)} ${this.compileWheres(joinClause.wheres, "on") ?? EMPTY}`;
@@ -1023,6 +1055,25 @@ var Builder = class _Builder {
1023
1055
  this.wheres.push({ type: "between", column, values, not: true, boolean: "and" });
1024
1056
  return this;
1025
1057
  }
1058
+ /**
1059
+ * Laravel's whereLike(): the value is the pattern, `%` and `_` included (`whereLike('title', `%${term}%`)`).
1060
+ * Case-insensitive unless caseSensitive: ilike on Postgres, like on MySQL and SQLite (their like already ignores
1061
+ * case: MySQL through the column's collation, SQLite for ASCII letters). Case-sensitive is like on Postgres,
1062
+ * like binary on MySQL and glob on SQLite.
1063
+ */
1064
+ whereLike(column, value, caseSensitive = false, boolean = "and", not = false) {
1065
+ this.wheres.push({ type: "like", column, value, caseSensitive, not, boolean });
1066
+ return this;
1067
+ }
1068
+ orWhereLike(column, value, caseSensitive = false) {
1069
+ return this.whereLike(column, value, caseSensitive, "or");
1070
+ }
1071
+ whereNotLike(column, value, caseSensitive = false, boolean = "and") {
1072
+ return this.whereLike(column, value, caseSensitive, boolean, true);
1073
+ }
1074
+ orWhereNotLike(column, value, caseSensitive = false) {
1075
+ return this.whereNotLike(column, value, caseSensitive, "or");
1076
+ }
1026
1077
  /** Compares two columns: whereColumn('updated_at', '>', 'created_at'). */
1027
1078
  whereColumn(first, operatorOrSecond, second, boolean = "and") {
1028
1079
  const [operator, other] = second === void 0 ? ["=", operatorOrSecond] : [operatorOrSecond, second];
@@ -1146,10 +1197,16 @@ var Builder = class _Builder {
1146
1197
  this.lockMode = "share";
1147
1198
  return this;
1148
1199
  }
1149
- /** Calls callback(this, value) when value is truthy (or the default callback otherwise). */
1150
1200
  when(value, callback, otherwise) {
1151
- if (value) callback(this, value);
1152
- else otherwise?.(this, value);
1201
+ const resolved = typeof value === "function" ? value(this) : value;
1202
+ if (resolved) callback(this, resolved);
1203
+ else otherwise?.(this, resolved);
1204
+ return this;
1205
+ }
1206
+ unless(value, callback, otherwise) {
1207
+ const resolved = typeof value === "function" ? value(this) : value;
1208
+ if (!resolved) callback(this, resolved);
1209
+ else otherwise?.(this, resolved);
1153
1210
  return this;
1154
1211
  }
1155
1212
  tap(callback) {
@@ -2743,7 +2800,7 @@ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
2743
2800
  import { DatabaseManager as DatabaseManager2 } from "@orieljs/contracts";
2744
2801
  import { Collection as Collection11 } from "@orieljs/collections";
2745
2802
  import { currentContainer as currentContainer3, inject } from "@orieljs/container";
2746
- import { Str as Str5 } from "@orieljs/support";
2803
+ import { Str as Str6 } from "@orieljs/support";
2747
2804
 
2748
2805
  // Eloquent/Builder.ts
2749
2806
  import { Collection as Collection4 } from "@orieljs/collections";
@@ -2880,6 +2937,18 @@ var Builder2 = class extends Builder {
2880
2937
  whereBetween(column, values) {
2881
2938
  return super.whereBetween(column, values);
2882
2939
  }
2940
+ whereLike(column, value, caseSensitive = false, boolean = "and", not = false) {
2941
+ return super.whereLike(column, value, caseSensitive, boolean, not);
2942
+ }
2943
+ orWhereLike(column, value, caseSensitive = false) {
2944
+ return super.orWhereLike(column, value, caseSensitive);
2945
+ }
2946
+ whereNotLike(column, value, caseSensitive = false, boolean = "and") {
2947
+ return super.whereNotLike(column, value, caseSensitive, boolean);
2948
+ }
2949
+ orWhereNotLike(column, value, caseSensitive = false) {
2950
+ return super.orWhereNotLike(column, value, caseSensitive);
2951
+ }
2883
2952
  orderBy(column, direction = "asc") {
2884
2953
  return super.orderBy(column, direction);
2885
2954
  }
@@ -3069,12 +3138,19 @@ var Builder2 = class extends Builder {
3069
3138
  const key = column.includes(".") ? column.slice(column.lastIndexOf(".") + 1) : column;
3070
3139
  return new Collection4(rows.map((row) => this.model.newInstance().setRawAttributes({ [key]: row[key] }).getAttribute(key)));
3071
3140
  }
3141
+ /** Whether `id` can't be one of the model's unique ids (not a UUID for HasUuids): it matches no row. */
3142
+ isMalformedKey(id) {
3143
+ return this.model.uniqueIds().includes(this.model.getKeyName()) && !this.model.isValidUniqueId(id);
3144
+ }
3145
+ /** A malformed unique id (HasUuids, HasUlids) finds nothing without a query, as route model binding does. */
3072
3146
  async find(id) {
3147
+ if (this.isMalformedKey(id)) return void 0;
3073
3148
  return this.clone().whereKey(id).first();
3074
3149
  }
3075
3150
  async findMany(ids) {
3076
- if (!ids.length) return new Collection4();
3077
- return this.clone().whereKey([...ids]).get();
3151
+ const keys = ids.filter((id) => !this.isMalformedKey(id));
3152
+ if (!keys.length) return new Collection4();
3153
+ return this.clone().whereKey(keys).get();
3078
3154
  }
3079
3155
  async findOrFail(id) {
3080
3156
  if (Array.isArray(id)) {
@@ -3330,7 +3406,7 @@ import { existsSync, readdirSync } from "fs";
3330
3406
  import { join as join3 } from "path";
3331
3407
  import { pathToFileURL } from "url";
3332
3408
  import { Collection as Collection8 } from "@orieljs/collections";
3333
- import { Str as Str4 } from "@orieljs/support";
3409
+ import { Str as Str5 } from "@orieljs/support";
3334
3410
 
3335
3411
  // Eloquent/Relations/BelongsTo.ts
3336
3412
  import { Str as Str3 } from "@orieljs/support";
@@ -3722,6 +3798,7 @@ var BelongsToMany = class extends Relation {
3722
3798
  };
3723
3799
 
3724
3800
  // Eloquent/Relations/HasOneOrMany.ts
3801
+ import { Str as Str4 } from "@orieljs/support";
3725
3802
  var HasOneOrMany = class extends Relation {
3726
3803
  /**
3727
3804
  * @param foreignKey the qualified foreign key on the related table ('comments.post_id')
@@ -3738,6 +3815,8 @@ var HasOneOrMany = class extends Relation {
3738
3815
  foreignKey;
3739
3816
  localKey;
3740
3817
  morph;
3818
+ /** The relation on each related model that chaperone() points back at the parent. */
3819
+ inverseRelationship;
3741
3820
  /** 'post_id' */
3742
3821
  getForeignKeyName() {
3743
3822
  return this.foreignKey.slice(this.foreignKey.lastIndexOf(".") + 1);
@@ -3759,6 +3838,61 @@ var HasOneOrMany = class extends Relation {
3759
3838
  getMorphClass() {
3760
3839
  return this.morph?.value;
3761
3840
  }
3841
+ /**
3842
+ * Laravel's chaperone(): every related model this relation loads, eagerly or lazily, or makes, gets the parent as
3843
+ * its `relation` (guessed when not given: post_id → post, the parent's class, owner), so reading it needs no query:
3844
+ * `comments() { return this.hasMany(Comment).chaperone() }`.
3845
+ */
3846
+ chaperone(relation) {
3847
+ const name = relation ?? this.guessInverseRelation();
3848
+ if (name === void 0 || !this.model.isRelation(name)) throw new RelationNotFoundError(this.model.constructor.name, name ?? "null");
3849
+ this.inverseRelationship = name;
3850
+ return this;
3851
+ }
3852
+ /** Laravel's inverse(): chaperone() under its other name. */
3853
+ inverse(relation) {
3854
+ return this.chaperone(relation);
3855
+ }
3856
+ withoutChaperone() {
3857
+ this.inverseRelationship = void 0;
3858
+ return this;
3859
+ }
3860
+ withoutInverse() {
3861
+ return this.withoutChaperone();
3862
+ }
3863
+ getInverseRelationship() {
3864
+ return this.inverseRelationship;
3865
+ }
3866
+ /** The first of the possible names that is a relation of the related model. */
3867
+ guessInverseRelation() {
3868
+ return this.getPossibleInverseRelations().find((name) => this.model.isRelation(name));
3869
+ }
3870
+ /** Laravel's candidates: the morph name, the foreign key without the parent's key, the parent's class, owner, parent. */
3871
+ getPossibleInverseRelations() {
3872
+ const key = this.parent.getKeyName();
3873
+ const names = [
3874
+ this.morph ? Str4.beforeLast(this.getMorphType(), "_type") : "",
3875
+ Str4.camel(Str4.beforeLast(this.getForeignKeyName(), key)),
3876
+ Str4.camel(Str4.beforeLast(this.parent.getForeignKey(), key)),
3877
+ Str4.camel(this.parent.constructor.name),
3878
+ "owner",
3879
+ this.parent.constructor === this.model.constructor ? "parent" : ""
3880
+ ];
3881
+ return [...new Set(names.filter((name) => name !== ""))];
3882
+ }
3883
+ /** Sets the parent on a related model, when chaperone() named the relation. */
3884
+ applyInverseRelationToModel(model, parent = this.parent) {
3885
+ if (model && this.inverseRelationship !== void 0) model.setRelation(this.inverseRelationship, parent);
3886
+ return model;
3887
+ }
3888
+ applyInverseRelationToMany(models, parent = this.parent) {
3889
+ for (const model of models) this.applyInverseRelationToModel(model, parent);
3890
+ return models;
3891
+ }
3892
+ /** The relation query's rows (get(), first(), paginate(), …), pointing back at the parent with chaperone(). */
3893
+ async runSelect() {
3894
+ return this.applyInverseRelationToMany(await super.runSelect());
3895
+ }
3762
3896
  addConstraints() {
3763
3897
  this.where(this.foreignKey, "=", this.getParentKey());
3764
3898
  this.whereNotNull(this.foreignKey);
@@ -3792,7 +3926,7 @@ var HasOneOrMany = class extends Relation {
3792
3926
  setForeignAttributes(model) {
3793
3927
  model.setAttribute(this.getForeignKeyName(), this.getParentKey());
3794
3928
  if (this.morph) model.setAttribute(this.getMorphType(), this.morph.value);
3795
- return model;
3929
+ return this.applyInverseRelationToModel(model);
3796
3930
  }
3797
3931
  async saveMany(models) {
3798
3932
  const saved = [];
@@ -3947,13 +4081,13 @@ var Factory = class _Factory {
3947
4081
  }
3948
4082
  /** Creates related models for each created model: has(Post.factory().count(3)) (relationship default: 'posts'). */
3949
4083
  has(factory, relationship, pivot = {}) {
3950
- const name = relationship ?? Str4.camel(Str4.plural(new factory.model().constructor.name));
4084
+ const name = relationship ?? Str5.camel(Str5.plural(new factory.model().constructor.name));
3951
4085
  return this.newInstance({ hasRelations: [...this.hasRelations, { factory, relationship: name, pivot }] });
3952
4086
  }
3953
4087
  /** Sets a belongsTo parent: for(User.factory()) or for(user) (relationship default: 'user'). Created once. */
3954
4088
  for(parent, relationship) {
3955
4089
  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) }] });
4090
+ return this.newInstance({ forRelations: [...this.forRelations, { parent, relationship: relationship ?? Str5.camel(cls.name) }] });
3957
4091
  }
3958
4092
  afterMaking(callback) {
3959
4093
  return this.newInstance({ afterMakingCallbacks: [...this.afterMakingCallbacks, callback] });
@@ -4124,7 +4258,8 @@ var HasMany = class extends HasOneOrMany {
4124
4258
  match(models, results, relation) {
4125
4259
  const dictionary = this.buildDictionary(results);
4126
4260
  for (const model of models) {
4127
- model.setRelation(relation, new Collection9(dictionary.get(String(model.getAttribute(this.localKey))) ?? []));
4261
+ const children = this.applyInverseRelationToMany(dictionary.get(String(model.getAttribute(this.localKey))) ?? [], model);
4262
+ model.setRelation(relation, new Collection9(children));
4128
4263
  }
4129
4264
  return models;
4130
4265
  }
@@ -4238,7 +4373,7 @@ var HasOne = class extends HasOneOrMany {
4238
4373
  match(models, results, relation) {
4239
4374
  const dictionary = this.buildDictionary(results);
4240
4375
  for (const model of models) {
4241
- model.setRelation(relation, dictionary.get(String(model.getAttribute(this.localKey)))?.[0] ?? null);
4376
+ model.setRelation(relation, this.applyInverseRelationToModel(dictionary.get(String(model.getAttribute(this.localKey)))?.[0] ?? null, model));
4242
4377
  }
4243
4378
  return models;
4244
4379
  }
@@ -4287,7 +4422,7 @@ function installScopeProxies(cls) {
4287
4422
  for (const key of Object.getOwnPropertyNames(current)) {
4288
4423
  if (!key.startsWith("scope") || key.length <= 5) continue;
4289
4424
  if (typeof Reflect.get(current, key) !== "function") continue;
4290
- const name = Str5.lcfirst(key.slice(5));
4425
+ const name = Str6.lcfirst(key.slice(5));
4291
4426
  if (name in cls) continue;
4292
4427
  Object.defineProperty(cls, name, {
4293
4428
  configurable: true,
@@ -4304,6 +4439,7 @@ function methodOf(model, name) {
4304
4439
  const value = Reflect.get(Object.getPrototypeOf(model), name);
4305
4440
  return typeof value === "function" ? value : void 0;
4306
4441
  }
4442
+ var serializing = /* @__PURE__ */ new WeakSet();
4307
4443
  function serializeDate(date) {
4308
4444
  return date.toISOString().replace(/\.(\d{3})Z$/, ".$1000Z");
4309
4445
  }
@@ -4494,6 +4630,14 @@ var Model = class _Model {
4494
4630
  const query = this.query();
4495
4631
  return Reflect.apply(query.where, query, args);
4496
4632
  }
4633
+ static when(...args) {
4634
+ const query = this.query();
4635
+ return Reflect.apply(query.when, query, args);
4636
+ }
4637
+ static unless(...args) {
4638
+ const query = this.query();
4639
+ return Reflect.apply(query.unless, query, args);
4640
+ }
4497
4641
  static whereKey(id) {
4498
4642
  return this.query().whereKey(id);
4499
4643
  }
@@ -4512,6 +4656,13 @@ var Model = class _Model {
4512
4656
  static whereBetween(column, values) {
4513
4657
  return this.query().whereBetween(column, values);
4514
4658
  }
4659
+ /** Post.whereLike('title', `%${term}%`): case-insensitive unless caseSensitive (see the query builder's whereLike()). */
4660
+ static whereLike(column, value, caseSensitive = false) {
4661
+ return this.query().whereLike(column, value, caseSensitive);
4662
+ }
4663
+ static whereNotLike(column, value, caseSensitive = false) {
4664
+ return this.query().whereNotLike(column, value, caseSensitive);
4665
+ }
4515
4666
  static whereColumn(first, operatorOrSecond, second) {
4516
4667
  return this.query().whereColumn(first, operatorOrSecond, second);
4517
4668
  }
@@ -4744,7 +4895,7 @@ var Model = class _Model {
4744
4895
  /** Every cast, including the implied ones: the incrementing key (int) and the timestamp columns (datetime). */
4745
4896
  getCasts() {
4746
4897
  const implied = {};
4747
- if (this.incrementing) implied[this.getKeyName()] = this.keyType === "int" ? "int" : "string";
4898
+ if (this.getIncrementing()) implied[this.getKeyName()] = this.getKeyType() === "int" ? "int" : "string";
4748
4899
  if (this.usesTimestamps()) {
4749
4900
  const created = this.getCreatedAtColumn();
4750
4901
  const updated = this.getUpdatedAtColumn();
@@ -4855,7 +5006,7 @@ var Model = class _Model {
4855
5006
  }
4856
5007
  }
4857
5008
  mutatorFor(kind, key) {
4858
- return methodOf(this, `${kind}${Str5.studly(key)}Attribute`);
5009
+ return methodOf(this, `${kind}${Str6.studly(key)}Attribute`);
4859
5010
  }
4860
5011
  // ---------------------------------------------------------------- keys, table and naming
4861
5012
  getKeyName() {
@@ -4867,11 +5018,34 @@ var Model = class _Model {
4867
5018
  getIncrementing() {
4868
5019
  return this.incrementing;
4869
5020
  }
5021
+ /** Whether new rows get unique string ids before `creating` (HasUuids, HasUlids). */
5022
+ usesUniqueIds() {
5023
+ return false;
5024
+ }
5025
+ /** The columns that get a unique id (HasUuids and HasUlids: the primary key). */
5026
+ uniqueIds() {
5027
+ return [];
5028
+ }
5029
+ /** A new unique id (HasUuids: a version 7 UUID; HasUlids: a lower-case ULID). */
5030
+ newUniqueId() {
5031
+ return void 0;
5032
+ }
5033
+ /** Whether a value has the shape of this model's unique ids (HasUuids: a UUID). Any value passes by default. */
5034
+ isValidUniqueId(_value) {
5035
+ return true;
5036
+ }
5037
+ /** Fills each empty unique id column with newUniqueId() (Laravel's setUniqueIds()). */
5038
+ setUniqueIds() {
5039
+ for (const column of this.uniqueIds()) {
5040
+ const value = this.getAttribute(column);
5041
+ if (value === void 0 || value === null || value === "") this.setAttribute(column, this.newUniqueId());
5042
+ }
5043
+ }
4870
5044
  getKey() {
4871
5045
  return this.getAttribute(this.getKeyName());
4872
5046
  }
4873
5047
  getTable() {
4874
- return this.table ?? Str5.snake(Str5.plural(this.constructor.name));
5048
+ return this.table ?? Str6.snake(Str6.plural(this.constructor.name));
4875
5049
  }
4876
5050
  getConnectionName() {
4877
5051
  return this.connection;
@@ -4888,7 +5062,7 @@ var Model = class _Model {
4888
5062
  }
4889
5063
  /** The conventional foreign key pointing at this model: user_id for User. */
4890
5064
  getForeignKey() {
4891
- return `${Str5.snake(this.constructor.name)}_${this.getKeyName()}`;
5065
+ return `${Str6.snake(this.constructor.name)}_${this.getKeyName()}`;
4892
5066
  }
4893
5067
  getRouteKeyName() {
4894
5068
  return this.getKeyName();
@@ -4898,11 +5072,13 @@ var Model = class _Model {
4898
5072
  }
4899
5073
  /**
4900
5074
  * 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.
5075
+ * soft-deleted row isn't found). A non-numeric value for an integer primary key, or a value that isn't a UUID
5076
+ * (ULID) for a unique id column, finds nothing without a query.
4902
5077
  */
4903
5078
  async resolveRouteBinding(value, field) {
4904
5079
  const column = field ?? this.getRouteKeyName();
4905
- if (column === this.getKeyName() && this.keyType === "int" && !/^-?\d+$/.test(value)) return void 0;
5080
+ if (column === this.getKeyName() && this.getKeyType() === "int" && !/^-?\d+$/.test(value)) return void 0;
5081
+ if (this.uniqueIds().includes(column) && !this.isValidUniqueId(value)) return void 0;
4906
5082
  return this.resolveRouteBindingQuery(this.newQuery(), value, column).first();
4907
5083
  }
4908
5084
  /** Override to customize the binding query (Laravel's resolveRouteBindingQuery()). */
@@ -5120,6 +5296,7 @@ var Model = class _Model {
5120
5296
  if (!this.exists && created && !this.isDirty(created)) this.setAttribute(created, time);
5121
5297
  }
5122
5298
  async performInsert(query) {
5299
+ if (this.usesUniqueIds()) this.setUniqueIds();
5123
5300
  if (await this.fireModelEvent("creating") === false) return false;
5124
5301
  if (this.usesTimestamps()) this.updateTimestamps();
5125
5302
  const attributes = this.getAttributes();
@@ -5235,7 +5412,7 @@ var Model = class _Model {
5235
5412
  */
5236
5413
  belongsToMany(related, table, foreignPivotKey, relatedPivotKey, parentKey, relatedKey) {
5237
5414
  const instance = this.newRelatedInstance(related);
5238
- const joining = table ?? [Str5.snake(this.constructor.name), Str5.snake(related.name)].sort().join("_").toLowerCase();
5415
+ const joining = table ?? [Str6.snake(this.constructor.name), Str6.snake(related.name)].sort().join("_").toLowerCase();
5239
5416
  const relation = new BelongsToMany(
5240
5417
  instance,
5241
5418
  this,
@@ -5303,6 +5480,10 @@ var Model = class _Model {
5303
5480
  if (!instance.getConnectionName()) instance.setConnection(this.getConnectionName());
5304
5481
  return instance;
5305
5482
  }
5483
+ /** Whether the model has a relation method called `name` (Laravel's isRelation()). */
5484
+ isRelation(name) {
5485
+ return !(name in _Model.prototype) && methodOf(this, name) !== void 0;
5486
+ }
5306
5487
  /** Calls the relation method `name` (post.comments()) and checks that it returns a relation. */
5307
5488
  getRelationInstance(name) {
5308
5489
  if (name in _Model.prototype) throw new RelationNotFoundError(this.constructor.name, name);
@@ -5397,9 +5578,18 @@ var Model = class _Model {
5397
5578
  this.appends = [.../* @__PURE__ */ new Set([...this.appends, ...attributes.flat()])];
5398
5579
  return this;
5399
5580
  }
5400
- /** Attributes (through accessors and casts, dates as ISO strings), appends and loaded relations, minus hidden ones. */
5581
+ /**
5582
+ * Attributes (through accessors and casts, dates as ISO strings), appends and loaded relations, minus hidden ones.
5583
+ * A model met again while its own toArray() runs (a child chaperone() pointed back at it) gives its attributes only.
5584
+ */
5401
5585
  toArray() {
5402
- return { ...this.attributesToArray(), ...this.relationsToArray() };
5586
+ if (serializing.has(this)) return this.attributesToArray();
5587
+ serializing.add(this);
5588
+ try {
5589
+ return { ...this.attributesToArray(), ...this.relationsToArray() };
5590
+ } finally {
5591
+ serializing.delete(this);
5592
+ }
5403
5593
  }
5404
5594
  toJSON() {
5405
5595
  return this.toArray();
@@ -5422,7 +5612,7 @@ var Model = class _Model {
5422
5612
  relationsToArray() {
5423
5613
  const result = {};
5424
5614
  for (const [name, value] of Object.entries(this.relations)) {
5425
- const key = Str5.snake(name);
5615
+ const key = Str6.snake(name);
5426
5616
  if (!this.isArrayableKey(key)) continue;
5427
5617
  if (value === null || value === void 0) result[key] = null;
5428
5618
  else if (value instanceof Collection11) result[key] = value.toArray();
@@ -5471,6 +5661,128 @@ var Pivot = class extends Model {
5471
5661
  timestamps = false;
5472
5662
  };
5473
5663
 
5664
+ // Eloquent/DatabaseNotification.ts
5665
+ import { Collection as Collection12 } from "@orieljs/collections";
5666
+
5667
+ // Eloquent/HasUniqueStringIds.ts
5668
+ import { Str as Str7 } from "@orieljs/support";
5669
+ function uniqueStringIds(Base, generate, valid) {
5670
+ return class WithUniqueStringIds extends Base {
5671
+ usesUniqueIds() {
5672
+ return true;
5673
+ }
5674
+ uniqueIds() {
5675
+ return [this.getKeyName()];
5676
+ }
5677
+ newUniqueId() {
5678
+ return generate();
5679
+ }
5680
+ isValidUniqueId(value) {
5681
+ return valid(value);
5682
+ }
5683
+ getKeyType() {
5684
+ return this.uniqueIds().includes(this.getKeyName()) ? "string" : super.getKeyType();
5685
+ }
5686
+ getIncrementing() {
5687
+ return this.uniqueIds().includes(this.getKeyName()) ? false : super.getIncrementing();
5688
+ }
5689
+ };
5690
+ }
5691
+ function HasUuids(Base) {
5692
+ return uniqueStringIds(Base, () => Str7.uuid7(), Str7.isUuid);
5693
+ }
5694
+ function HasUlids(Base) {
5695
+ return uniqueStringIds(Base, () => Str7.ulid().toLowerCase(), Str7.isUlid);
5696
+ }
5697
+
5698
+ // Eloquent/DatabaseNotification.ts
5699
+ var DatabaseNotification = class extends HasUuids(Model) {
5700
+ table = "notifications";
5701
+ keyType = "string";
5702
+ incrementing = false;
5703
+ guarded = [];
5704
+ casts = { data: "array", read_at: "datetime" };
5705
+ /** The model the notification was sent to. */
5706
+ notifiable() {
5707
+ return this.morphTo("notifiable");
5708
+ }
5709
+ /** Sets read_at to now and saves, unless it is already read. */
5710
+ async markAsRead() {
5711
+ if (this.unread()) await this.forceFill({ read_at: this.freshTimestamp() }).save();
5712
+ }
5713
+ /** Clears read_at and saves, unless it is already unread. */
5714
+ async markAsUnread() {
5715
+ if (this.read()) await this.forceFill({ read_at: null }).save();
5716
+ }
5717
+ read() {
5718
+ return this.read_at !== null && this.read_at !== void 0;
5719
+ }
5720
+ unread() {
5721
+ return !this.read();
5722
+ }
5723
+ /** `query.read()`: only read notifications. */
5724
+ static scopeRead(query) {
5725
+ return query.whereNotNull("read_at");
5726
+ }
5727
+ /** `query.unread()`: only unread notifications. */
5728
+ static scopeUnread(query) {
5729
+ return query.whereNull("read_at");
5730
+ }
5731
+ };
5732
+ var DatabaseNotificationCollection = class extends Collection12 {
5733
+ /** Marks every notification as read (one save each, as in Laravel). */
5734
+ async markAsRead() {
5735
+ for (const notification of this.all()) await notification.markAsRead();
5736
+ }
5737
+ /** Marks every notification as unread. */
5738
+ async markAsUnread() {
5739
+ for (const notification of this.all()) await notification.markAsUnread();
5740
+ }
5741
+ };
5742
+ var DatabaseNotificationsRelation = class extends MorphMany {
5743
+ async get() {
5744
+ return new DatabaseNotificationCollection(await this.runSelect());
5745
+ }
5746
+ async getResults() {
5747
+ const key = this.getParentKey();
5748
+ return key === null || key === void 0 ? new DatabaseNotificationCollection() : this.get();
5749
+ }
5750
+ initRelation(models, relation) {
5751
+ for (const model of models) model.setRelation(relation, new DatabaseNotificationCollection());
5752
+ return models;
5753
+ }
5754
+ match(models, results, relation) {
5755
+ const dictionary = this.buildDictionary(results);
5756
+ for (const model of models) {
5757
+ model.setRelation(relation, new DatabaseNotificationCollection(dictionary.get(String(model.getAttribute(this.localKey))) ?? []));
5758
+ }
5759
+ return models;
5760
+ }
5761
+ };
5762
+
5763
+ // Eloquent/HasDatabaseNotifications.ts
5764
+ function HasDatabaseNotifications(Base) {
5765
+ class WithDatabaseNotifications extends Base {
5766
+ notifications() {
5767
+ const related = this.newRelatedInstance(DatabaseNotification);
5768
+ return new DatabaseNotificationsRelation(
5769
+ related,
5770
+ this,
5771
+ related.qualifyColumn("notifiable_type"),
5772
+ related.qualifyColumn("notifiable_id"),
5773
+ this.getKeyName()
5774
+ ).latest();
5775
+ }
5776
+ readNotifications() {
5777
+ return this.notifications().whereNotNull("read_at");
5778
+ }
5779
+ unreadNotifications() {
5780
+ return this.notifications().whereNull("read_at");
5781
+ }
5782
+ }
5783
+ return WithDatabaseNotifications;
5784
+ }
5785
+
5474
5786
  // Migrations/Migration.ts
5475
5787
  var Migration = class {
5476
5788
  /** The connection to run on (default: the default connection). */
@@ -5482,7 +5794,7 @@ var Migration = class {
5482
5794
  // Migrations/MigrationCreator.ts
5483
5795
  import { existsSync as existsSync2, mkdirSync, writeFileSync } from "fs";
5484
5796
  import { join as join4 } from "path";
5485
- import { Str as Str6 } from "@orieljs/support";
5797
+ import { Str as Str8 } from "@orieljs/support";
5486
5798
  var MIGRATION_CREATE_STUB = `import { Migration, Schema } from '{{ importSource }}'
5487
5799
 
5488
5800
  export default class extends Migration {
@@ -5540,7 +5852,7 @@ function migrationDatePrefix(date = /* @__PURE__ */ new Date()) {
5540
5852
  var MigrationCreator = class {
5541
5853
  /** Returns the path of the new file. */
5542
5854
  create(name, path, options = {}) {
5543
- const snake = Str6.snake(name.trim());
5855
+ const snake = Str8.snake(name.trim());
5544
5856
  let table = options.table ?? options.create;
5545
5857
  let create = options.create !== void 0;
5546
5858
  if (table === void 0) {
@@ -5789,7 +6101,7 @@ import { pathToFileURL as pathToFileURL3 } from "url";
5789
6101
  // Types/TypeGenerator.ts
5790
6102
  import { mkdir, writeFile } from "fs/promises";
5791
6103
  import { dirname, relative, sep } from "path";
5792
- import { Str as Str7 } from "@orieljs/support";
6104
+ import { Str as Str9 } from "@orieljs/support";
5793
6105
  var INTEGER = /* @__PURE__ */ new Set(["int", "integer", "int2", "int4", "int8", "bigint", "smallint", "mediumint", "tinyint", "serial", "bigserial", "smallserial", "year"]);
5794
6106
  var FLOAT = /* @__PURE__ */ new Set(["float", "float4", "float8", "double", "double precision", "real"]);
5795
6107
  var BOOLEAN = /* @__PURE__ */ new Set(["bool", "boolean"]);
@@ -5824,7 +6136,7 @@ function accessors(model) {
5824
6136
  for (let proto = model.prototype; proto && proto !== Model.prototype; proto = Object.getPrototypeOf(proto)) {
5825
6137
  for (const key of Object.getOwnPropertyNames(proto)) {
5826
6138
  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);
6139
+ if (match && typeof Reflect.get(proto, key) === "function" && !found.has(Str9.snake(match[1]))) found.set(Str9.snake(match[1]), key);
5828
6140
  }
5829
6141
  }
5830
6142
  return [...found];
@@ -5834,7 +6146,7 @@ function scopes(model) {
5834
6146
  for (let current = model; current && current !== Model; current = Object.getPrototypeOf(current)) {
5835
6147
  for (const key of Object.getOwnPropertyNames(current)) {
5836
6148
  if (key.startsWith("scope") && key.length > 5 && typeof Reflect.get(current, key) === "function") {
5837
- const name = Str7.lcfirst(key.slice(5));
6149
+ const name = Str9.lcfirst(key.slice(5));
5838
6150
  if (!found.has(name)) found.set(name, key);
5839
6151
  }
5840
6152
  }
@@ -5947,6 +6259,11 @@ async function generateModelTypes(context) {
5947
6259
  await new TypeGenerator({ outputFile, importSource: context.typesImportSource }).write((await context.models()).all());
5948
6260
  return relative2(context.app.basePath(), outputFile);
5949
6261
  }
6262
+ async function writeModelTypes(context, command) {
6263
+ if (context.app.isProduction() || !existsSync4(context.app.basePath("types"))) return;
6264
+ const written = await generateModelTypes(context);
6265
+ if (written) command.line(`Model types written to ${written}.`);
6266
+ }
5950
6267
  async function seedIfRequested(context, command) {
5951
6268
  const seeder = text(command.option("seeder"));
5952
6269
  if (command.option("seed") !== true && seeder === void 0) return;
@@ -5958,10 +6275,7 @@ function registerMigrationCommands(kernel, context) {
5958
6275
  if (!confirmToProceed(context, command)) return 1;
5959
6276
  await migrator(context, command).run(migrationPaths(context, command), { step: command.option("step") === true });
5960
6277
  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
- }
6278
+ await writeModelTypes(context, command);
5965
6279
  return 0;
5966
6280
  });
5967
6281
  define(kernel, "migrate:install {--database=}", "Create the migration repository", async (command) => {
@@ -5992,12 +6306,14 @@ function registerMigrationCommands(kernel, context) {
5992
6306
  else await instance.reset(paths);
5993
6307
  await instance.run(paths);
5994
6308
  await seedIfRequested(context, command);
6309
+ await writeModelTypes(context, command);
5995
6310
  return 0;
5996
6311
  });
5997
6312
  define(kernel, "migrate:fresh {--database=} {--force} {--path=*} {--seed} {--seeder=}", "Drop all tables and re-run all migrations", async (command) => {
5998
6313
  if (!confirmToProceed(context, command)) return 1;
5999
6314
  await migrator(context, command).fresh(migrationPaths(context, command));
6000
6315
  await seedIfRequested(context, command);
6316
+ await writeModelTypes(context, command);
6001
6317
  return 0;
6002
6318
  });
6003
6319
  define(kernel, "migrate:status {--database=} {--path=*}", "Show the status of each migration", async (command) => {
@@ -6052,7 +6368,7 @@ function registerModelTypesCommand(kernel, context) {
6052
6368
  import { existsSync as existsSync5, readdirSync as readdirSync3, statSync } from "fs";
6053
6369
  import { join as join7 } from "path";
6054
6370
  import { pathToFileURL as pathToFileURL4 } from "url";
6055
- import { Str as Str8 } from "@orieljs/support";
6371
+ import { Str as Str10 } from "@orieljs/support";
6056
6372
  var MODEL_FILE = /^(?!.*\.d\.[mc]?ts$).+\.(ts|js|mts|mjs)$/;
6057
6373
  var ModelRegistry = class {
6058
6374
  models = /* @__PURE__ */ new Map();
@@ -6078,7 +6394,7 @@ var ModelRegistry = class {
6078
6394
  }
6079
6395
  /** A model by class name or route parameter name: 'Post', 'post', 'blog_post' and 'blogPost' find BlogPost. */
6080
6396
  get(name) {
6081
- return this.models.get(name) ?? this.models.get(Str8.studly(name));
6397
+ return this.models.get(name) ?? this.models.get(Str10.studly(name));
6082
6398
  }
6083
6399
  resolve(name) {
6084
6400
  return this.get(name)?.model;
@@ -6476,9 +6792,10 @@ import {
6476
6792
  ConsoleKernel,
6477
6793
  DatabaseManager as DatabaseManager3,
6478
6794
  HttpRequest,
6795
+ PaginationState,
6479
6796
  RouteModelResolver
6480
6797
  } from "@orieljs/contracts";
6481
- import { currentContainer as currentContainer4 } from "@orieljs/container";
6798
+ import { BindingResolutionError, currentContainer as currentContainer4 } from "@orieljs/container";
6482
6799
  import { ServiceProvider } from "@orieljs/support";
6483
6800
  var env = (key, fallback) => {
6484
6801
  const value = process.env[key];
@@ -6535,9 +6852,21 @@ function currentRequest() {
6535
6852
  return void 0;
6536
6853
  }
6537
6854
  }
6855
+ function paginationState() {
6856
+ const container = currentContainer4();
6857
+ if (!container?.bound(PaginationState)) return void 0;
6858
+ try {
6859
+ return container.make(PaginationState);
6860
+ } catch (error) {
6861
+ if (error instanceof BindingResolutionError) return void 0;
6862
+ throw error;
6863
+ }
6864
+ }
6538
6865
  function usePaginationResolvers() {
6539
- AbstractPaginator.currentPathResolver = () => currentRequest()?.url() ?? "/";
6866
+ AbstractPaginator.currentPathResolver = () => paginationState()?.currentPath() ?? currentRequest()?.url() ?? "/";
6540
6867
  AbstractPaginator.currentPageResolver = (pageName) => {
6868
+ const state = paginationState()?.currentPage(pageName);
6869
+ if (state !== void 0) return state;
6541
6870
  const page = Number(currentRequest()?.input(pageName));
6542
6871
  return Number.isInteger(page) && page >= 1 ? page : 1;
6543
6872
  };
@@ -6587,6 +6916,9 @@ export {
6587
6916
  DatabaseConfigError,
6588
6917
  DatabaseError,
6589
6918
  DatabaseManagerImpl,
6919
+ DatabaseNotification,
6920
+ DatabaseNotificationCollection,
6921
+ DatabaseNotificationsRelation,
6590
6922
  DatabaseServiceProvider,
6591
6923
  Expression,
6592
6924
  Factory,
@@ -6595,10 +6927,13 @@ export {
6595
6927
  ForeignIdColumnDefinition,
6596
6928
  ForeignKeyDefinition,
6597
6929
  Grammar,
6930
+ HasDatabaseNotifications,
6598
6931
  HasMany,
6599
6932
  HasManyThrough,
6600
6933
  HasOne,
6601
6934
  HasOneOrMany,
6935
+ HasUlids,
6936
+ HasUuids,
6602
6937
  InvalidCastError,
6603
6938
  JoinClause,
6604
6939
  LengthAwarePaginator,