@duraxis/orm 0.1.0 → 0.2.2

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
@@ -1,4 +1,5 @@
1
1
  import { CommitOutcomeUnknownError, CommitOutcomeUnknownError as CommitOutcomeUnknownError$1, TransactionConflictError, TransactionConflictError as TransactionConflictError$1, UniqueIndexViolationError, normalizeCollection } from "@duraxis/core";
2
+ import { createHash } from "node:crypto";
2
3
  // src/metadata/decorator-metadata.ts
3
4
  var drafts = /* @__PURE__ */ new WeakMap();
4
5
  function ownDraft(entity) {
@@ -11,7 +12,9 @@ function mutableDraft(entity) {
11
12
  entityApplications: 0,
12
13
  columns: [],
13
14
  primaryKeys: [],
14
- indexes: []
15
+ indexes: [],
16
+ relations: [],
17
+ joinTables: []
15
18
  };
16
19
  drafts.set(entity, draft);
17
20
  }
@@ -72,6 +75,41 @@ function Index(nameOrOptions = {}, fields, compositeOptions = {}) {
72
75
  });
73
76
  };
74
77
  }
78
+ // src/decorators/relation.decorators.ts
79
+ function relation(kind, target, inverse, options) {
80
+ return (prototype, key) => {
81
+ mutableDraft(entityConstructor(prototype)).relations.push({
82
+ kind,
83
+ property: propertyName(key),
84
+ target,
85
+ ...inverse ? { inverse } : {},
86
+ ...options?.foreignKey ? { foreignKey: options.foreignKey } : {},
87
+ ...options?.onDelete ? { onDelete: options.onDelete } : {}
88
+ });
89
+ };
90
+ }
91
+ function ManyToOne(target, options) {
92
+ return relation("many-to-one", target, void 0, options);
93
+ }
94
+ function OneToMany(target, inverse) {
95
+ return relation("one-to-many", target, inverse, void 0);
96
+ }
97
+ function OneToOne(target, inverseOrOptions) {
98
+ return typeof inverseOrOptions == "function" ? relation("one-to-one", target, inverseOrOptions, void 0) : relation("one-to-one", target, void 0, inverseOrOptions);
99
+ }
100
+ function ManyToMany(target, inverse) {
101
+ return relation("many-to-many", target, inverse, void 0);
102
+ }
103
+ function JoinTable(options) {
104
+ return (prototype, key) => {
105
+ mutableDraft(entityConstructor(prototype)).joinTables.push({
106
+ property: propertyName(key),
107
+ name: options.name,
108
+ ...options.joinColumn ? { joinColumn: options.joinColumn } : {},
109
+ ...options.inverseJoinColumn ? { inverseJoinColumn: options.inverseJoinColumn } : {}
110
+ });
111
+ };
112
+ }
75
113
  // src/errors/index.ts
