@duraxis/orm 0.1.0 → 0.3.0

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