@duraxis/core 0.1.0 → 0.2.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.d.ts CHANGED
@@ -5,6 +5,8 @@ export type { TransactionState } from "./transactions/transaction.js";
5
5
  export { TransactionConflictError } from "./errors/transaction-conflict.error.js";
6
6
  export { TransactionStateError } from "./errors/transaction-state.error.js";
7
7
  export { CommitOutcomeUnknownError } from "./errors/commit-outcome-unknown.error.js";
8
+ export { ForeignKeyViolationError, ReferencedRecordNotFoundError, ReferencedRecordRestrictedError, InvalidForeignKeyDefinitionError, } from "./errors/foreign-key.error.js";
9
+ export { ForeignKeyManager } from "./relations/foreign-key-manager.js";
8
10
  export { RecoveryManager } from "./recovery/recovery-manager.js";
9
11
  export type { CommitStatus } from "./recovery/recovery-manager.js";
10
12
  export { GarbageCollector } from "./gc/garbage-collector.js";
@@ -26,7 +28,7 @@ export type { SecondaryIndexScanOptions, SecondaryIndexEntry, SecondaryIndexLogi
26
28
  export { encodeScalar, encodeCompositeKey, encodeIdentifier, encodeSecondaryKey, prefixSuccessor, prefixBounds, compositePrefixBounds, indexRangeBounds, compareBytes, compareIndexScalars, } from "./indexes/index-key.js";
27
29
  export type { IndexKeyPart, EncodedIndexBounds } from "./indexes/index-key.js";
28
30
  export { validateCollection, normalizeCollection, validateDocument, indexFields, fieldDefinition, recordKey, parseRecordKey, indexId, encodeDocument, decodeDocument, indexedValue, } from "./catalog/collection-schema.js";
29
- export type { IndexScalar, FieldType, FieldDefinition, IndexOrder, IndexFieldDefinition, SecondaryIndexDefinition, CollectionDefinition, DocumentRecord, } from "./catalog/collection-schema.js";
31
+ export type { IndexScalar, FieldType, FieldDefinition, IndexOrder, IndexFieldDefinition, SecondaryIndexDefinition, CollectionDefinition, DocumentRecord, ReferentialAction, ForeignKeyDefinition, } from "./catalog/collection-schema.js";
30
32
  export type { CollectionRow } from "./database/duraxis-database.js";
31
33
  export { QueryContext } from "./query/context/query-context.js";
32
34
  export type { QueryContextOptions, QueryMetrics } from "./query/context/query-context.js";
package/dist/index.js CHANGED
@@ -69,6 +69,37 @@ var StorageKeyManager = class {
69
69
  if (!this.indexNodePattern.test(key)) throw new Error("Invalid or foreign Duraxis index node reference");
70
70
  }
71
71
  };
72
+ // src/errors/foreign-key.error.ts
73
+ var ForeignKeyViolationError = class extends Error {
74
+ collection;
75
+ constraint;
76
+ reference;
77
+ constructor(message, collection, constraint, reference) {
78
+ super(message);
79
+ this.collection = collection;
80
+ this.constraint = constraint;
81
+ this.reference = reference;
82
+ this.name = "ForeignKeyViolationError";
83
+ }
84
+ };
85
+ var ReferencedRecordNotFoundError = class extends ForeignKeyViolationError {
86
+ constructor(collection, constraint, reference) {
87
+ super(`Referenced record not found for ${collection}/${constraint}: ${reference}`, collection, constraint, reference);
88
+ this.name = "ReferencedRecordNotFoundError";
89
+ }
90
+ };
91
+ var ReferencedRecordRestrictedError = class extends ForeignKeyViolationError {
92
+ constructor(collection, constraint, reference) {
93
+ super(`Referenced record is still used by ${collection}/${constraint}: ${reference}`, collection, constraint, reference);
94
+ this.name = "ReferencedRecordRestrictedError";
95
+ }
96
+ };
97
+ var InvalidForeignKeyDefinitionError = class extends Error {
98
+ constructor(message) {
99
+ super(message);
100
+ this.name = "InvalidForeignKeyDefinitionError";
101
+ }
102
+ };
72
103
  // src/catalog/collection-schema.ts