76
114
  var DuraxisOrmError = class extends Error {
77
115
  constructor(message, options) {
@@ -120,6 +158,7 @@ var EntityMetadata = class {
120
158
  primaryKey;
121
159
  columns;
122
160
  indexes;
161
+ relations;
123
162
  constructor(options) {
124
163
  this.entity = options.entity;
125
164
  this.collection = options.collection;
@@ -129,6 +168,10 @@ var EntityMetadata = class {
129
168
  ...index,
130
169
  fields: Object.freeze(index.fields.map((field) => Object.freeze({ ...field })))
131
170
  })));
171
+ this.relations = Object.freeze((options.relations ?? []).map((relation) => Object.freeze({
172
+ ...relation,
173
+ ...relation.joinTable ? { joinTable: Object.freeze({ ...relation.joinTable }) } : {}
174
+ })));
132
175
  this.#byProperty = new Map(this.columns.map((column) => [column.property, column]));
133
176
  this.#byField = new Map(this.columns.map((column) => [column.field, column]));
134
177
  Object.freeze(this);
@@ -139,9 +182,12 @@ var EntityMetadata = class {
139
182
  columnForField(field) {
140
183
  return this.#byField.get(field);
141
184
  }
185
+ relationForProperty(property) {
186
+ return this.relations.find((relation) => relation.property == property);
187
+ }
142
188
  };
143
189
  // src/metadata/metadata-validator.ts
144
- var NAME = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
190
+ var NAME$1 = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
145
191
  var TYPES = /* @__PURE__ */ new Set([
146
192
  "string",
147
193
  "number",
@@ -149,9 +195,9 @@ var TYPES = /* @__PURE__ */ new Set([
149
195
  "date"
150
196
  ]);
151
197
  function requireName(name, label) {
152
- if (typeof name != "string" || !NAME.test(name)) throw new InvalidMetadataError(`Invalid ${label}: ${String(name)}`);
198
+ if (typeof name != "string" || !NAME$1.test(name)) throw new InvalidMetadataError(`Invalid ${label}: ${String(name)}`);
153
199
  }
154
- function hierarchy(entity) {
200
+ function decoratorHierarchy(entity) {
155
201
  const result = [];
156
202
  let current = entity;
157
203
  while (typeof current == "function" && current != Function.prototype) {
@@ -166,7 +212,7 @@ function buildEntityMetadata(entity) {
166
212
  if (!own?.entityName) throw new InvalidMetadataError(`Class ${entity.name} is missing @Entity()`);
167
213
  if (own.entityApplications != 1) throw new InvalidMetadataError(`Class ${entity.name} has duplicate @Entity() decorators`);
168
214
  requireName(own.entityName, "entity name");
169
- const drafts = hierarchy(entity);
215
+ const drafts = decoratorHierarchy(entity);
170
216
  const columns = [];
171
217
  const byProperty = /* @__PURE__ */ new Map();
172
218
  const byField = /* @__PURE__ */ new Map();
@@ -236,10 +282,25 @@ function buildEntityMetadata(entity) {
236
282
  collection: own.entityName,
237
283
  primaryKey,
238
284
  columns,
239
- indexes
285
+ indexes,
286
+ relations: []
240
287
  });
241
288
  }
242
289
  // src/metadata/metadata-registry.ts
290
+ var NAME = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
291
+ function selectedProperty(selector) {
292
+ let selected;
293
+ selector(new Proxy(Object.create(null), { get(_target, property) {
294
+ if (typeof property != "string") throw new InvalidMetadataError("Invalid inverse selector");
295
+ selected = property;
296
+ return property;
297
+ } }));
298
+ if (!selected || !NAME.test(selected)) throw new InvalidMetadataError("Inverse relation selector must select one property");
299
+ return selected;
300
+ }
301
+ function defaultJoinField(entity) {
302
+ return `${entity.name.charAt(0).toLowerCase()}${entity.name.slice(1)}Id`;
303
+ }
243
304
  var MetadataRegistry = class {
244
305
  #metadata = /* @__PURE__ */ new Map();
245
306
  #collections = /* @__PURE__ */ new Map();
@@ -259,6 +320,84 @@ var MetadataRegistry = class {
259
320
  return metadata;
260
321
  }
261
322
  finalize() {
323
+ const preliminary = /* @__PURE__ */ new Map();
324
+ for (const raw of this.#metadata.values()) {
325
+ const metadata = raw;
326
+ const relations = [];
327
+ const drafts = decoratorHierarchy(metadata.entity);
328
+ const relationDrafts = drafts.flatMap((draft) => draft.relations);
329
+ const joinTables = drafts.flatMap((draft) => draft.joinTables);
330
+ const properties = /* @__PURE__ */ new Set();
331
+ for (const draft of relationDrafts) {
332
+ if (!NAME.test(draft.property) || properties.has(draft.property)) throw new InvalidMetadataError(`Invalid or duplicate relation: ${draft.property}`);
333
+ properties.add(draft.property);
334
+ const target = draft.target();
335
+ if (typeof target != "function" || !this.#metadata.has(target)) throw new InvalidMetadataError(`Relation ${metadata.collection}.${draft.property} targets an unregistered entity`);
336
+ const targetMetadata = this.get(target);
337
+ const column = draft.foreignKey ? metadata.columnForProperty(draft.foreignKey) : void 0;
338
+ const owner = draft.kind == "many-to-one" || draft.kind == "one-to-one" && !!draft.foreignKey;
339
+ if (owner && draft.property.length > 61) throw new InvalidMetadataError(`Owning relation name is too long: ${draft.property}`);
340
+ if (owner && (!column || column.type != "string")) throw new InvalidMetadataError(`Owning relation ${metadata.collection}.${draft.property} requires a string foreign-key column`);
341
+ if (draft.onDelete == "SET_NULL" && !column?.nullable) throw new InvalidMetadataError(`SET_NULL relation ${metadata.collection}.${draft.property} requires a nullable column`);
342
+ const join = joinTables.find((item) => item.property == draft.property);
343
+ if (join && draft.kind != "many-to-many") throw new InvalidMetadataError(`@JoinTable is only valid on ManyToMany relations`);
344
+ if (join && !NAME.test(join.name)) throw new InvalidMetadataError(`Invalid join table name: ${join.name}`);
345
+ relations.push({
346
+ kind: draft.kind,
347
+ property: draft.property,
348
+ target,
349
+ targetCollection: targetMetadata.collection,
350
+ ...draft.inverse ? { inverseProperty: selectedProperty(draft.inverse) } : {},
351
+ owner: owner || !!join,
352
+ ...draft.foreignKey ? { foreignKeyProperty: draft.foreignKey } : {},
353
+ ...column ? { foreignKeyField: column.field } : {},
354
+ required: column?.required ?? false,
355
+ nullable: column?.nullable ?? false,
356
+ onDelete: draft.onDelete ?? (draft.kind == "many-to-many" ? "CASCADE" : "RESTRICT"),
357
+ ...join ? { joinTable: {
358
+ name: join.name,
359
+ ownerField: join.joinColumn ?? defaultJoinField(metadata.entity),
360
+ inverseField: join.inverseJoinColumn ?? defaultJoinField(target)
361
+ } } : {}
362
+ });
363
+ }
364
+ for (const join of joinTables) if (!relationDrafts.some((relation) => relation.property == join.property)) throw new InvalidMetadataError(`@JoinTable has no relation: ${join.property}`);
365
+ preliminary.set(metadata.entity, relations);
366
+ }
367
+ for (const raw of this.#metadata.values()) {
368
+ const metadata = raw;
369
+ for (const relation of preliminary.get(metadata.entity) ?? []) {
370
+ if (!relation.inverseProperty) continue;
371
+ const inverse = preliminary.get(relation.target)?.find((candidate) => candidate.property == relation.inverseProperty);
372
+ if (!inverse || inverse.target != metadata.entity) throw new InvalidMetadataError(`Invalid inverse relation ${metadata.collection}.${relation.property}`);
373
+ if (relation.kind == "many-to-many") {
374
+ if (inverse.kind != "many-to-many") throw new InvalidMetadataError("ManyToMany inverse must also be ManyToMany");
375
+ if (relation.owner && inverse.owner) throw new InvalidMetadataError("Only one ManyToMany side may declare @JoinTable");
376
+ if (!relation.owner && !inverse.owner) throw new InvalidMetadataError("One ManyToMany side must declare @JoinTable");
377
+ } else if (relation.kind == "one-to-many") {
378
+ if (inverse.kind != "many-to-one" || !inverse.owner) throw new InvalidMetadataError("OneToMany inverse must be an owning ManyToOne");
379
+ } else if (relation.kind == "one-to-one" && relation.owner == inverse.owner) throw new InvalidMetadataError("Exactly one OneToOne side must own the relation");
380
+ }
381
+ }
382
+ for (const [entity, raw] of [...this.#metadata]) {
383
+ const metadata = raw;
384
+ const relations = (preliminary.get(entity) ?? []).map((relation) => {
385
+ if (relation.kind != "many-to-many" || relation.joinTable) return relation;
386
+ const inverse = preliminary.get(relation.target).find((candidate) => candidate.property == relation.inverseProperty);
387
+ return {
388
+ ...relation,
389
+ joinTable: inverse.joinTable
390
+ };
391
+ });
392
+ this.#metadata.set(entity, new EntityMetadata({
393
+ entity: metadata.entity,
394
+ collection: metadata.collection,
395
+ primaryKey: metadata.primaryKey,
396
+ columns: metadata.columns,
397
+ indexes: metadata.indexes,
398
+ relations
399
+ }));
400
+ }
262
401
  this.#finalized = true;
263
402
  return this;
264
403
  }
@@ -614,6 +753,181 @@ var QueryMapper = class {
614
753
  throw new InvalidQueryError(`Invalid query value for ${property}`);
615
754
  }
616
755
  };
756
+ // src/relations/relation-loader.ts
757
+ var BATCH_SIZE = 64;
758
+ var MAX_DEPTH = 8;
759
+ var MAX_RELATED_ENTITIES = 1e5;
760
+ var RelationLoader = class {
761
+ metadata;
762
+ runtime;
763
+ #loaded = 0;
764
+ constructor(metadata, runtime) {
765
+ this.metadata = metadata;
766
+ this.runtime = runtime;
767
+ }
768
+ async load(entities, requested, signal) {
769
+ if (!requested || entities.length == 0) return entities;
770
+ await this.loadLevel(this.metadata, entities, requested, signal, 0, /* @__PURE__ */ new Set());
771
+ return entities;
772
+ }
773
+ async loadLevel(metadata, entities, requested, signal, depth, path) {
774
+ if (depth >= MAX_DEPTH) throw new Error(`Relation depth exceeds ${MAX_DEPTH}`);
775
+ for (const [property, nested] of Object.entries(requested)) {
776
+ if (!nested) continue;
777
+ signal?.throwIfAborted();
778
+ const relation = metadata.relationForProperty(property);
779
+ if (!relation) throw new Error(`Unknown relation: ${metadata.collection}.${property}`);
780
+ const edge = `${metadata.collection}.${property}`;
781
+ if (path.has(edge)) continue;
782
+ const related = await this.loadRelation(metadata, entities, relation, signal);
783
+ this.#loaded += related.length;
784
+ if (this.#loaded > MAX_RELATED_ENTITIES) throw new Error("Related entity expansion limit exceeded");
785
+ if (nested !== true && related.length) {
786
+ const target = this.runtime.registry.get(relation.target);
787
+ await this.loadLevel(target, related, nested, signal, depth + 1, /* @__PURE__ */ new Set([...path, edge]));
788
+ }
789
+ }
790
+ }
791
+ async loadRelation(metadata, entities, relation, signal) {
792
+ const target = this.runtime.registry.get(relation.target);
793
+ const targetMapper = new EntityMapper(target);
794
+ const related = /* @__PURE__ */ new Map();
795
+ if (relation.kind == "many-to-one" || relation.kind == "one-to-one" && relation.owner) {
796
+ const ids = this.values(entities, relation.foreignKeyProperty);
797
+ for (const row of await this.byIds(target.collection, ids, signal)) related.set(row.id, targetMapper.hydrate(row.id, row.document));
798
+ for (const entity of entities) {
799
+ const id = this.value(entity, relation.foreignKeyProperty);
800
+ this.define(entity, relation.property, typeof id == "string" ? related.get(id) ?? null : null);
801
+ }
802
+ return [...related.values()];
803
+ }
804
+ if (relation.kind == "one-to-many" || relation.kind == "one-to-one") {
805
+ const inverse = target.relationForProperty(relation.inverseProperty);
806
+ if (!inverse?.foreignKeyField) throw new Error(`Relation ${metadata.collection}.${relation.property} has no owning inverse`);
807
+ const ownerIds = this.values(entities, metadata.primaryKey);
808
+ const rows = await this.queryBatches(target.collection, inverse.foreignKeyField, ownerIds, signal);
809
+ const groups = /* @__PURE__ */ new Map();
810
+ for (const row of rows) {
811
+ const entity = targetMapper.hydrate(row.id, row.document);
812
+ related.set(row.id, entity);
813
+ const owner = row.document[inverse.foreignKeyField];
814
+ if (typeof owner == "string") groups.set(owner, [...groups.get(owner) ?? [], entity]);
815
+ }
816
+ for (const entity of entities) {
817
+ const id = this.value(entity, metadata.primaryKey);
818
+ const matches = typeof id == "string" ? groups.get(id) ?? [] : [];
819
+ this.define(entity, relation.property, relation.kind == "one-to-many" ? matches : matches[0] ?? null);
820
+ }
821
+ return [...related.values()];
822
+ }
823
+ const join = relation.joinTable;
824
+ const localField = relation.owner ? join.ownerField : join.inverseField;
825
+ const remoteField = relation.owner ? join.inverseField : join.ownerField;
826
+ const ownerIds = this.values(entities, metadata.primaryKey);
827
+ const junctions = await this.queryBatches(join.name, localField, ownerIds, signal);
828
+ const remoteIds = /* @__PURE__ */ new Set();
829
+ for (const row of junctions) {
830
+ const id = row.document[remoteField];
831
+ if (typeof id == "string") remoteIds.add(id);
832
+ }
833
+ for (const row of await this.byIds(target.collection, remoteIds, signal)) related.set(row.id, targetMapper.hydrate(row.id, row.document));
834
+ const groups = /* @__PURE__ */ new Map();
835
+ for (const row of junctions) {
836
+ const local = row.document[localField];
837
+ const remote = row.document[remoteField];
838
+ const entity = typeof remote == "string" ? related.get(remote) : void 0;
839
+ if (typeof local == "string" && entity) groups.set(local, [...groups.get(local) ?? [], entity]);
840
+ }
841
+ for (const entity of entities) {
842
+ const id = this.value(entity, metadata.primaryKey);
843
+ this.define(entity, relation.property, typeof id == "string" ? groups.get(id) ?? [] : []);
844
+ }
845
+ return [...related.values()];
846
+ }
847
+ byIds(collection, ids, signal) {
848
+ return this.queryBatches(collection, "$id", ids, signal);
849
+ }
850
+ async queryBatches(collection, field, values, signal) {
851
+ const all = [...values];
852
+ const rows = [];
853
+ for (let offset = 0; offset < all.length; offset += BATCH_SIZE) {
854
+ signal?.throwIfAborted();
855
+ const batch = all.slice(offset, offset + BATCH_SIZE);
856
+ if (!batch.length) continue;
857
+ const query = {
858
+ collection,
859
+ where: {
860
+ type: "in",
861
+ field,
862
+ values: batch
863
+ }
864
+ };
865
+ const source = this.runtime.transaction ? this.runtime.transaction.query(query, { signal }) : this.runtime.database.query(query, { signal });
866
+ for await (const row of source) rows.push(row);
867
+ }
868
+ return rows;
869
+ }
870
+ values(entities, property) {
871
+ const result = /* @__PURE__ */ new Set();
872
+ for (const entity of entities) {
873
+ const value = this.value(entity, property);
874
+ if (typeof value == "string") result.add(value);
875
+ }
876
+ return result;
877
+ }
878
+ value(entity, property) {
879
+ const descriptor = Object.getOwnPropertyDescriptor(entity, property);
880
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
881
+ }
882
+ define(entity, property, value) {
883
+ Object.defineProperty(entity, property, {
884
+ value,
885
+ enumerable: true,
886
+ configurable: true,
887
+ writable: true
888
+ });
889
+ }
890
+ };
891
+ // src/relations/relation-operations.ts
892
+ function associationId(ownerId, inverseId) {
893
+ return createHash("sha256").update(JSON.stringify([ownerId, inverseId])).digest("hex");
894
+ }
895
+ var RelationOperations = class {
896
+ metadata;
897
+ relation;
898
+ write;
899
+ constructor(metadata, relation, write) {
900
+ this.metadata = metadata;
901
+ this.relation = relation;
902
+ this.write = write;
903
+ if (relation.kind != "many-to-many" || !relation.joinTable) throw new Error(`Relation ${metadata.collection}.${relation.property} is not ManyToMany`);
904
+ }
905
+ async add(sourceId, targetId) {
906
+ await this.write(async (tx) => {
907
+ if (!await tx.getDocument(this.metadata.collection, sourceId)) throw new RecordNotFoundError(`Record not found: ${this.metadata.collection}/${sourceId}`);
908
+ if (!await tx.getDocument(this.relation.targetCollection, targetId)) throw new RecordNotFoundError(`Record not found: ${this.relation.targetCollection}/${targetId}`);
909
+ const join = this.relation.joinTable;
910
+ const ownerId = this.relation.owner ? sourceId : targetId;
911
+ const inverseId = this.relation.owner ? targetId : sourceId;
912
+ const id = associationId(ownerId, inverseId);
913
+ if (await tx.getDocument(join.name, id)) throw new DuplicateRecordError(`Relation already exists: ${join.name}/${id}`);
914
+ tx.putDocument(join.name, id, {
915
+ [join.ownerField]: ownerId,
916
+ [join.inverseField]: inverseId
917
+ });
918
+ });
919
+ }
920
+ async remove(sourceId, targetId) {
921
+ let removed = false;
922
+ await this.write(async (tx) => {
923
+ const id = associationId(this.relation.owner ? sourceId : targetId, this.relation.owner ? targetId : sourceId);
924
+ if (!await tx.getDocument(this.relation.joinTable.name, id)) return;
925
+ tx.deleteDocument(this.relation.joinTable.name, id);
926
+ removed = true;
927
+ });
928
+ return removed;
929
+ }
930
+ };
617
931
  // src/repository/repository.ts
618
932
  var Repository = class {
619
933
  metadata;
@@ -685,11 +999,14 @@ var Repository = class {
685
999
  });
686
1000
  return deleted;
687
1001
  }
688
- async findById(id) {
1002
+ async findById(id, options = {}) {
689
1003
  this.runtime.assertUsable();
690
1004
  if (this.runtime.transaction) {
691
1005
  const document = await this.runtime.transaction.getDocument(this.metadata.collection, id);
692
- return document ? this.#entityMapper.hydrate(id, document) : null;
1006
+ if (!document) return null;
1007
+ const entity = this.#entityMapper.hydrate(id, document);
1008
+ await this.loadRelations([entity], options.relations, options.signal);
1009
+ return entity;
693
1010
  }
694
1011
  const row = (await this.runtime.database.queryPage({
695
1012
  collection: this.metadata.collection,
@@ -700,23 +1017,33 @@ var Repository = class {
700
1017
  value: id
701
1018
  },
702
1019
  limit: 1
703
- })).rows[0];
704
- return row ? this.#entityMapper.hydrate(row.id, row.document) : null;
1020
+ }, { signal: options.signal })).rows[0];
1021
+ if (!row) return null;
1022
+ const entity = this.#entityMapper.hydrate(row.id, row.document);
1023
+ await this.loadRelations([entity], options.relations, options.signal);
1024
+ return entity;
705
1025
  }
706
1026
  async findOne(options = {}) {
707
1027
  const rows = await this.queryRows({
708
- ...this.#queryMapper.map(options),
1028
+ ...this.mapFind(options),
709
1029
  limit: 1
710
1030
  }, options.signal);
711
- return rows[0] ? this.hydrate(rows[0]) : null;
1031
+ if (!rows[0]) return null;
1032
+ const entity = this.hydrate(rows[0]);
1033
+ await this.loadRelations([entity], options.relations, options.signal);
1034
+ return entity;
712
1035
  }
713
1036
  async find(options = {}) {
714
- return (await this.queryRows(this.#queryMapper.map(options), options.signal)).map((row) => this.hydrate(row));
1037
+ const entities = (await this.queryRows(this.mapFind(options), options.signal)).map((row) => this.hydrate(row));
1038
+ await this.loadRelations(entities, options.relations, options.signal);
1039
+ return entities;
715
1040
  }
716
1041
  async findPage(options) {
717
- const page = await this.queryPage(this.#queryMapper.map(options), options.signal);
1042
+ const page = await this.queryPage(this.mapFind(options), options.signal);
1043
+ const items = page.rows.map((row) => this.hydrate(row));
1044
+ await this.loadRelations(items, options.relations, options.signal);
718
1045
  return {
719
- items: page.rows.map((row) => this.hydrate(row)),
1046
+ items,
720
1047
  nextCursor: page.nextCursor
721
1048
  };
722
1049
  }
@@ -743,9 +1070,32 @@ var Repository = class {
743
1070
  explain: (query) => this.runtime.database.explain(query)
744
1071
  }, this.metadata.collection);
745
1072
  }
1073
+ relations(property) {
1074
+ this.runtime.assertUsable();
1075
+ const relation = this.metadata.relationForProperty(property);
1076
+ if (!relation) throw new Error(`Unknown relation: ${this.metadata.collection}.${property}`);
1077
+ return new RelationOperations(this.metadata, relation, (action) => this.write(action));
1078
+ }
746
1079
  hydrate(row) {
747
1080
  return this.#entityMapper.hydrate(row.id, row.document);
748
1081
  }
1082
+ loadRelations(entities, relations, signal) {
1083
+ return new RelationLoader(this.metadata, this.runtime).load(entities, relations, signal);
1084
+ }
1085
+ mapFind(options) {
1086
+ const query = this.#queryMapper.map(options);
1087
+ if (!query.projection || !options.relations) return query;
1088
+ const projection = new Set(query.projection);
1089
+ for (const [property, enabled] of Object.entries(options.relations)) {
1090
+ if (!enabled) continue;
1091
+ const relation = this.metadata.relationForProperty(property);
1092
+ if (relation?.owner && relation.foreignKeyField) projection.add(relation.foreignKeyField);
1093
+ }
1094
+ return {
1095
+ ...query,
1096
+ projection: [...projection]
1097
+ };
1098
+ }
749
1099
  async queryRows(query, signal) {
750
1100
  this.runtime.assertUsable();
751
1101
  const rows = [];
@@ -772,6 +1122,14 @@ var Repository = class {
772
1122
  };
773
1123
  // src/schema/schema-mapper.ts
774
1124
  function mapEntitySchema(metadata) {
1125
+ const relationIndexes = metadata.relations.filter((relation) => relation.kind == "one-to-one" && relation.owner).map((relation) => ({
1126
+ name: `unique_${relation.property}`,
1127
+ unique: true,
1128
+ fields: [{
1129
+ field: relation.foreignKeyField,
1130
+ order: "ASC"
1131
+ }]
1132
+ }));
775
1133
  return {
776
1134
  name: metadata.collection,
777
1135
  fields: Object.fromEntries(metadata.columns.map((column) => [column.field, {
@@ -780,16 +1138,91 @@ function mapEntitySchema(metadata) {
780
1138
  nullable: column.nullable
781
1139
  }])),
782
1140
  allowAdditionalFields: false,
783
- indexes: metadata.indexes.map((index) => ({
1141
+ indexes: [...metadata.indexes.map((index) => ({
784
1142
  name: index.name,
785
1143
  unique: index.unique,
786
1144
  fields: index.fields.map((field) => ({
787
1145
  field: field.field,
788
1146
  order: field.order
789
1147
  }))
1148
+ })), ...relationIndexes],
1149
+ foreignKeys: metadata.relations.filter((relation) => relation.owner && relation.foreignKeyField).map((relation) => ({
1150
+ name: relation.property,
1151
+ field: relation.foreignKeyField,
1152
+ references: {
1153
+ collection: relation.targetCollection,
1154
+ field: "$id"
1155
+ },
1156
+ onDelete: relation.onDelete
790
1157
  }))
791
1158
  };
792
1159
  }
1160
+ function mapJunctionSchemas(metadata) {
1161
+ const schemas = /* @__PURE__ */ new Map();
1162
+ for (const entity of metadata) for (const relation of entity.relations) {
1163
+ if (relation.kind != "many-to-many" || !relation.owner || !relation.joinTable) continue;
1164
+ const join = relation.joinTable;
1165
+ if (join.ownerField == join.inverseField) throw new Error(`Join table ${join.name} uses the same field for both sides`);
1166
+ if (schemas.has(join.name)) throw new Error(`Duplicate join table: ${join.name}`);
1167
+ schemas.set(join.name, {
1168
+ name: join.name,
1169
+ fields: {
1170
+ [join.ownerField]: {
1171
+ type: "string",
1172
+ required: true,
1173
+ nullable: false
1174
+ },
1175
+ [join.inverseField]: {
1176
+ type: "string",
1177
+ required: true,
1178
+ nullable: false
1179
+ }
1180
+ },
1181
+ allowAdditionalFields: false,
1182
+ indexes: [
1183
+ {
1184
+ name: "owner",
1185
+ unique: false,
1186
+ field: join.ownerField
1187
+ },
1188
+ {
1189
+ name: "inverse",
1190
+ unique: false,
1191
+ field: join.inverseField
1192
+ },
1193
+ {
1194
+ name: "pair",
1195
+ unique: true,
1196
+ fields: [{
1197
+ field: join.ownerField,
1198
+ order: "ASC"
1199
+ }, {
1200
+ field: join.inverseField,
1201
+ order: "ASC"
1202
+ }]
1203
+ }
1204
+ ],
1205
+ foreignKeys: [{
1206
+ name: "owner",
1207
+ field: join.ownerField,
1208
+ references: {
1209
+ collection: entity.collection,
1210
+ field: "$id"
1211
+ },
1212
+ onDelete: "CASCADE"
1213
+ }, {
1214
+ name: "inverse",
1215
+ field: join.inverseField,
1216
+ references: {
1217
+ collection: relation.targetCollection,
1218
+ field: "$id"
1219
+ },
1220
+ onDelete: "CASCADE"
1221
+ }]
1222
+ });
1223
+ }
1224
+ return [...schemas.values()];
1225
+ }
793
1226
  // src/schema/schema-manager.ts
794
1227
  function same(left, right) {
795
1228
  return JSON.stringify(left) == JSON.stringify(right);
@@ -808,16 +1241,18 @@ var SchemaManager = class {
808
1241
  }
809
1242
  async initialize() {
810
1243
  const persisted = new Map((await this.database.getCollectionDefinitions()).map((definition) => [definition.name, normalizeCollection(definition)]));
811
- for (const metadata of this.registry.all()) {
812
- const expected = normalizeCollection(mapEntitySchema(metadata));
1244
+ const expectedSchemas = [...this.registry.all().map((metadata) => mapEntitySchema(metadata)), ...mapJunctionSchemas(this.registry.all())].map((schema) => normalizeCollection(schema));
1245
+ const missing = expectedSchemas.filter((schema) => !persisted.has(schema.name));
1246
+ if (missing.length && this.mode == "validate") throw new SchemaViolationError(`Missing collection: ${missing[0].name}`);
1247
+ if (missing.length) {
1248
+ await this.mutate(() => this.database.defineCollections(missing), `Could not create collections: ${missing.map((schema) => schema.name).join(", ")}`);
1249
+ for (const schema of missing) persisted.set(schema.name, schema);
1250
+ }
1251
+ for (const expected of expectedSchemas) {
813
1252
  const current = persisted.get(expected.name);
814
- if (!current) {
815
- if (this.mode == "validate") throw new SchemaViolationError(`Missing collection: ${expected.name}`);
816
- await this.mutate(() => this.database.defineCollection(expected), `Could not create collection: ${expected.name}`);
817
- persisted.set(expected.name, expected);
818
- continue;
819
- }
1253
+ if (!current) throw new SchemaViolationError(`Missing collection: ${expected.name}`);
820
1254
  this.validateFields(expected, current);
1255
+ if (!same(expected.foreignKeys ?? [], current.foreignKeys ?? [])) throw new SchemaViolationError(`Incompatible foreign keys: ${expected.name}`);
821
1256
  const actualIndexes = indexMap(current);
822
1257
  for (const expectedIndex of expected.indexes) {
823
1258
  const actual = actualIndexes.get(expectedIndex.name);
@@ -861,6 +1296,7 @@ var OrmTransactionManager = class {
861
1296
  const repository = new Repository(this.registry.get(entity), {
862
1297
  database: this.database,
863
1298
  transaction: this.transaction,
1299
+ registry: this.registry,
864
1300
  assertUsable: () => this.assertActive()
865
1301
  });
866
1302
  this.#repositories.set(entity, repository);
@@ -909,6 +1345,7 @@ var DuraxisORM = class {
909
1345
  if (cached) return cached;
910
1346
  const repository = new Repository(this.#registry.get(entity), {
911
1347
  database: this.options.database,
1348
+ registry: this.#registry,
912
1349
  assertUsable: () => this.assertReady()
913
1350
  });
914
1351
  this.#repositories.set(entity, repository);
@@ -946,6 +1383,6 @@ var DuraxisORM = class {
946
1383
  if (this.#lifecycle != "initialized") throw new OrmNotInitializedError();
947
1384
  }
948
1385
  };
949
- export { Column, CommitOutcomeUnknownError, DuplicateRecordError, DuraxisORM, DuraxisOrmError, Entity, EntityHydrator, EntityMapper, EntityMetadata, EntityNotRegisteredError, Index, InvalidColumnError, InvalidMetadataError, InvalidQueryError, MetadataRegistry, MissingPrimaryKeyError, OrmClosedError, OrmNotInitializedError, OrmTransactionManager, PrimaryKey, QueryBuilder, RecordNotFoundError, Repository, SchemaManager, SchemaViolationError, TransactionConflictError, TransactionManagerClosedError, UniqueIndexViolationOrmError, ValueTransformer };
1386
+ export { Column, CommitOutcomeUnknownError, DuplicateRecordError, DuraxisORM, DuraxisOrmError, Entity, EntityHydrator, EntityMapper, EntityMetadata, EntityNotRegisteredError, Index, InvalidColumnError, InvalidMetadataError, InvalidQueryError, JoinTable, ManyToMany, ManyToOne, MetadataRegistry, MissingPrimaryKeyError, OneToMany, OneToOne, OrmClosedError, OrmNotInitializedError, OrmTransactionManager, PrimaryKey, QueryBuilder, RecordNotFoundError, RelationLoader, RelationOperations, Repository, SchemaManager, SchemaViolationError, TransactionConflictError, TransactionManagerClosedError, UniqueIndexViolationOrmError, ValueTransformer };
950
1387
 
951
1388
  //# sourceMappingURL=index.js.map