@duraxis/orm 0.0.0-stage → 0.1.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/CHANGELOG.md +4 -0
- package/LICENSE +15 -0
- package/README.md +57 -2
- package/dist/database/duraxis-orm.d.ts +16 -0
- package/dist/database/orm-options.d.ts +12 -0
- package/dist/decorators/column.decorator.d.ts +2 -0
- package/dist/decorators/entity.decorator.d.ts +1 -0
- package/dist/decorators/index.decorator.d.ts +13 -0
- package/dist/decorators/primary-key.decorator.d.ts +2 -0
- package/dist/errors/index.d.ts +32 -0
- package/dist/index.cjs +990 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +951 -0
- package/dist/index.js.map +1 -0
- package/dist/mapping/entity-hydrator.d.ts +11 -0
- package/dist/mapping/entity-mapper.d.ts +15 -0
- package/dist/mapping/value-transformer.d.ts +6 -0
- package/dist/metadata/decorator-metadata.d.ts +31 -0
- package/dist/metadata/entity-metadata.d.ts +45 -0
- package/dist/metadata/metadata-registry.d.ts +11 -0
- package/dist/metadata/metadata-validator.d.ts +2 -0
- package/dist/query/find-options.d.ts +15 -0
- package/dist/query/query-builder.d.ts +50 -0
- package/dist/query/query-mapper.d.ts +14 -0
- package/dist/query/where-operator.d.ts +26 -0
- package/dist/repository/repository-errors.d.ts +1 -0
- package/dist/repository/repository-options.d.ts +6 -0
- package/dist/repository/repository.d.ts +28 -0
- package/dist/schema/schema-manager.d.ts +12 -0
- package/dist/schema/schema-mapper.d.ts +3 -0
- package/dist/transactions/orm-transaction.d.ts +15 -0
- package/dist/transactions/transaction-context.d.ts +5 -0
- package/package.json +59 -3
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,990 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let _duraxis_core = require("@duraxis/core");
|
|
3
|
+
// src/metadata/decorator-metadata.ts
|
|
4
|
+
var drafts = /* @__PURE__ */ new WeakMap();
|
|
5
|
+
function ownDraft(entity) {
|
|
6
|
+
return drafts.get(entity);
|
|
7
|
+
}
|
|
8
|
+
function mutableDraft(entity) {
|
|
9
|
+
let draft = drafts.get(entity);
|
|
10
|
+
if (!draft) {
|
|
11
|
+
draft = {
|
|
12
|
+
entityApplications: 0,
|
|
13
|
+
columns: [],
|
|
14
|
+
primaryKeys: [],
|
|
15
|
+
indexes: []
|
|
16
|
+
};
|
|
17
|
+
drafts.set(entity, draft);
|
|
18
|
+
}
|
|
19
|
+
return draft;
|
|
20
|
+
}
|
|
21
|
+
function entityConstructor(target) {
|
|
22
|
+
const constructor = target.constructor;
|
|
23
|
+
if (typeof constructor != "function") throw new TypeError("Invalid decorator target");
|
|
24
|
+
return constructor;
|
|
25
|
+
}
|
|
26
|
+
function propertyName(value) {
|
|
27
|
+
if (typeof value != "string") throw new TypeError("Symbol entity properties are not supported");
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
// src/decorators/entity.decorator.ts
|
|
31
|
+
function Entity(name) {
|
|
32
|
+
return (target) => {
|
|
33
|
+
const draft = mutableDraft(target);
|
|
34
|
+
draft.entityApplications++;
|
|
35
|
+
draft.entityName = name ?? target.name;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
// src/decorators/column.decorator.ts
|
|
39
|
+
function Column(options) {
|
|
40
|
+
return (target, key) => {
|
|
41
|
+
mutableDraft(entityConstructor(target)).columns.push({
|
|
42
|
+
property: propertyName(key),
|
|
43
|
+
options: { ...options }
|
|
44
|
+
});
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
// src/decorators/primary-key.decorator.ts
|
|
48
|
+
/** Declares the logical record identifier. It is never stored inside the document. */
|
|
49
|
+
function PrimaryKey() {
|
|
50
|
+
return (target, key) => {
|
|
51
|
+
mutableDraft(entityConstructor(target)).primaryKeys.push(propertyName(key));
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
// src/decorators/index.decorator.ts
|
|
55
|
+
function Index(nameOrOptions = {}, fields, compositeOptions = {}) {
|
|
56
|
+
if (typeof nameOrOptions == "string") return (target) => {
|
|
57
|
+
mutableDraft(target).indexes.push({
|
|
58
|
+
kind: "composite",
|
|
59
|
+
name: nameOrOptions,
|
|
60
|
+
unique: compositeOptions.unique ?? false,
|
|
61
|
+
fields: (fields ?? []).map((field) => ({
|
|
62
|
+
property: field.property,
|
|
63
|
+
order: field.order ?? "ASC"
|
|
64
|
+
}))
|
|
65
|
+
});
|
|
66
|
+
};
|
|
67
|
+
return (target, key) => {
|
|
68
|
+
mutableDraft(entityConstructor(target)).indexes.push({
|
|
69
|
+
kind: "property",
|
|
70
|
+
property: propertyName(key),
|
|
71
|
+
...nameOrOptions.name == null ? {} : { name: nameOrOptions.name },
|
|
72
|
+
unique: nameOrOptions.unique ?? false
|
|
73
|
+
});
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
// src/errors/index.ts
|
|
77
|
+
var DuraxisOrmError = class extends Error {
|
|
78
|
+
constructor(message, options) {
|
|
79
|
+
super(message, options);
|
|
80
|
+
this.name = new.target.name;
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
var EntityNotRegisteredError = class extends DuraxisOrmError {
|
|
84
|
+
constructor(entity) {
|
|
85
|
+
super(`Entity is not registered: ${entity.name || "<anonymous>"}`);
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
var InvalidMetadataError = class extends DuraxisOrmError {};
|
|
89
|
+
var MissingPrimaryKeyError = class extends InvalidMetadataError {};
|
|
90
|
+
var DuplicateRecordError = class extends DuraxisOrmError {};
|
|
91
|
+
var RecordNotFoundError = class extends DuraxisOrmError {};
|
|
92
|
+
var InvalidColumnError = class extends DuraxisOrmError {};
|
|
93
|
+
var SchemaViolationError = class extends DuraxisOrmError {};
|
|
94
|
+
var InvalidQueryError = class extends DuraxisOrmError {};
|
|
95
|
+
var UniqueIndexViolationOrmError = class extends DuraxisOrmError {
|
|
96
|
+
constructor(message, cause) {
|
|
97
|
+
super(message, { cause });
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
var OrmNotInitializedError = class extends DuraxisOrmError {
|
|
101
|
+
constructor() {
|
|
102
|
+
super("DuraxisORM is not initialized");
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
var OrmClosedError = class extends DuraxisOrmError {
|
|
106
|
+
constructor() {
|
|
107
|
+
super("DuraxisORM is closed");
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
var TransactionManagerClosedError = class extends DuraxisOrmError {
|
|
111
|
+
constructor() {
|
|
112
|
+
super("ORM transaction manager is no longer active");
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
// src/metadata/entity-metadata.ts
|
|
116
|
+
var EntityMetadata = class {
|
|
117
|
+
#byProperty;
|
|
118
|
+
#byField;
|
|
119
|
+
entity;
|
|
120
|
+
collection;
|
|
121
|
+
primaryKey;
|
|
122
|
+
columns;
|
|
123
|
+
indexes;
|
|
124
|
+
constructor(options) {
|
|
125
|
+
this.entity = options.entity;
|
|
126
|
+
this.collection = options.collection;
|
|
127
|
+
this.primaryKey = options.primaryKey;
|
|
128
|
+
this.columns = Object.freeze(options.columns.map((column) => Object.freeze({ ...column })));
|
|
129
|
+
this.indexes = Object.freeze(options.indexes.map((index) => Object.freeze({
|
|
130
|
+
...index,
|
|
131
|
+
fields: Object.freeze(index.fields.map((field) => Object.freeze({ ...field })))
|
|
132
|
+
})));
|
|
133
|
+
this.#byProperty = new Map(this.columns.map((column) => [column.property, column]));
|
|
134
|
+
this.#byField = new Map(this.columns.map((column) => [column.field, column]));
|
|
135
|
+
Object.freeze(this);
|
|
136
|
+
}
|
|
137
|
+
columnForProperty(property) {
|
|
138
|
+
return this.#byProperty.get(property);
|
|
139
|
+
}
|
|
140
|
+
columnForField(field) {
|
|
141
|
+
return this.#byField.get(field);
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
// src/metadata/metadata-validator.ts
|
|
145
|
+
var NAME = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
|
|
146
|
+
var TYPES = /* @__PURE__ */ new Set([
|
|
147
|
+
"string",
|
|
148
|
+
"number",
|
|
149
|
+
"boolean",
|
|
150
|
+
"date"
|
|
151
|
+
]);
|
|
152
|
+
function requireName(name, label) {
|
|
153
|
+
if (typeof name != "string" || !NAME.test(name)) throw new InvalidMetadataError(`Invalid ${label}: ${String(name)}`);
|
|
154
|
+
}
|
|
155
|
+
function hierarchy(entity) {
|
|
156
|
+
const result = [];
|
|
157
|
+
let current = entity;
|
|
158
|
+
while (typeof current == "function" && current != Function.prototype) {
|
|
159
|
+
const draft = ownDraft(current);
|
|
160
|
+
if (draft) result.unshift(draft);
|
|
161
|
+
current = Object.getPrototypeOf(current);
|
|
162
|
+
}
|
|
163
|
+
return result;
|
|
164
|
+
}
|
|
165
|
+
function buildEntityMetadata(entity) {
|
|
166
|
+
const own = ownDraft(entity);
|
|
167
|
+
if (!own?.entityName) throw new InvalidMetadataError(`Class ${entity.name} is missing @Entity()`);
|
|
168
|
+
if (own.entityApplications != 1) throw new InvalidMetadataError(`Class ${entity.name} has duplicate @Entity() decorators`);
|
|
169
|
+
requireName(own.entityName, "entity name");
|
|
170
|
+
const drafts = hierarchy(entity);
|
|
171
|
+
const columns = [];
|
|
172
|
+
const byProperty = /* @__PURE__ */ new Map();
|
|
173
|
+
const byField = /* @__PURE__ */ new Map();
|
|
174
|
+
const primaryKeys = [];
|
|
175
|
+
for (const draft of drafts) {
|
|
176
|
+
for (const key of draft.primaryKeys) {
|
|
177
|
+
requireName(key, "primary-key property");
|
|
178
|
+
primaryKeys.push(key);
|
|
179
|
+
}
|
|
180
|
+
for (const column of draft.columns) {
|
|
181
|
+
requireName(column.property, "column property");
|
|
182
|
+
const field = column.options.name ?? column.property;
|
|
183
|
+
requireName(field, "persisted column name");
|
|
184
|
+
if (!TYPES.has(column.options.type)) throw new InvalidMetadataError(`Invalid column type for ${column.property}`);
|
|
185
|
+
if (byProperty.has(column.property)) throw new InvalidMetadataError(`Duplicate column property: ${column.property}`);
|
|
186
|
+
if (byField.has(field)) throw new InvalidMetadataError(`Duplicate persisted column name: ${field}`);
|
|
187
|
+
const metadata = {
|
|
188
|
+
property: column.property,
|
|
189
|
+
field,
|
|
190
|
+
type: column.options.type,
|
|
191
|
+
required: column.options.required ?? false,
|
|
192
|
+
nullable: column.options.nullable ?? false
|
|
193
|
+
};
|
|
194
|
+
columns.push(metadata);
|
|
195
|
+
byProperty.set(column.property, metadata);
|
|
196
|
+
byField.set(field, metadata);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (primaryKeys.length == 0) throw new MissingPrimaryKeyError(`Entity ${entity.name} must declare exactly one primary key`);
|
|
200
|
+
if (primaryKeys.length != 1) throw new InvalidMetadataError(`Entity ${entity.name} declares multiple primary keys`);
|
|
201
|
+
const primaryKey = primaryKeys[0];
|
|
202
|
+
if (byProperty.has(primaryKey)) throw new InvalidMetadataError(`Primary key ${primaryKey} must not also be declared as a persisted column`);
|
|
203
|
+
const indexes = [];
|
|
204
|
+
const indexNames = /* @__PURE__ */ new Set();
|
|
205
|
+
for (const draft of drafts) for (const index of draft.indexes) {
|
|
206
|
+
const name = index.kind == "property" ? index.name ?? index.property : index.name;
|
|
207
|
+
requireName(name, "index name");
|
|
208
|
+
if (indexNames.has(name)) throw new InvalidMetadataError(`Duplicate index name: ${name}`);
|
|
209
|
+
indexNames.add(name);
|
|
210
|
+
const fields = index.kind == "property" ? [{
|
|
211
|
+
property: index.property,
|
|
212
|
+
order: "ASC"
|
|
213
|
+
}] : index.fields;
|
|
214
|
+
if (fields.length == 0) throw new InvalidMetadataError(`Index ${name} has no fields`);
|
|
215
|
+
const seen = /* @__PURE__ */ new Set();
|
|
216
|
+
const mapped = fields.map((part) => {
|
|
217
|
+
requireName(part.property, `property in index ${name}`);
|
|
218
|
+
const column = byProperty.get(part.property);
|
|
219
|
+
if (!column) throw new InvalidMetadataError(`Index ${name} references unknown column property: ${part.property}`);
|
|
220
|
+
if (seen.has(part.property)) throw new InvalidMetadataError(`Index ${name} repeats property: ${part.property}`);
|
|
221
|
+
seen.add(part.property);
|
|
222
|
+
if (part.order != "ASC" && part.order != "DESC") throw new InvalidMetadataError(`Invalid order in index ${name}`);
|
|
223
|
+
return {
|
|
224
|
+
property: column.property,
|
|
225
|
+
field: column.field,
|
|
226
|
+
order: part.order
|
|
227
|
+
};
|
|
228
|
+
});
|
|
229
|
+
indexes.push({
|
|
230
|
+
name,
|
|
231
|
+
unique: index.unique,
|
|
232
|
+
fields: mapped
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
return new EntityMetadata({
|
|
236
|
+
entity,
|
|
237
|
+
collection: own.entityName,
|
|
238
|
+
primaryKey,
|
|
239
|
+
columns,
|
|
240
|
+
indexes
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
// src/metadata/metadata-registry.ts
|
|
244
|
+
var MetadataRegistry = class {
|
|
245
|
+
#metadata = /* @__PURE__ */ new Map();
|
|
246
|
+
#collections = /* @__PURE__ */ new Map();
|
|
247
|
+
#finalized = false;
|
|
248
|
+
constructor(entities = []) {
|
|
249
|
+
for (const entity of entities) this.register(entity);
|
|
250
|
+
}
|
|
251
|
+
register(entity) {
|
|
252
|
+
if (this.#finalized) throw new InvalidMetadataError("Metadata registry is finalized");
|
|
253
|
+
const existing = this.#metadata.get(entity);
|
|
254
|
+
if (existing) return existing;
|
|
255
|
+
const metadata = buildEntityMetadata(entity);
|
|
256
|
+
const collectionOwner = this.#collections.get(metadata.collection);
|
|
257
|
+
if (collectionOwner && collectionOwner != entity) throw new InvalidMetadataError(`Duplicate entity collection: ${metadata.collection}`);
|
|
258
|
+
this.#metadata.set(entity, metadata);
|
|
259
|
+
this.#collections.set(metadata.collection, entity);
|
|
260
|
+
return metadata;
|
|
261
|
+
}
|
|
262
|
+
finalize() {
|
|
263
|
+
this.#finalized = true;
|
|
264
|
+
return this;
|
|
265
|
+
}
|
|
266
|
+
get(entity) {
|
|
267
|
+
const metadata = this.#metadata.get(entity);
|
|
268
|
+
if (!metadata) throw new EntityNotRegisteredError(entity);
|
|
269
|
+
return metadata;
|
|
270
|
+
}
|
|
271
|
+
has(entity) {
|
|
272
|
+
return this.#metadata.has(entity);
|
|
273
|
+
}
|
|
274
|
+
all() {
|
|
275
|
+
return Object.freeze([...this.#metadata.values()].map((metadata) => metadata));
|
|
276
|
+
}
|
|
277
|
+
get finalized() {
|
|
278
|
+
return this.#finalized;
|
|
279
|
+
}
|
|
280
|
+
};
|
|
281
|
+
// src/mapping/value-transformer.ts
|
|
282
|
+
var ValueTransformer = class {
|
|
283
|
+
toDocument(column, value) {
|
|
284
|
+
if (value === null) {
|
|
285
|
+
if (!column.nullable) throw new InvalidColumnError(`Column ${column.property} is not nullable`);
|
|
286
|
+
return null;
|
|
287
|
+
}
|
|
288
|
+
switch (column.type) {
|
|
289
|
+
case "string": return typeof value != "string" ? this.invalid(column, "string") : value;
|
|
290
|
+
case "number": return typeof value != "number" || !Number.isFinite(value) ? this.invalid(column, "finite number") : Object.is(value, -0) ? 0 : value;
|
|
291
|
+
case "boolean": return typeof value != "boolean" ? this.invalid(column, "boolean") : value;
|
|
292
|
+
case "date": return !(value instanceof Date) || !Number.isFinite(value.getTime()) ? this.invalid(column, "valid Date") : value.toISOString();
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
fromDocument(column, value) {
|
|
296
|
+
if (value === null) {
|
|
297
|
+
if (!column.nullable) throw new InvalidColumnError(`Stored column ${column.field} is not nullable`);
|
|
298
|
+
return null;
|
|
299
|
+
}
|
|
300
|
+
if (column.type == "date") {
|
|
301
|
+
if (typeof value != "string") return this.invalid(column, "canonical date string");
|
|
302
|
+
const date = new Date(value);
|
|
303
|
+
return !Number.isFinite(date.getTime()) || date.toISOString() != value ? this.invalid(column, "canonical date string") : date;
|
|
304
|
+
}
|
|
305
|
+
return this.toDocument(column, value);
|
|
306
|
+
}
|
|
307
|
+
invalid(column, expected) {
|
|
308
|
+
throw new InvalidColumnError(`Column ${column.property} must be a ${expected}`);
|
|
309
|
+
}
|
|
310
|
+
};
|
|
311
|
+
// src/mapping/entity-hydrator.ts
|
|
312
|
+
var EntityHydrator = class {
|
|
313
|
+
metadata;
|
|
314
|
+
transformer;
|
|
315
|
+
constructor(metadata, transformer = new ValueTransformer()) {
|
|
316
|
+
this.metadata = metadata;
|
|
317
|
+
this.transformer = transformer;
|
|
318
|
+
}
|
|
319
|
+
hydrate(id, document) {
|
|
320
|
+
const entity = Object.create(this.metadata.entity.prototype);
|
|
321
|
+
this.define(entity, this.metadata.primaryKey, id);
|
|
322
|
+
for (const column of this.metadata.columns) if (Object.hasOwn(document, column.field)) this.define(entity, column.property, this.transformer.fromDocument(column, document[column.field]));
|
|
323
|
+
return entity;
|
|
324
|
+
}
|
|
325
|
+
create(data) {
|
|
326
|
+
const entity = Object.create(this.metadata.entity.prototype);
|
|
327
|
+
const allowed = /* @__PURE__ */ new Set([this.metadata.primaryKey, ...this.metadata.columns.map((column) => column.property)]);
|
|
328
|
+
for (const key of allowed) {
|
|
329
|
+
const descriptor = Object.getOwnPropertyDescriptor(data, key);
|
|
330
|
+
if (descriptor && "value" in descriptor && descriptor.value !== void 0) this.define(entity, key, descriptor.value);
|
|
331
|
+
}
|
|
332
|
+
return entity;
|
|
333
|
+
}
|
|
334
|
+
define(target, property, value) {
|
|
335
|
+
Object.defineProperty(target, property, {
|
|
336
|
+
value,
|
|
337
|
+
enumerable: true,
|
|
338
|
+
configurable: true,
|
|
339
|
+
writable: true
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
// src/mapping/entity-mapper.ts
|
|
344
|
+
var EntityMapper = class {
|
|
345
|
+
metadata;
|
|
346
|
+
#transformer = new ValueTransformer();
|
|
347
|
+
#hydrator;
|
|
348
|
+
constructor(metadata) {
|
|
349
|
+
this.metadata = metadata;
|
|
350
|
+
this.#hydrator = new EntityHydrator(metadata, this.#transformer);
|
|
351
|
+
}
|
|
352
|
+
create(data) {
|
|
353
|
+
return this.#hydrator.create(data);
|
|
354
|
+
}
|
|
355
|
+
serialize(entity) {
|
|
356
|
+
const id = this.ownValue(entity, this.metadata.primaryKey);
|
|
357
|
+
if (typeof id != "string" || id.length == 0) throw new MissingPrimaryKeyError(`Primary key ${this.metadata.primaryKey} must be a non-empty string`);
|
|
358
|
+
const document = {};
|
|
359
|
+
for (const column of this.metadata.columns) {
|
|
360
|
+
const descriptor = Object.getOwnPropertyDescriptor(entity, column.property);
|
|
361
|
+
if (!descriptor || !("value" in descriptor) || descriptor.value === void 0) {
|
|
362
|
+
if (column.required) throw new InvalidColumnError(`Missing required column: ${column.property}`);
|
|
363
|
+
continue;
|
|
364
|
+
}
|
|
365
|
+
document[column.field] = this.#transformer.toDocument(column, descriptor.value);
|
|
366
|
+
}
|
|
367
|
+
return {
|
|
368
|
+
id,
|
|
369
|
+
document
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
hydrate(id, document) {
|
|
373
|
+
return this.#hydrator.hydrate(id, document);
|
|
374
|
+
}
|
|
375
|
+
ownValue(entity, property) {
|
|
376
|
+
const descriptor = Object.getOwnPropertyDescriptor(entity, property);
|
|
377
|
+
if (!descriptor || !("value" in descriptor)) return void 0;
|
|
378
|
+
return descriptor.value;
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
// src/query/query-builder.ts
|
|
382
|
+
var QueryBuilder = class QueryBuilder {
|
|
383
|
+
mapper;
|
|
384
|
+
executor;
|
|
385
|
+
collection;
|
|
386
|
+
state;
|
|
387
|
+
constructor(mapper, executor, collection, state = { orderBy: [] }) {
|
|
388
|
+
this.mapper = mapper;
|
|
389
|
+
this.executor = executor;
|
|
390
|
+
this.collection = collection;
|
|
391
|
+
this.state = state;
|
|
392
|
+
}
|
|
393
|
+
where(property, operator, ...value) {
|
|
394
|
+
return this.with({ where: this.mapper.comparison(property, operator, value[0]) });
|
|
395
|
+
}
|
|
396
|
+
andWhere(property, operator, ...value) {
|
|
397
|
+
return this.combine("and", this.mapper.comparison(property, operator, value[0]));
|
|
398
|
+
}
|
|
399
|
+
orWhere(property, operator, ...value) {
|
|
400
|
+
return this.combine("or", this.mapper.comparison(property, operator, value[0]));
|
|
401
|
+
}
|
|
402
|
+
andWhereGroup(where) {
|
|
403
|
+
return this.combine("and", this.mapper.where(where));
|
|
404
|
+
}
|
|
405
|
+
orWhereGroup(where) {
|
|
406
|
+
return this.combine("or", this.mapper.where(where));
|
|
407
|
+
}
|
|
408
|
+
notWhere(where) {
|
|
409
|
+
return this.combine("and", {
|
|
410
|
+
type: "not",
|
|
411
|
+
predicate: this.mapper.where(where)
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
orderBy(property, direction) {
|
|
415
|
+
const field = this.mapper.field(property);
|
|
416
|
+
return this.with({ orderBy: [...this.state.orderBy.filter((order) => order.field != field), {
|
|
417
|
+
field,
|
|
418
|
+
direction
|
|
419
|
+
}] });
|
|
420
|
+
}
|
|
421
|
+
select(properties) {
|
|
422
|
+
return this.with({ projection: properties.map((property) => {
|
|
423
|
+
const field = this.mapper.field(property);
|
|
424
|
+
if (field == "$id") throw new Error("Primary key is always selected");
|
|
425
|
+
return field;
|
|
426
|
+
}) });
|
|
427
|
+
}
|
|
428
|
+
limit(limit) {
|
|
429
|
+
return this.with({ limit });
|
|
430
|
+
}
|
|
431
|
+
cursor(cursor) {
|
|
432
|
+
return this.with({ cursor });
|
|
433
|
+
}
|
|
434
|
+
withSignal(signal) {
|
|
435
|
+
return this.with({ signal });
|
|
436
|
+
}
|
|
437
|
+
async getMany() {
|
|
438
|
+
return (await this.executor.queryRows(this.toLogicalQuery(), this.state.signal)).map(this.executor.hydrate);
|
|
439
|
+
}
|
|
440
|
+
async getOne() {
|
|
441
|
+
const rows = await this.executor.queryRows({
|
|
442
|
+
...this.toLogicalQuery(),
|
|
443
|
+
limit: 1
|
|
444
|
+
}, this.state.signal);
|
|
445
|
+
return rows[0] ? this.executor.hydrate(rows[0]) : null;
|
|
446
|
+
}
|
|
447
|
+
async getCount() {
|
|
448
|
+
const query = this.toLogicalQuery();
|
|
449
|
+
return this.executor.count({
|
|
450
|
+
collection: query.collection,
|
|
451
|
+
...query.where ? { where: query.where } : {}
|
|
452
|
+
}, this.state.signal);
|
|
453
|
+
}
|
|
454
|
+
async getPage() {
|
|
455
|
+
const page = await this.executor.queryPage(this.toLogicalQuery(), this.state.signal);
|
|
456
|
+
return {
|
|
457
|
+
items: page.rows.map(this.executor.hydrate),
|
|
458
|
+
nextCursor: page.nextCursor
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
explain() {
|
|
462
|
+
return this.executor.explain(this.toLogicalQuery());
|
|
463
|
+
}
|
|
464
|
+
toLogicalQuery() {
|
|
465
|
+
return {
|
|
466
|
+
collection: this.collection,
|
|
467
|
+
...this.state.where ? { where: this.state.where } : {},
|
|
468
|
+
...this.state.orderBy.length ? { orderBy: this.state.orderBy } : {},
|
|
469
|
+
...this.state.projection ? { projection: this.state.projection } : {},
|
|
470
|
+
...this.state.limit == null ? {} : { limit: this.state.limit },
|
|
471
|
+
...this.state.cursor == null ? {} : { cursor: this.state.cursor }
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
combine(type, predicate) {
|
|
475
|
+
return this.with({ where: this.state.where ? {
|
|
476
|
+
type,
|
|
477
|
+
predicates: [this.state.where, predicate]
|
|
478
|
+
} : predicate });
|
|
479
|
+
}
|
|
480
|
+
with(changes) {
|
|
481
|
+
return new QueryBuilder(this.mapper, this.executor, this.collection, {
|
|
482
|
+
...this.state,
|
|
483
|
+
...changes
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
};
|
|
487
|
+
// src/query/query-mapper.ts
|
|
488
|
+
var OPERATORS = /* @__PURE__ */ new Set([
|
|
489
|
+
"eq",
|
|
490
|
+
"ne",
|
|
491
|
+
"gt",
|
|
492
|
+
"gte",
|
|
493
|
+
"lt",
|
|
494
|
+
"lte",
|
|
495
|
+
"in",
|
|
496
|
+
"isNull",
|
|
497
|
+
"isMissing"
|
|
498
|
+
]);
|
|
499
|
+
function isRecord(value) {
|
|
500
|
+
return typeof value == "object" && value != null && !Array.isArray(value) && !(value instanceof Date);
|
|
501
|
+
}
|
|
502
|
+
var QueryMapper = class {
|
|
503
|
+
metadata;
|
|
504
|
+
constructor(metadata) {
|
|
505
|
+
this.metadata = metadata;
|
|
506
|
+
}
|
|
507
|
+
map(options = {}) {
|
|
508
|
+
if (options.limit != null && (!Number.isSafeInteger(options.limit) || options.limit < 0 || options.limit > 1e6)) throw new InvalidQueryError("Invalid query limit");
|
|
509
|
+
if (options.projection?.length == 0) throw new InvalidQueryError("Projection cannot be empty");
|
|
510
|
+
if (options.cursor != null && (options.cursor.length == 0 || options.cursor.length > 16384)) throw new InvalidQueryError("Invalid query cursor");
|
|
511
|
+
const where = options.where ? this.where(options.where) : void 0;
|
|
512
|
+
const orderBy = [];
|
|
513
|
+
for (const [property, direction] of Object.entries(options.orderBy ?? {})) {
|
|
514
|
+
if (direction !== "ASC" && direction !== "DESC") throw new InvalidQueryError(`Invalid order for ${property}`);
|
|
515
|
+
orderBy.push({
|
|
516
|
+
field: this.field(property),
|
|
517
|
+
direction
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
const projection = options.projection?.map((property) => {
|
|
521
|
+
const field = this.field(property);
|
|
522
|
+
if (field == "$id") throw new InvalidQueryError("Primary key is always returned separately");
|
|
523
|
+
return field;
|
|
524
|
+
});
|
|
525
|
+
return {
|
|
526
|
+
collection: this.metadata.collection,
|
|
527
|
+
...where == null ? {} : { where },
|
|
528
|
+
...orderBy.length == 0 ? {} : { orderBy },
|
|
529
|
+
...projection == null ? {} : { projection },
|
|
530
|
+
...options.limit == null ? {} : { limit: options.limit },
|
|
531
|
+
...options.cursor == null ? {} : { cursor: options.cursor }
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
where(where) {
|
|
535
|
+
if (!isRecord(where)) throw new InvalidQueryError("Where clause must be an object");
|
|
536
|
+
const predicates = [];
|
|
537
|
+
for (const [property, condition] of Object.entries(where)) if (property == "AND" || property == "OR") {
|
|
538
|
+
if (!Array.isArray(condition) || condition.length == 0) throw new InvalidQueryError(`${property} requires at least one predicate`);
|
|
539
|
+
predicates.push({
|
|
540
|
+
type: property == "AND" ? "and" : "or",
|
|
541
|
+
predicates: condition.map((item) => this.where(item))
|
|
542
|
+
});
|
|
543
|
+
} else if (property == "NOT") predicates.push({
|
|
544
|
+
type: "not",
|
|
545
|
+
predicate: this.where(condition)
|
|
546
|
+
});
|
|
547
|
+
else predicates.push(...this.condition(property, condition));
|
|
548
|
+
if (predicates.length == 0) throw new InvalidQueryError("Where clause cannot be empty");
|
|
549
|
+
return predicates.length == 1 ? predicates[0] : {
|
|
550
|
+
type: "and",
|
|
551
|
+
predicates
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
comparison(property, operator, value) {
|
|
555
|
+
const field = this.field(property);
|
|
556
|
+
if ([
|
|
557
|
+
"eq",
|
|
558
|
+
"ne",
|
|
559
|
+
"gt",
|
|
560
|
+
"gte",
|
|
561
|
+
"lt",
|
|
562
|
+
"lte"
|
|
563
|
+
].includes(operator)) return {
|
|
564
|
+
type: "comparison",
|
|
565
|
+
field,
|
|
566
|
+
operator,
|
|
567
|
+
value: this.scalar(property, value)
|
|
568
|
+
};
|
|
569
|
+
if (operator == "in") {
|
|
570
|
+
if (!Array.isArray(value) || value.length == 0) throw new InvalidQueryError(`IN on ${property} requires a non-empty array`);
|
|
571
|
+
return {
|
|
572
|
+
type: "in",
|
|
573
|
+
field,
|
|
574
|
+
values: value.map((item) => this.scalar(property, item))
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
if (operator == "isNull" || operator == "isMissing") return {
|
|
578
|
+
type: operator,
|
|
579
|
+
field
|
|
580
|
+
};
|
|
581
|
+
throw new InvalidQueryError(`Unknown query operator: ${operator}`);
|
|
582
|
+
}
|
|
583
|
+
field(property) {
|
|
584
|
+
if (property == this.metadata.primaryKey) return "$id";
|
|
585
|
+
const column = this.metadata.columnForProperty(property);
|
|
586
|
+
if (!column) throw new InvalidQueryError(`Unknown entity property: ${property}`);
|
|
587
|
+
return column.field;
|
|
588
|
+
}
|
|
589
|
+
condition(property, condition) {
|
|
590
|
+
this.field(property);
|
|
591
|
+
if (!isRecord(condition)) return [this.comparison(property, "eq", condition)];
|
|
592
|
+
const entries = Object.entries(condition);
|
|
593
|
+
if (entries.length == 0) throw new InvalidQueryError(`Empty condition for ${property}`);
|
|
594
|
+
return entries.map(([operator, value]) => {
|
|
595
|
+
if (!OPERATORS.has(operator)) throw new InvalidQueryError(`Unknown query operator: ${operator}`);
|
|
596
|
+
if ((operator == "isNull" || operator == "isMissing") && value !== true) throw new InvalidQueryError(`${operator} must be true`);
|
|
597
|
+
return this.comparison(property, operator, value);
|
|
598
|
+
});
|
|
599
|
+
}
|
|
600
|
+
scalar(property, value) {
|
|
601
|
+
if (property == this.metadata.primaryKey) {
|
|
602
|
+
if (typeof value == "string") return value;
|
|
603
|
+
throw new InvalidQueryError("Primary-key comparisons require a string");
|
|
604
|
+
}
|
|
605
|
+
const column = this.metadata.columnForProperty(property);
|
|
606
|
+
if (!column) throw new InvalidQueryError(`Unknown entity property: ${property}`);
|
|
607
|
+
if (value === null) {
|
|
608
|
+
if (column.nullable) return null;
|
|
609
|
+
throw new InvalidQueryError(`Column ${property} is not nullable`);
|
|
610
|
+
}
|
|
611
|
+
if (column.type == "date" && value instanceof Date && Number.isFinite(value.getTime())) return value;
|
|
612
|
+
if (column.type == "string" && typeof value == "string") return value;
|
|
613
|
+
if (column.type == "boolean" && typeof value == "boolean") return value;
|
|
614
|
+
if (column.type == "number" && typeof value == "number" && Number.isFinite(value)) return value;
|
|
615
|
+
throw new InvalidQueryError(`Invalid query value for ${property}`);
|
|
616
|
+
}
|
|
617
|
+
};
|
|
618
|
+
// src/repository/repository.ts
|
|
619
|
+
var Repository = class {
|
|
620
|
+
metadata;
|
|
621
|
+
runtime;
|
|
622
|
+
#entityMapper;
|
|
623
|
+
#queryMapper;
|
|
624
|
+
constructor(metadata, runtime) {
|
|
625
|
+
this.metadata = metadata;
|
|
626
|
+
this.runtime = runtime;
|
|
627
|
+
this.#entityMapper = new EntityMapper(metadata);
|
|
628
|
+
this.#queryMapper = new QueryMapper(metadata);
|
|
629
|
+
}
|
|
630
|
+
create(data) {
|
|
631
|
+
this.runtime.assertUsable();
|
|
632
|
+
return this.#entityMapper.create(data);
|
|
633
|
+
}
|
|
634
|
+
async insert(entity) {
|
|
635
|
+
this.runtime.assertUsable();
|
|
636
|
+
const serialized = this.#entityMapper.serialize(entity);
|
|
637
|
+
await this.write(async (tx) => {
|
|
638
|
+
if (await tx.getDocument(this.metadata.collection, serialized.id) != null) throw new DuplicateRecordError(`Record already exists: ${this.metadata.collection}/${serialized.id}`);
|
|
639
|
+
tx.putDocument(this.metadata.collection, serialized.id, serialized.document);
|
|
640
|
+
});
|
|
641
|
+
return entity;
|
|
642
|
+
}
|
|
643
|
+
save(entity) {
|
|
644
|
+
return this.upsert(entity);
|
|
645
|
+
}
|
|
646
|
+
async update(id, changes) {
|
|
647
|
+
this.runtime.assertUsable();
|
|
648
|
+
let updated;
|
|
649
|
+
await this.write(async (tx) => {
|
|
650
|
+
const document = await tx.getDocument(this.metadata.collection, id);
|
|
651
|
+
if (!document) throw new RecordNotFoundError(`Record not found: ${this.metadata.collection}/${id}`);
|
|
652
|
+
const entity = this.#entityMapper.hydrate(id, document);
|
|
653
|
+
const primaryChange = Object.getOwnPropertyDescriptor(changes, this.metadata.primaryKey);
|
|
654
|
+
if (primaryChange && "value" in primaryChange && primaryChange.value !== void 0 && primaryChange.value !== id) throw new InvalidColumnError("Primary key cannot be changed by update()");
|
|
655
|
+
for (const column of this.metadata.columns) {
|
|
656
|
+
const descriptor = Object.getOwnPropertyDescriptor(changes, column.property);
|
|
657
|
+
if (descriptor && "value" in descriptor && descriptor.value !== void 0) Object.defineProperty(entity, column.property, {
|
|
658
|
+
value: descriptor.value,
|
|
659
|
+
enumerable: true,
|
|
660
|
+
configurable: true,
|
|
661
|
+
writable: true
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
const serialized = this.#entityMapper.serialize(entity);
|
|
665
|
+
tx.putDocument(this.metadata.collection, id, serialized.document);
|
|
666
|
+
updated = entity;
|
|
667
|
+
});
|
|
668
|
+
if (!updated) throw new Error("Update completed without an entity result");
|
|
669
|
+
return updated;
|
|
670
|
+
}
|
|
671
|
+
async upsert(entity) {
|
|
672
|
+
this.runtime.assertUsable();
|
|
673
|
+
const serialized = this.#entityMapper.serialize(entity);
|
|
674
|
+
await this.write((tx) => {
|
|
675
|
+
tx.putDocument(this.metadata.collection, serialized.id, serialized.document);
|
|
676
|
+
});
|
|
677
|
+
return entity;
|
|
678
|
+
}
|
|
679
|
+
async delete(id) {
|
|
680
|
+
this.runtime.assertUsable();
|
|
681
|
+
let deleted = false;
|
|
682
|
+
await this.write(async (tx) => {
|
|
683
|
+
if (await tx.getDocument(this.metadata.collection, id) == null) return;
|
|
684
|
+
tx.deleteDocument(this.metadata.collection, id);
|
|
685
|
+
deleted = true;
|
|
686
|
+
});
|
|
687
|
+
return deleted;
|
|
688
|
+
}
|
|
689
|
+
async findById(id) {
|
|
690
|
+
this.runtime.assertUsable();
|
|
691
|
+
if (this.runtime.transaction) {
|
|
692
|
+
const document = await this.runtime.transaction.getDocument(this.metadata.collection, id);
|
|
693
|
+
return document ? this.#entityMapper.hydrate(id, document) : null;
|
|
694
|
+
}
|
|
695
|
+
const row = (await this.runtime.database.queryPage({
|
|
696
|
+
collection: this.metadata.collection,
|
|
697
|
+
where: {
|
|
698
|
+
type: "comparison",
|
|
699
|
+
field: "$id",
|
|
700
|
+
operator: "eq",
|
|
701
|
+
value: id
|
|
702
|
+
},
|
|
703
|
+
limit: 1
|
|
704
|
+
})).rows[0];
|
|
705
|
+
return row ? this.#entityMapper.hydrate(row.id, row.document) : null;
|
|
706
|
+
}
|
|
707
|
+
async findOne(options = {}) {
|
|
708
|
+
const rows = await this.queryRows({
|
|
709
|
+
...this.#queryMapper.map(options),
|
|
710
|
+
limit: 1
|
|
711
|
+
}, options.signal);
|
|
712
|
+
return rows[0] ? this.hydrate(rows[0]) : null;
|
|
713
|
+
}
|
|
714
|
+
async find(options = {}) {
|
|
715
|
+
return (await this.queryRows(this.#queryMapper.map(options), options.signal)).map((row) => this.hydrate(row));
|
|
716
|
+
}
|
|
717
|
+
async findPage(options) {
|
|
718
|
+
const page = await this.queryPage(this.#queryMapper.map(options), options.signal);
|
|
719
|
+
return {
|
|
720
|
+
items: page.rows.map((row) => this.hydrate(row)),
|
|
721
|
+
nextCursor: page.nextCursor
|
|
722
|
+
};
|
|
723
|
+
}
|
|
724
|
+
async exists(options = {}) {
|
|
725
|
+
return await this.findOne(options) != null;
|
|
726
|
+
}
|
|
727
|
+
async count(options = {}) {
|
|
728
|
+
const query = this.#queryMapper.map(options);
|
|
729
|
+
let count = 0;
|
|
730
|
+
for await (const _row of this.sourceQuery(query, options.signal)) count++;
|
|
731
|
+
return count;
|
|
732
|
+
}
|
|
733
|
+
createQueryBuilder() {
|
|
734
|
+
this.runtime.assertUsable();
|
|
735
|
+
return new QueryBuilder(this.#queryMapper, {
|
|
736
|
+
queryRows: (query, signal) => this.queryRows(query, signal),
|
|
737
|
+
queryPage: (query, signal) => this.queryPage(query, signal),
|
|
738
|
+
count: async (query, signal) => {
|
|
739
|
+
let count = 0;
|
|
740
|
+
for await (const _row of this.sourceQuery(query, signal)) count++;
|
|
741
|
+
return count;
|
|
742
|
+
},
|
|
743
|
+
hydrate: (row) => this.hydrate(row),
|
|
744
|
+
explain: (query) => this.runtime.database.explain(query)
|
|
745
|
+
}, this.metadata.collection);
|
|
746
|
+
}
|
|
747
|
+
hydrate(row) {
|
|
748
|
+
return this.#entityMapper.hydrate(row.id, row.document);
|
|
749
|
+
}
|
|
750
|
+
async queryRows(query, signal) {
|
|
751
|
+
this.runtime.assertUsable();
|
|
752
|
+
const rows = [];
|
|
753
|
+
for await (const row of this.sourceQuery(query, signal)) rows.push(row);
|
|
754
|
+
return rows;
|
|
755
|
+
}
|
|
756
|
+
queryPage(query, signal) {
|
|
757
|
+
this.runtime.assertUsable();
|
|
758
|
+
return this.runtime.transaction ? this.runtime.transaction.queryPage(query, { signal }) : this.runtime.database.queryPage(query, { signal });
|
|
759
|
+
}
|
|
760
|
+
sourceQuery(query, signal) {
|
|
761
|
+
this.runtime.assertUsable();
|
|
762
|
+
return this.runtime.transaction ? this.runtime.transaction.query(query, { signal }) : this.runtime.database.query(query, { signal });
|
|
763
|
+
}
|
|
764
|
+
async write(action) {
|
|
765
|
+
try {
|
|
766
|
+
if (this.runtime.transaction) await action(this.runtime.transaction);
|
|
767
|
+
else await this.runtime.database.transaction(action);
|
|
768
|
+
} catch (cause) {
|
|
769
|
+
if (cause instanceof _duraxis_core.UniqueIndexViolationError) throw new UniqueIndexViolationOrmError(cause.message, cause);
|
|
770
|
+
throw cause;
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
};
|
|
774
|
+
// src/schema/schema-mapper.ts
|
|
775
|
+
function mapEntitySchema(metadata) {
|
|
776
|
+
return {
|
|
777
|
+
name: metadata.collection,
|
|
778
|
+
fields: Object.fromEntries(metadata.columns.map((column) => [column.field, {
|
|
779
|
+
type: column.type,
|
|
780
|
+
required: column.required,
|
|
781
|
+
nullable: column.nullable
|
|
782
|
+
}])),
|
|
783
|
+
allowAdditionalFields: false,
|
|
784
|
+
indexes: metadata.indexes.map((index) => ({
|
|
785
|
+
name: index.name,
|
|
786
|
+
unique: index.unique,
|
|
787
|
+
fields: index.fields.map((field) => ({
|
|
788
|
+
field: field.field,
|
|
789
|
+
order: field.order
|
|
790
|
+
}))
|
|
791
|
+
}))
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
// src/schema/schema-manager.ts
|
|
795
|
+
function same(left, right) {
|
|
796
|
+
return JSON.stringify(left) == JSON.stringify(right);
|
|
797
|
+
}
|
|
798
|
+
function indexMap(definition) {
|
|
799
|
+
return new Map(definition.indexes.map((index) => [index.name, index]));
|
|
800
|
+
}
|
|
801
|
+
var SchemaManager = class {
|
|
802
|
+
database;
|
|
803
|
+
registry;
|
|
804
|
+
mode;
|
|
805
|
+
constructor(database, registry, mode) {
|
|
806
|
+
this.database = database;
|
|
807
|
+
this.registry = registry;
|
|
808
|
+
this.mode = mode;
|
|
809
|
+
}
|
|
810
|
+
async initialize() {
|
|
811
|
+
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));
|
|
814
|
+
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
|
+
}
|
|
821
|
+
this.validateFields(expected, current);
|
|
822
|
+
const actualIndexes = indexMap(current);
|
|
823
|
+
for (const expectedIndex of expected.indexes) {
|
|
824
|
+
const actual = actualIndexes.get(expectedIndex.name);
|
|
825
|
+
if (!actual) {
|
|
826
|
+
if (this.mode == "validate") throw new SchemaViolationError(`Missing index: ${expected.name}/${expectedIndex.name}`);
|
|
827
|
+
await this.mutate(() => this.database.addIndex(expected.name, expectedIndex), `Could not create index: ${expected.name}/${expectedIndex.name}`);
|
|
828
|
+
continue;
|
|
829
|
+
}
|
|
830
|
+
if (!same(actual, expectedIndex)) throw new SchemaViolationError(`Incompatible index: ${expected.name}/${expectedIndex.name}`);
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
validateFields(expected, actual) {
|
|
835
|
+
if (expected.allowAdditionalFields != actual.allowAdditionalFields || !same(expected.fields ?? {}, actual.fields ?? {})) throw new SchemaViolationError(`Incompatible collection schema: ${expected.name}`);
|
|
836
|
+
}
|
|
837
|
+
async mutate(operation, message) {
|
|
838
|
+
try {
|
|
839
|
+
await operation();
|
|
840
|
+
} catch (cause) {
|
|
841
|
+
if (cause instanceof _duraxis_core.TransactionConflictError || cause instanceof _duraxis_core.CommitOutcomeUnknownError || cause instanceof SchemaViolationError) throw cause;
|
|
842
|
+
throw new SchemaViolationError(message, { cause });
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
};
|
|
846
|
+
// src/transactions/orm-transaction.ts
|
|
847
|
+
var OrmTransactionManager = class {
|
|
848
|
+
database;
|
|
849
|
+
transaction;
|
|
850
|
+
registry;
|
|
851
|
+
#repositories = /* @__PURE__ */ new Map();
|
|
852
|
+
#active = true;
|
|
853
|
+
constructor(database, transaction, registry) {
|
|
854
|
+
this.database = database;
|
|
855
|
+
this.transaction = transaction;
|
|
856
|
+
this.registry = registry;
|
|
857
|
+
}
|
|
858
|
+
getRepository(entity) {
|
|
859
|
+
this.assertActive();
|
|
860
|
+
const cached = this.#repositories.get(entity);
|
|
861
|
+
if (cached) return cached;
|
|
862
|
+
const repository = new Repository(this.registry.get(entity), {
|
|
863
|
+
database: this.database,
|
|
864
|
+
transaction: this.transaction,
|
|
865
|
+
assertUsable: () => this.assertActive()
|
|
866
|
+
});
|
|
867
|
+
this.#repositories.set(entity, repository);
|
|
868
|
+
return repository;
|
|
869
|
+
}
|
|
870
|
+
close() {
|
|
871
|
+
this.#active = false;
|
|
872
|
+
this.#repositories.clear();
|
|
873
|
+
}
|
|
874
|
+
assertActive() {
|
|
875
|
+
if (!this.#active) throw new TransactionManagerClosedError();
|
|
876
|
+
}
|
|
877
|
+
};
|
|
878
|
+
// src/database/duraxis-orm.ts
|
|
879
|
+
var DuraxisORM = class {
|
|
880
|
+
options;
|
|
881
|
+
#registry;
|
|
882
|
+
#repositories = /* @__PURE__ */ new Map();
|
|
883
|
+
#lifecycle = "new";
|
|
884
|
+
#initialization;
|
|
885
|
+
constructor(options) {
|
|
886
|
+
this.options = options;
|
|
887
|
+
this.#registry = new MetadataRegistry(options.entities).finalize();
|
|
888
|
+
}
|
|
889
|
+
initialize() {
|
|
890
|
+
if (this.#lifecycle == "closed") return Promise.reject(new OrmClosedError());
|
|
891
|
+
if (this.#lifecycle == "initialized") return Promise.resolve();
|
|
892
|
+
if (this.#initialization) return this.#initialization;
|
|
893
|
+
this.#lifecycle = "initializing";
|
|
894
|
+
this.#initialization = (async () => {
|
|
895
|
+
try {
|
|
896
|
+
await new SchemaManager(this.options.database, this.#registry, this.options.schema?.mode ?? "validate").initialize();
|
|
897
|
+
if (this.#lifecycle == "closed") throw new OrmClosedError();
|
|
898
|
+
this.#lifecycle = "initialized";
|
|
899
|
+
} catch (error) {
|
|
900
|
+
if (this.#lifecycle != "closed") this.#lifecycle = "new";
|
|
901
|
+
this.#initialization = void 0;
|
|
902
|
+
throw error;
|
|
903
|
+
}
|
|
904
|
+
})();
|
|
905
|
+
return this.#initialization;
|
|
906
|
+
}
|
|
907
|
+
getRepository(entity) {
|
|
908
|
+
this.assertReady();
|
|
909
|
+
const cached = this.#repositories.get(entity);
|
|
910
|
+
if (cached) return cached;
|
|
911
|
+
const repository = new Repository(this.#registry.get(entity), {
|
|
912
|
+
database: this.options.database,
|
|
913
|
+
assertUsable: () => this.assertReady()
|
|
914
|
+
});
|
|
915
|
+
this.#repositories.set(entity, repository);
|
|
916
|
+
return repository;
|
|
917
|
+
}
|
|
918
|
+
async transaction(callback) {
|
|
919
|
+
this.assertReady();
|
|
920
|
+
try {
|
|
921
|
+
return await this.options.database.transaction(async (transaction) => {
|
|
922
|
+
const manager = new OrmTransactionManager(this.options.database, transaction, this.#registry);
|
|
923
|
+
try {
|
|
924
|
+
return await callback(manager);
|
|
925
|
+
} finally {
|
|
926
|
+
manager.close();
|
|
927
|
+
}
|
|
928
|
+
});
|
|
929
|
+
} catch (cause) {
|
|
930
|
+
if (cause instanceof _duraxis_core.UniqueIndexViolationError) throw new UniqueIndexViolationOrmError(cause.message, cause);
|
|
931
|
+
throw cause;
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
async close() {
|
|
935
|
+
if (this.#lifecycle == "closed") return;
|
|
936
|
+
const initialization = this.#initialization;
|
|
937
|
+
if (initialization) await initialization.catch(() => void 0);
|
|
938
|
+
this.#lifecycle = "closed";
|
|
939
|
+
this.#repositories.clear();
|
|
940
|
+
if (this.options.closeDatabase || this.options.closeStorage) await this.options.database.close({ closeStorage: this.options.closeStorage ?? false });
|
|
941
|
+
}
|
|
942
|
+
get metadata() {
|
|
943
|
+
return this.#registry;
|
|
944
|
+
}
|
|
945
|
+
assertReady() {
|
|
946
|
+
if (this.#lifecycle == "closed") throw new OrmClosedError();
|
|
947
|
+
if (this.#lifecycle != "initialized") throw new OrmNotInitializedError();
|
|
948
|
+
}
|
|
949
|
+
};
|
|
950
|
+
exports.Column = Column;
|
|
951
|
+
Object.defineProperty(exports, "CommitOutcomeUnknownError", {
|
|
952
|
+
enumerable: true,
|
|
953
|
+
get: function() {
|
|
954
|
+
return _duraxis_core.CommitOutcomeUnknownError;
|
|
955
|
+
}
|
|
956
|
+
});
|
|
957
|
+
exports.DuplicateRecordError = DuplicateRecordError;
|
|
958
|
+
exports.DuraxisORM = DuraxisORM;
|
|
959
|
+
exports.DuraxisOrmError = DuraxisOrmError;
|
|
960
|
+
exports.Entity = Entity;
|
|
961
|
+
exports.EntityHydrator = EntityHydrator;
|
|
962
|
+
exports.EntityMapper = EntityMapper;
|
|
963
|
+
exports.EntityMetadata = EntityMetadata;
|
|
964
|
+
exports.EntityNotRegisteredError = EntityNotRegisteredError;
|
|
965
|
+
exports.Index = Index;
|
|
966
|
+
exports.InvalidColumnError = InvalidColumnError;
|
|
967
|
+
exports.InvalidMetadataError = InvalidMetadataError;
|
|
968
|
+
exports.InvalidQueryError = InvalidQueryError;
|
|
969
|
+
exports.MetadataRegistry = MetadataRegistry;
|
|
970
|
+
exports.MissingPrimaryKeyError = MissingPrimaryKeyError;
|
|
971
|
+
exports.OrmClosedError = OrmClosedError;
|
|
972
|
+
exports.OrmNotInitializedError = OrmNotInitializedError;
|
|
973
|
+
exports.OrmTransactionManager = OrmTransactionManager;
|
|
974
|
+
exports.PrimaryKey = PrimaryKey;
|
|
975
|
+
exports.QueryBuilder = QueryBuilder;
|
|
976
|
+
exports.RecordNotFoundError = RecordNotFoundError;
|
|
977
|
+
exports.Repository = Repository;
|
|
978
|
+
exports.SchemaManager = SchemaManager;
|
|
979
|
+
exports.SchemaViolationError = SchemaViolationError;
|
|
980
|
+
Object.defineProperty(exports, "TransactionConflictError", {
|
|
981
|
+
enumerable: true,
|
|
982
|
+
get: function() {
|
|
983
|
+
return _duraxis_core.TransactionConflictError;
|
|
984
|
+
}
|
|
985
|
+
});
|
|
986
|
+
exports.TransactionManagerClosedError = TransactionManagerClosedError;
|
|
987
|
+
exports.UniqueIndexViolationOrmError = UniqueIndexViolationOrmError;
|
|
988
|
+
exports.ValueTransformer = ValueTransformer;
|
|
989
|
+
|
|
990
|
+
//# sourceMappingURL=index.cjs.map
|