73
104
  var NAME = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
74
105
  var RECORD_PREFIX = "@duraxis/records/";
@@ -92,18 +123,42 @@ function normalizeCollection(schema) {
92
123
  required: field.required ?? false,
93
124
  nullable: field.nullable ?? false
94
125
  }])) : void 0;
126
+ const foreignKeys = [...schema.foreignKeys ?? []].sort((left, right) => left.name.localeCompare(right.name)).map((foreignKey) => ({
127
+ name: foreignKey.name,
128
+ field: foreignKey.field,
129
+ references: {
130
+ collection: foreignKey.references.collection,
131
+ field: "$id"
132
+ },
133
+ onDelete: foreignKey.onDelete
134
+ }));
135
+ const indexes = schema.indexes.map((index) => ({
136
+ name: index.name,
137
+ unique: index.unique,
138
+ fields: indexFields(index).map((part) => ({
139
+ field: part.field,
140
+ order: part.order
141
+ }))
142
+ }));
143
+ for (const foreignKey of foreignKeys) {
144
+ if (indexes.some((index) => index.fields.length == 1 && index.fields[0].field == foreignKey.field)) continue;
145
+ const name = `fk_${foreignKey.name}`;
146
+ if (indexes.find((index) => index.name == name)) throw new Error(`Foreign-key index name collision: ${schema.name}/${name}`);
147
+ indexes.push({
148
+ name,
149
+ unique: false,
150
+ fields: [{
151
+ field: foreignKey.field,
152
+ order: "ASC"
153
+ }]
154
+ });
155
+ }
95
156
  return {
96
157
  name: schema.name,
97
158
  ...fields == null ? {} : { fields },
98
159
  allowAdditionalFields: schema.allowAdditionalFields ?? true,
99
- indexes: schema.indexes.map((index) => ({
100
- name: index.name,
101
- unique: index.unique,
102
- fields: indexFields(index).map((part) => ({
103
- field: part.field,
104
- order: part.order
105
- }))
106
- }))
160
+ indexes,
161
+ ...foreignKeys.length == 0 ? {} : { foreignKeys }
107
162
  };
108
163
  }
109
164
  function validateCollection(schema) {
@@ -141,6 +196,24 @@ function validateCollection(schema) {
141
196
  if (fields && !Object.hasOwn(fields, part.field)) throw new Error(`Unknown indexed field: ${part.field}`);
142
197
  }
143
198
  }
199
+ if (schema.foreignKeys != null && !Array.isArray(schema.foreignKeys)) throw new InvalidForeignKeyDefinitionError("Foreign keys must be an array");
200
+ const foreignKeyNames = /* @__PURE__ */ new Set();
201
+ const foreignKeyFields = /* @__PURE__ */ new Set();
202
+ for (const foreignKey of schema.foreignKeys ?? []) {
203
+ if (!foreignKey || !isValidSchemaName(foreignKey.name) || foreignKey.name.length > 61 || !isValidSchemaName(foreignKey.field) || !foreignKey.references || !isValidSchemaName(foreignKey.references.collection) || foreignKey.references.field != "$id" || ![
204
+ "RESTRICT",
205
+ "CASCADE",
206
+ "SET_NULL"
207
+ ].includes(foreignKey.onDelete)) throw new InvalidForeignKeyDefinitionError(`Invalid foreign key definition: ${foreignKey?.name ?? "unknown"}`);
208
+ if (foreignKeyNames.has(foreignKey.name)) throw new InvalidForeignKeyDefinitionError(`Duplicate foreign key: ${foreignKey.name}`);
209
+ if (foreignKeyFields.has(foreignKey.field)) throw new InvalidForeignKeyDefinitionError(`Duplicate foreign key field: ${foreignKey.field}`);
210
+ foreignKeyNames.add(foreignKey.name);
211
+ foreignKeyFields.add(foreignKey.field);
212
+ const definition = fields?.[foreignKey.field];
213
+ if (!definition) throw new InvalidForeignKeyDefinitionError(`Unknown foreign key field: ${foreignKey.field}`);
214
+ if (definition.type != "string") throw new InvalidForeignKeyDefinitionError(`Foreign key ${foreignKey.name} must use a string field`);
215
+ if (foreignKey.onDelete == "SET_NULL" && !definition.nullable) throw new InvalidForeignKeyDefinitionError(`SET_NULL foreign key ${foreignKey.name} must be nullable`);
216
+ }
144
217
  }
145
218
  function normalizeFieldValue(name, definition, value) {
146
219
  if (value === null) {
@@ -1407,17 +1480,146 @@ var SecondaryIndexManager = class {
1407
1480
  return ids;
1408
1481
  }
1409
1482
  };
1483
+ // src/relations/foreign-key-manager.ts
1484
+ var MAX_CASCADE_OPERATIONS = 1e5;
1485
+ var ForeignKeyManager = class {
1486
+ #primary;
1487
+ #secondary;
1488
+ constructor(storage, keys = new StorageKeyManager()) {
1489
+ this.#primary = new PrimaryIndex(storage, keys);
1490
+ this.#secondary = new SecondaryIndexManager(storage, keys);
1491
+ }
1492
+ async prepare(snapshot, sourceWrites, sourceCatalog) {
1493
+ const catalog = this.validateCatalog(sourceCatalog);
1494
+ const writes = new Map(sourceWrites);
1495
+ const incoming = this.incoming(catalog);
1496
+ const queue = [];
1497
+ const visited = /* @__PURE__ */ new Set();
1498
+ for (const [key, operation] of writes) {
1499
+ const parsed = parseRecordKey(key);
1500
+ if (parsed && operation.type == "delete") queue.push(parsed);
1501
+ }
1502
+ for (let offset = 0; offset < queue.length; offset++) {
1503
+ if (visited.size > MAX_CASCADE_OPERATIONS) throw new Error("Foreign-key cascade operation limit exceeded");
1504
+ const parent = queue[offset];
1505
+ const parentKey = recordKey(parent.collection, parent.id);
1506
+ if (visited.has(parentKey)) continue;
1507
+ visited.add(parentKey);
1508
+ for (const relation of incoming.get(parent.collection) ?? []) {
1509
+ const childIds = await this.childIds(snapshot, writes, relation, parent.id);
1510
+ for (const childId of childIds) {
1511
+ const childKey = recordKey(relation.collection, childId);
1512
+ const document = await this.finalDocument(snapshot, writes, relation.collection, childId);
1513
+ if (!document || document[relation.foreignKey.field] !== parent.id) continue;
1514
+ switch (relation.foreignKey.onDelete) {
1515
+ case "RESTRICT": throw new ReferencedRecordRestrictedError(relation.collection, relation.foreignKey.name, `${parent.collection}/${parent.id}`);
1516
+ case "CASCADE":
1517
+ writes.set(childKey, { type: "delete" });
1518
+ queue.push({
1519
+ collection: relation.collection,
1520
+ id: childId
1521
+ });
1522
+ break;
1523
+ case "SET_NULL": {
1524
+ const next = {
1525
+ ...document,
1526
+ [relation.foreignKey.field]: null
1527
+ };
1528
+ writes.set(childKey, {
1529
+ type: "put",
1530
+ data: encodeDocument(validateDocument(relation.schema, next))
1531
+ });
1532
+ break;
1533
+ }
1534
+ }
1535
+ }
1536
+ }
1537
+ }
1538
+ for (const [key, operation] of writes) {
1539
+ const parsed = parseRecordKey(key);
1540
+ if (!parsed || operation.type != "put") continue;
1541
+ const schema = catalog.get(parsed.collection);
1542
+ if (!schema) throw new InvalidForeignKeyDefinitionError(`Unknown collection: ${parsed.collection}`);
1543
+ const document = decodeDocument(operation.data);
1544
+ for (const foreignKey of schema.foreignKeys ?? []) {
1545
+ const definition = fieldDefinition(schema, foreignKey.field);
1546
+ const value = document[foreignKey.field];
1547
+ if (value == null) {
1548
+ if (value === null && definition.nullable) continue;
1549
+ if (value === void 0 && !definition.required) continue;
1550
+ throw new ReferencedRecordNotFoundError(parsed.collection, foreignKey.name, String(value));
1551
+ }
1552
+ if (typeof value != "string" || !await this.finalRecordExists(snapshot, writes, foreignKey.references.collection, value)) throw new ReferencedRecordNotFoundError(parsed.collection, foreignKey.name, `${foreignKey.references.collection}/${String(value)}`);
1553
+ }
1554
+ }
1555
+ return writes;
1556
+ }
1557
+ validateCatalog(source) {
1558
+ const catalog = /* @__PURE__ */ new Map();
1559
+ try {
1560
+ for (const [name, definition] of source) catalog.set(name, normalizeCollection(definition));
1561
+ } catch (cause) {
1562
+ throw new InvalidForeignKeyDefinitionError(cause instanceof Error ? cause.message : "Invalid foreign key definition");
1563
+ }
1564
+ for (const [collection, schema] of catalog) for (const foreignKey of schema.foreignKeys ?? []) if (!catalog.has(foreignKey.references.collection)) throw new InvalidForeignKeyDefinitionError(`Foreign key ${collection}/${foreignKey.name} references unknown collection ${foreignKey.references.collection}`);
1565
+ return catalog;
1566
+ }
1567
+ incoming(catalog) {
1568
+ const result = /* @__PURE__ */ new Map();
1569
+ for (const [collection, schema] of catalog) for (const foreignKey of schema.foreignKeys ?? []) {
1570
+ const index = schema.indexes.find((candidate) => {
1571
+ const parts = indexFields(candidate);
1572
+ return parts.length == 1 && parts[0].field == foreignKey.field;
1573
+ });
1574
+ if (!index) throw new InvalidForeignKeyDefinitionError(`Foreign key ${collection}/${foreignKey.name} has no supporting index`);
1575
+ const values = result.get(foreignKey.references.collection) ?? [];
1576
+ values.push({
1577
+ collection,
1578
+ schema,
1579
+ foreignKey,
1580
+ index: index.name
1581
+ });
1582
+ result.set(foreignKey.references.collection, values);
1583
+ }
1584
+ for (const values of result.values()) values.sort((left, right) => `${left.collection}/${left.foreignKey.name}`.localeCompare(`${right.collection}/${right.foreignKey.name}`));
1585
+ return result;
1586
+ }
1587
+ async childIds(snapshot, writes, relation, parentId) {
1588
+ const result = /* @__PURE__ */ new Set();
1589
+ if (snapshot.manifest.catalog.get(relation.collection)?.indexes.some((index) => index.name == relation.index)) for await (const entry of this.#secondary.scanIds(snapshot.manifest, relation.collection, relation.index, { eq: parentId })) result.add(entry.id);
1590
+ for (const [key, operation] of writes) {
1591
+ const parsed = parseRecordKey(key);
1592
+ if (!parsed || parsed.collection != relation.collection) continue;
1593
+ if (operation.type == "delete") result.delete(parsed.id);
1594
+ else if (decodeDocument(operation.data)[relation.foreignKey.field] === parentId) result.add(parsed.id);
1595
+ else result.delete(parsed.id);
1596
+ }
1597
+ return result;
1598
+ }
1599
+ async finalRecordExists(snapshot, writes, collection, id) {
1600
+ return await this.finalDocument(snapshot, writes, collection, id) != null;
1601
+ }
1602
+ async finalDocument(snapshot, writes, collection, id) {
1603
+ const key = recordKey(collection, id);
1604
+ const pending = writes.get(key);
1605
+ if (pending) return pending.type == "delete" ? null : decodeDocument(pending.data);
1606
+ const stored = await this.#primary.read(snapshot.manifest, key);
1607
+ return stored == null ? null : decodeDocument(stored);
1608
+ }
1609
+ };
1410
1610
  // src/commit/commit-coordinator.ts
1411
1611
  var CommitCoordinator = class {
1412
1612
  storage;
1413
1613
  keys;
1414
1614
  primary;
1415
1615
  secondary;
1616
+ foreignKeys;
1416
1617
  constructor(storage, keys = new StorageKeyManager()) {
1417
1618
  this.storage = storage;
1418
1619
  this.keys = keys;
1419
1620
  this.primary = new PrimaryIndex(storage, keys);
1420
1621
  this.secondary = new SecondaryIndexManager(storage, keys);
1622
+ this.foreignKeys = new ForeignKeyManager(storage, keys);
1421
1623
  }
1422
1624
  async commit(transaction) {
1423
1625
  const prepared = transaction.prepareForCommit();
@@ -1428,8 +1630,9 @@ var CommitCoordinator = class {
1428
1630
  const transactionId = randomUUID();
1429
1631
  const catalog = new Map(prepared.snapshot.manifest.catalog);
1430
1632
  for (const [name, schema] of prepared.schemaChanges) catalog.set(name, schema);
1633
+ const writes = await this.foreignKeys.prepare(prepared.snapshot, prepared.writes, catalog);
1431
1634
  const changes = /* @__PURE__ */ new Map();
1432
- for (const [key, operation] of prepared.writes) {
1635
+ for (const [key, operation] of writes) {
1433
1636
  if (operation.type == "delete") {
1434
1637
  changes.set(key, null);
1435
1638
  continue;
@@ -1439,7 +1642,7 @@ var CommitCoordinator = class {
1439
1642
  changes.set(key, ref);
1440
1643
  }
1441
1644
  const primaryRoot = await this.primary.prepare(prepared.snapshot.manifest.primaryRoot, changes);
1442
- const indexRoots = await this.secondary.prepare(prepared.snapshot.manifest, primaryRoot, prepared.writes, catalog);
1645
+ const indexRoots = await this.secondary.prepare(prepared.snapshot.manifest, primaryRoot, writes, catalog);
1443
1646
  const commitBytes = encodeCommitRecord({
1444
1647
  format: 1,
1445
1648
  transactionId,
@@ -2872,6 +3075,16 @@ var Transaction = class {
2872
3075
  if (this.collection(definition.name)) throw new Error(`Collection already exists: ${definition.name}`);
2873
3076
  this.schemas.set(definition.name, cloneSchema(definition));
2874
3077
  }
3078
+ defineCollections(definitions) {
3079
+ this.assertActive();
3080
+ const names = /* @__PURE__ */ new Set();
3081
+ for (const definition of definitions) {
3082
+ validateCollection(definition);
3083
+ if (names.has(definition.name) || this.collection(definition.name)) throw new Error(`Collection already exists: ${definition.name}`);
3084
+ names.add(definition.name);
3085
+ }
3086
+ for (const definition of definitions) this.schemas.set(definition.name, cloneSchema(definition));
3087
+ }
2875
3088
  addIndex(collection, index) {
2876
3089
  this.assertActive();
2877
3090
  const current = this.requireCollection(collection);
@@ -3392,10 +3605,15 @@ function immutableCollection(definition) {
3392
3605
  ...index,
3393
3606
  fields: Object.freeze((index.fields ?? []).map((field) => Object.freeze({ ...field })))
3394
3607
  })));
3608
+ const foreignKeys = Object.freeze((normalized.foreignKeys ?? []).map((foreignKey) => Object.freeze({
3609
+ ...foreignKey,
3610
+ references: Object.freeze({ ...foreignKey.references })
3611
+ })));
3395
3612
  return Object.freeze({
3396
3613
  ...normalized,
3397
3614
  ...fields == null ? {} : { fields },
3398
- indexes
3615
+ indexes,
3616
+ ...foreignKeys.length == 0 ? {} : { foreignKeys }
3399
3617
  });
3400
3618
  }
3401
3619
  var DuraxisDatabase = class {
@@ -3470,6 +3688,9 @@ var DuraxisDatabase = class {
3470
3688
  tx.defineCollection(schema);
3471
3689
  });
3472
3690
  }
3691
+ async defineCollections(schemas) {
3692
+ await this.transaction((tx) => tx.defineCollections(schemas));
3693
+ }
3473
3694
  async getCollectionDefinitions() {
3474
3695
  const snapshot = await this.acquireSnapshot();
3475
3696
  try {
@@ -3763,6 +3984,6 @@ var ReferenceQueryExecutor = class {
3763
3984
  return this.executor.page(context, query, new CollectionScan(query.collection));
3764
3985
  }
3765
3986
  };
3766
- export { AccessPathEnumerator, BPlusTree, BPlusTreeNodeCache, BPlusTreeNodeStore, BPlusTreeValidator, CollectionScan, CommitOutcomeUnknownError, Difference, DuraxisDatabase, Filter, GarbageCollector, Intersection, Limit, ManifestReachabilityScanner, ManifestSnapshotReader, PlanCompiler, PredicateAnalyzer, PrimaryIndex, PrimaryLookup, Projection, QueryContext, QueryExecutor, QueryMemoryLimitError, RecoveryManager, ReferenceQueryExecutor, RuleBasedPlanner, SecondaryIndexManager, SecondaryIndexRangeScan, SecondaryIndexScan, Sort, Transaction, TransactionConflictError, TransactionStateError, Union, UniqueIndexLookup, UniqueIndexViolationError, compareBytes, compareIndexScalars, compareRows, compositePrefixBounds, decodeDocument, decodeQueryCursor, encodeCompositeKey, encodeDocument, encodeIdentifier, encodeQueryCursor, encodeScalar, encodeSecondaryKey, evaluatePredicate, explainPhysicalPlan, fieldDefinition, indexFields, indexId, indexRangeBounds, indexedValue, normalizeCollection, parseRecordKey, prefixBounds, prefixSuccessor, recordKey, secondaryIndexBounds, validateCollection, validateDocument, validateQuery };
3987
+ export { AccessPathEnumerator, BPlusTree, BPlusTreeNodeCache, BPlusTreeNodeStore, BPlusTreeValidator, CollectionScan, CommitOutcomeUnknownError, Difference, DuraxisDatabase, Filter, ForeignKeyManager, ForeignKeyViolationError, GarbageCollector, Intersection, InvalidForeignKeyDefinitionError, Limit, ManifestReachabilityScanner, ManifestSnapshotReader, PlanCompiler, PredicateAnalyzer, PrimaryIndex, PrimaryLookup, Projection, QueryContext, QueryExecutor, QueryMemoryLimitError, RecoveryManager, ReferenceQueryExecutor, ReferencedRecordNotFoundError, ReferencedRecordRestrictedError, RuleBasedPlanner, SecondaryIndexManager, SecondaryIndexRangeScan, SecondaryIndexScan, Sort, Transaction, TransactionConflictError, TransactionStateError, Union, UniqueIndexLookup, UniqueIndexViolationError, compareBytes, compareIndexScalars, compareRows, compositePrefixBounds, decodeDocument, decodeQueryCursor, encodeCompositeKey, encodeDocument, encodeIdentifier, encodeQueryCursor, encodeScalar, encodeSecondaryKey, evaluatePredicate, explainPhysicalPlan, fieldDefinition, indexFields, indexId, indexRangeBounds, indexedValue, normalizeCollection, parseRecordKey, prefixBounds, prefixSuccessor, recordKey, secondaryIndexBounds, validateCollection, validateDocument, validateQuery };
3767
3988
 
3768
3989
  //# sourceMappingURL=index.js.map