@cyphra/runtime 0.1.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +3 -1
- package/dist/index.d.ts +328 -2
- package/dist/index.js +960 -0
- package/dist/index.js.map +1 -1
- package/package.json +30 -8
package/dist/index.js
CHANGED
|
@@ -155,8 +155,968 @@ var CyphraClient = class {
|
|
|
155
155
|
await this.driver.close();
|
|
156
156
|
}
|
|
157
157
|
};
|
|
158
|
+
|
|
159
|
+
// src/orm/client.ts
|
|
160
|
+
import { compileCypher as compileCypher2 } from "@cyphra/query";
|
|
161
|
+
|
|
162
|
+
// src/orm/engine.ts
|
|
163
|
+
import { randomUUID, getRandomValues } from "crypto";
|
|
164
|
+
import { isInt as isInt2 } from "neo4j-driver";
|
|
165
|
+
|
|
166
|
+
// src/orm/compile.ts
|
|
167
|
+
import neo4j3 from "neo4j-driver";
|
|
168
|
+
|
|
169
|
+
// src/orm/errors.ts
|
|
170
|
+
var CyphraError = class extends Error {
|
|
171
|
+
constructor(message) {
|
|
172
|
+
super(message);
|
|
173
|
+
this.name = new.target.name;
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
var CyphraValidationError = class extends CyphraError {
|
|
177
|
+
};
|
|
178
|
+
var NotFoundError = class extends CyphraError {
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
// src/orm/values.ts
|
|
182
|
+
import neo4j2, { isDate, isDateTime, isInt, isLocalDateTime } from "neo4j-driver";
|
|
183
|
+
function integerToNumber(v) {
|
|
184
|
+
if (!v.inSafeRange()) {
|
|
185
|
+
throw new RangeError(`Neo4j integer ${v.toString()} is outside the JS safe integer range.`);
|
|
186
|
+
}
|
|
187
|
+
return v.toNumber();
|
|
188
|
+
}
|
|
189
|
+
function encodeOne(type, value, where) {
|
|
190
|
+
switch (type) {
|
|
191
|
+
case "String":
|
|
192
|
+
if (typeof value !== "string") break;
|
|
193
|
+
return value;
|
|
194
|
+
case "Boolean":
|
|
195
|
+
if (typeof value !== "boolean") break;
|
|
196
|
+
return value;
|
|
197
|
+
case "Float":
|
|
198
|
+
if (typeof value !== "number") break;
|
|
199
|
+
return value;
|
|
200
|
+
case "Int":
|
|
201
|
+
if (typeof value === "number" && Number.isInteger(value)) return neo4j2.int(value);
|
|
202
|
+
if (typeof value === "bigint") return neo4j2.int(value.toString());
|
|
203
|
+
break;
|
|
204
|
+
case "DateTime": {
|
|
205
|
+
const d = typeof value === "string" ? new Date(value) : value;
|
|
206
|
+
if (!(d instanceof Date) || Number.isNaN(d.getTime())) break;
|
|
207
|
+
return neo4j2.types.DateTime.fromStandardDate(d);
|
|
208
|
+
}
|
|
209
|
+
case "Date": {
|
|
210
|
+
const d = typeof value === "string" ? new Date(value) : value;
|
|
211
|
+
if (!(d instanceof Date) || Number.isNaN(d.getTime())) break;
|
|
212
|
+
return new neo4j2.types.Date(d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate());
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
throw new CyphraValidationError(`${where}: expected ${type}, got ${describe(value)}.`);
|
|
216
|
+
}
|
|
217
|
+
function describe(v) {
|
|
218
|
+
if (v === null) return "null";
|
|
219
|
+
if (v instanceof Date) return "Date";
|
|
220
|
+
if (Array.isArray(v)) return "array";
|
|
221
|
+
return typeof v;
|
|
222
|
+
}
|
|
223
|
+
function encodeScalar(field, value, owner) {
|
|
224
|
+
const where = `${owner}.${field.name}`;
|
|
225
|
+
if (value === null || value === void 0) {
|
|
226
|
+
if (!field.optional && !field.list && value === null) {
|
|
227
|
+
throw new CyphraValidationError(`${where}: field is required and cannot be null.`);
|
|
228
|
+
}
|
|
229
|
+
return null;
|
|
230
|
+
}
|
|
231
|
+
if (field.list) {
|
|
232
|
+
if (!Array.isArray(value)) {
|
|
233
|
+
throw new CyphraValidationError(`${where}: expected an array.`);
|
|
234
|
+
}
|
|
235
|
+
return value.map((v, i) => encodeOne(field.type, v, `${where}[${i}]`));
|
|
236
|
+
}
|
|
237
|
+
return encodeOne(field.type, value, where);
|
|
238
|
+
}
|
|
239
|
+
function encodeFilterValue(field, value, owner) {
|
|
240
|
+
return encodeOne(field.type, value, `${owner}.${field.name}`);
|
|
241
|
+
}
|
|
242
|
+
function decodeOne(type, value) {
|
|
243
|
+
if (value === null || value === void 0) return null;
|
|
244
|
+
if (isInt(value)) {
|
|
245
|
+
return integerToNumber(value);
|
|
246
|
+
}
|
|
247
|
+
if (type === "Date" && isDate(value)) {
|
|
248
|
+
const d = value;
|
|
249
|
+
return new Date(Date.UTC(Number(d.year), Number(d.month) - 1, Number(d.day)));
|
|
250
|
+
}
|
|
251
|
+
if (isDateTime(value) || isLocalDateTime(value)) {
|
|
252
|
+
return value.toStandardDate();
|
|
253
|
+
}
|
|
254
|
+
return value;
|
|
255
|
+
}
|
|
256
|
+
function decodeScalar(field, value) {
|
|
257
|
+
if (field.list) {
|
|
258
|
+
if (value === null || value === void 0) return [];
|
|
259
|
+
return value.map((v) => decodeOne(field.type, v));
|
|
260
|
+
}
|
|
261
|
+
return decodeOne(field.type, value);
|
|
262
|
+
}
|
|
263
|
+
function toNative(value) {
|
|
264
|
+
if (value === null || value === void 0) return value ?? null;
|
|
265
|
+
if (isInt(value)) return integerToNumber(value);
|
|
266
|
+
if (Array.isArray(value)) return value.map(toNative);
|
|
267
|
+
if (typeof value !== "object") return value;
|
|
268
|
+
if (isDate(value)) return decodeOne("Date", value);
|
|
269
|
+
if (isDateTime(value) || isLocalDateTime(value)) return decodeOne("DateTime", value);
|
|
270
|
+
const v = value;
|
|
271
|
+
if ("properties" in v && ("labels" in v || "type" in v) && "elementId" in v) {
|
|
272
|
+
return toNative(v.properties);
|
|
273
|
+
}
|
|
274
|
+
if (Object.getPrototypeOf(v) !== Object.prototype) return value;
|
|
275
|
+
const out = {};
|
|
276
|
+
for (const [k, x] of Object.entries(v)) out[k] = toNative(x);
|
|
277
|
+
return out;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// src/orm/compile.ts
|
|
281
|
+
function q(id) {
|
|
282
|
+
return "`" + id.replace(/`/g, "``") + "`";
|
|
283
|
+
}
|
|
284
|
+
var QueryContext = class {
|
|
285
|
+
constructor(schema) {
|
|
286
|
+
this.schema = schema;
|
|
287
|
+
}
|
|
288
|
+
schema;
|
|
289
|
+
params = {};
|
|
290
|
+
paramCount = 0;
|
|
291
|
+
varCount = 0;
|
|
292
|
+
/** Bind a value and return its `$placeholder`. */
|
|
293
|
+
param(value) {
|
|
294
|
+
const key = `p${this.paramCount++}`;
|
|
295
|
+
this.params[key] = value;
|
|
296
|
+
return `$${key}`;
|
|
297
|
+
}
|
|
298
|
+
/** Fresh variable name, e.g. `m3`. */
|
|
299
|
+
variable(prefix = "m") {
|
|
300
|
+
return `${prefix}${this.varCount++}`;
|
|
301
|
+
}
|
|
302
|
+
node(name) {
|
|
303
|
+
const n = this.schema.nodes.find((x) => x.name === name);
|
|
304
|
+
if (!n) throw new CyphraValidationError(`Unknown model "${name}".`);
|
|
305
|
+
return n;
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
function isPlainObject(v) {
|
|
309
|
+
return typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Date);
|
|
310
|
+
}
|
|
311
|
+
function scalarField(model, name) {
|
|
312
|
+
const f = model.fields.find((x) => x.name === name);
|
|
313
|
+
return f?.kind === "scalar" ? f : void 0;
|
|
314
|
+
}
|
|
315
|
+
function relationField(model, name) {
|
|
316
|
+
const f = model.fields.find((x) => x.name === name);
|
|
317
|
+
return f?.kind === "relation" ? f : void 0;
|
|
318
|
+
}
|
|
319
|
+
function scalarOrThrow(model, name) {
|
|
320
|
+
const f = scalarField(model, name);
|
|
321
|
+
if (!f) throw new CyphraValidationError(`Unknown scalar field "${model.name}.${name}".`);
|
|
322
|
+
return f;
|
|
323
|
+
}
|
|
324
|
+
function relationPattern(ctx, from, rel, to, relVar = "") {
|
|
325
|
+
const target = ctx.node(rel.target);
|
|
326
|
+
const edge = `[${relVar}:${q(rel.relType)}]`;
|
|
327
|
+
const end = `(${to}:${q(target.label)})`;
|
|
328
|
+
return rel.direction === "OUT" ? `(${from})-${edge}->${end}` : `(${from})<-${edge}-${end}`;
|
|
329
|
+
}
|
|
330
|
+
var SCALAR_OPS = /* @__PURE__ */ new Set([
|
|
331
|
+
"equals",
|
|
332
|
+
"not",
|
|
333
|
+
"in",
|
|
334
|
+
"notIn",
|
|
335
|
+
"lt",
|
|
336
|
+
"lte",
|
|
337
|
+
"gt",
|
|
338
|
+
"gte",
|
|
339
|
+
"contains",
|
|
340
|
+
"startsWith",
|
|
341
|
+
"endsWith"
|
|
342
|
+
]);
|
|
343
|
+
var LIST_OPS = /* @__PURE__ */ new Set(["has", "hasEvery", "hasSome", "isEmpty", "equals"]);
|
|
344
|
+
function and(parts) {
|
|
345
|
+
const p = parts.filter(Boolean);
|
|
346
|
+
if (p.length === 0) return null;
|
|
347
|
+
return p.length === 1 ? p[0] : p.map((x) => `(${x})`).join(" AND ");
|
|
348
|
+
}
|
|
349
|
+
function compileListFilter(ctx, model, field, ref, filter) {
|
|
350
|
+
if (!isPlainObject(filter)) {
|
|
351
|
+
throw new CyphraValidationError(
|
|
352
|
+
`${model.name}.${field.name}: list filters take { has, hasEvery, hasSome, isEmpty, equals }.`
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
const enc = (v) => encodeFilterValue(field, v, model.name);
|
|
356
|
+
const parts = [];
|
|
357
|
+
for (const [op, v] of Object.entries(filter)) {
|
|
358
|
+
if (v === void 0) continue;
|
|
359
|
+
if (!LIST_OPS.has(op)) throw new CyphraValidationError(`Unknown list filter "${op}".`);
|
|
360
|
+
const arr = (x) => {
|
|
361
|
+
if (!Array.isArray(x)) throw new CyphraValidationError(`${op} expects an array.`);
|
|
362
|
+
return x.map(enc);
|
|
363
|
+
};
|
|
364
|
+
if (op === "has") parts.push(`${ctx.param(enc(v))} IN ${ref}`);
|
|
365
|
+
if (op === "hasEvery") parts.push(`all(x IN ${ctx.param(arr(v))} WHERE x IN ${ref})`);
|
|
366
|
+
if (op === "hasSome") parts.push(`any(x IN ${ctx.param(arr(v))} WHERE x IN ${ref})`);
|
|
367
|
+
if (op === "isEmpty") parts.push(v ? `coalesce(size(${ref}), 0) = 0` : `size(${ref}) > 0`);
|
|
368
|
+
if (op === "equals") parts.push(`${ref} = ${ctx.param(arr(v))}`);
|
|
369
|
+
}
|
|
370
|
+
return and(parts);
|
|
371
|
+
}
|
|
372
|
+
function compileScalarFilter(ctx, model, field, ref, filter) {
|
|
373
|
+
if (filter === void 0) return null;
|
|
374
|
+
if (field.list) return compileListFilter(ctx, model, field, ref, filter);
|
|
375
|
+
const enc = (v) => encodeFilterValue(field, v, model.name);
|
|
376
|
+
if (filter === null) return `${ref} IS NULL`;
|
|
377
|
+
if (!isPlainObject(filter)) return `${ref} = ${ctx.param(enc(filter))}`;
|
|
378
|
+
const parts = [];
|
|
379
|
+
for (const [op, v] of Object.entries(filter)) {
|
|
380
|
+
if (v === void 0) continue;
|
|
381
|
+
if (!SCALAR_OPS.has(op)) {
|
|
382
|
+
throw new CyphraValidationError(`Unknown filter "${op}" on ${model.name}.${field.name}.`);
|
|
383
|
+
}
|
|
384
|
+
switch (op) {
|
|
385
|
+
case "equals":
|
|
386
|
+
parts.push(v === null ? `${ref} IS NULL` : `${ref} = ${ctx.param(enc(v))}`);
|
|
387
|
+
break;
|
|
388
|
+
case "not":
|
|
389
|
+
if (v === null) parts.push(`${ref} IS NOT NULL`);
|
|
390
|
+
else if (isPlainObject(v)) {
|
|
391
|
+
const inner = compileScalarFilter(ctx, model, field, ref, v);
|
|
392
|
+
if (inner) parts.push(`NOT (${inner})`);
|
|
393
|
+
} else parts.push(`${ref} <> ${ctx.param(enc(v))}`);
|
|
394
|
+
break;
|
|
395
|
+
case "in":
|
|
396
|
+
case "notIn": {
|
|
397
|
+
if (!Array.isArray(v)) throw new CyphraValidationError(`${op} expects an array.`);
|
|
398
|
+
const p = ctx.param(v.map(enc));
|
|
399
|
+
parts.push(op === "in" ? `${ref} IN ${p}` : `NOT ${ref} IN ${p}`);
|
|
400
|
+
break;
|
|
401
|
+
}
|
|
402
|
+
case "lt":
|
|
403
|
+
case "lte":
|
|
404
|
+
case "gt":
|
|
405
|
+
case "gte": {
|
|
406
|
+
const sym = { lt: "<", lte: "<=", gt: ">", gte: ">=" }[op];
|
|
407
|
+
parts.push(`${ref} ${sym} ${ctx.param(enc(v))}`);
|
|
408
|
+
break;
|
|
409
|
+
}
|
|
410
|
+
case "contains":
|
|
411
|
+
case "startsWith":
|
|
412
|
+
case "endsWith": {
|
|
413
|
+
if (field.type !== "String" || typeof v !== "string") {
|
|
414
|
+
throw new CyphraValidationError(`${op} is only valid on String fields.`);
|
|
415
|
+
}
|
|
416
|
+
const kw = { contains: "CONTAINS", startsWith: "STARTS WITH", endsWith: "ENDS WITH" }[op];
|
|
417
|
+
parts.push(`${ref} ${kw} ${ctx.param(v)}`);
|
|
418
|
+
break;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
return and(parts);
|
|
423
|
+
}
|
|
424
|
+
function compileRelationFilter(ctx, model, rel, alias, filter) {
|
|
425
|
+
if (filter === void 0) return null;
|
|
426
|
+
const target = ctx.node(rel.target);
|
|
427
|
+
const exists = (where) => {
|
|
428
|
+
const m = ctx.variable();
|
|
429
|
+
const pattern = relationPattern(ctx, alias, rel, m);
|
|
430
|
+
const inner = where === void 0 ? null : compileWhere(ctx, target, m, where);
|
|
431
|
+
return inner ? `EXISTS { MATCH ${pattern} WHERE ${inner} }` : `EXISTS { MATCH ${pattern} }`;
|
|
432
|
+
};
|
|
433
|
+
if (rel.many) {
|
|
434
|
+
if (!isPlainObject(filter)) {
|
|
435
|
+
throw new CyphraValidationError(
|
|
436
|
+
`${model.name}.${rel.name}: to-many relation filters take { some, none, every }.`
|
|
437
|
+
);
|
|
438
|
+
}
|
|
439
|
+
const parts2 = [];
|
|
440
|
+
for (const [op, v] of Object.entries(filter)) {
|
|
441
|
+
if (v === void 0) continue;
|
|
442
|
+
if (op === "some") parts2.push(exists(v));
|
|
443
|
+
else if (op === "none") parts2.push(`NOT ${exists(v)}`);
|
|
444
|
+
else if (op === "every") {
|
|
445
|
+
const m = ctx.variable();
|
|
446
|
+
const inner = compileWhere(ctx, target, m, v);
|
|
447
|
+
if (inner) {
|
|
448
|
+
parts2.push(
|
|
449
|
+
`NOT EXISTS { MATCH ${relationPattern(ctx, alias, rel, m)} WHERE NOT (${inner}) }`
|
|
450
|
+
);
|
|
451
|
+
}
|
|
452
|
+
} else throw new CyphraValidationError(`Unknown relation filter "${op}".`);
|
|
453
|
+
}
|
|
454
|
+
return and(parts2);
|
|
455
|
+
}
|
|
456
|
+
if (filter === null) return `NOT ${exists(void 0)}`;
|
|
457
|
+
if (!isPlainObject(filter)) {
|
|
458
|
+
throw new CyphraValidationError(
|
|
459
|
+
`${model.name}.${rel.name}: to-one relation filters take { is, isNot } or null.`
|
|
460
|
+
);
|
|
461
|
+
}
|
|
462
|
+
const parts = [];
|
|
463
|
+
for (const [op, v] of Object.entries(filter)) {
|
|
464
|
+
if (v === void 0) continue;
|
|
465
|
+
if (op === "is") parts.push(v === null ? `NOT ${exists(void 0)}` : exists(v));
|
|
466
|
+
else if (op === "isNot") parts.push(v === null ? exists(void 0) : `NOT ${exists(v)}`);
|
|
467
|
+
else throw new CyphraValidationError(`Unknown relation filter "${op}".`);
|
|
468
|
+
}
|
|
469
|
+
return and(parts);
|
|
470
|
+
}
|
|
471
|
+
function compileWhere(ctx, model, alias, where) {
|
|
472
|
+
if (where === void 0 || where === null) return null;
|
|
473
|
+
if (!isPlainObject(where)) {
|
|
474
|
+
throw new CyphraValidationError(`where on ${model.name} must be an object.`);
|
|
475
|
+
}
|
|
476
|
+
const parts = [];
|
|
477
|
+
for (const [key, value] of Object.entries(where)) {
|
|
478
|
+
if (value === void 0) continue;
|
|
479
|
+
if (key === "AND" || key === "OR" || key === "NOT") {
|
|
480
|
+
const list = Array.isArray(value) ? value : [value];
|
|
481
|
+
const compiled = list.map((w) => compileWhere(ctx, model, alias, w)).filter((x) => Boolean(x));
|
|
482
|
+
if (key === "AND") {
|
|
483
|
+
const a = and(compiled);
|
|
484
|
+
if (a) parts.push(a);
|
|
485
|
+
} else if (key === "OR") {
|
|
486
|
+
if (list.length === 0) parts.push("false");
|
|
487
|
+
else if (compiled.length === list.length) {
|
|
488
|
+
parts.push(compiled.map((x) => `(${x})`).join(" OR "));
|
|
489
|
+
}
|
|
490
|
+
} else {
|
|
491
|
+
for (const c2 of compiled) parts.push(`NOT (${c2})`);
|
|
492
|
+
}
|
|
493
|
+
continue;
|
|
494
|
+
}
|
|
495
|
+
const f = model.fields.find((x) => x.name === key);
|
|
496
|
+
if (!f) throw new CyphraValidationError(`Unknown field "${model.name}.${key}" in where.`);
|
|
497
|
+
const c = f.kind === "scalar" ? compileScalarFilter(ctx, model, f, `${alias}.${q(f.name)}`, value) : compileRelationFilter(ctx, model, f, alias, value);
|
|
498
|
+
if (c) parts.push(c);
|
|
499
|
+
}
|
|
500
|
+
return and(parts);
|
|
501
|
+
}
|
|
502
|
+
function compileOrderBy(model, alias, orderBy) {
|
|
503
|
+
if (orderBy === void 0 || orderBy === null) return null;
|
|
504
|
+
const list = Array.isArray(orderBy) ? orderBy : [orderBy];
|
|
505
|
+
const parts = [];
|
|
506
|
+
for (const item of list) {
|
|
507
|
+
if (!isPlainObject(item)) throw new CyphraValidationError("orderBy entries must be objects.");
|
|
508
|
+
for (const [key, dir] of Object.entries(item)) {
|
|
509
|
+
if (dir === void 0) continue;
|
|
510
|
+
scalarOrThrow(model, key);
|
|
511
|
+
if (dir !== "asc" && dir !== "desc") {
|
|
512
|
+
throw new CyphraValidationError(`orderBy ${model.name}.${key} must be "asc" or "desc".`);
|
|
513
|
+
}
|
|
514
|
+
parts.push(`${alias}.${q(key)} ${dir.toUpperCase()}`);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
return parts.length ? parts.join(", ") : null;
|
|
518
|
+
}
|
|
519
|
+
function nonNegativeInt(v, name) {
|
|
520
|
+
if (typeof v !== "number" || !Number.isInteger(v) || v < 0) {
|
|
521
|
+
throw new CyphraValidationError(`${name} must be a non-negative integer.`);
|
|
522
|
+
}
|
|
523
|
+
return v;
|
|
524
|
+
}
|
|
525
|
+
function compilePaging(ctx, model, alias, args) {
|
|
526
|
+
let s = "";
|
|
527
|
+
const order = compileOrderBy(model, alias, args.orderBy);
|
|
528
|
+
if (order) s += ` ORDER BY ${order}`;
|
|
529
|
+
if (args.skip !== void 0)
|
|
530
|
+
s += ` SKIP ${ctx.param(intParam(nonNegativeInt(args.skip, "skip")))}`;
|
|
531
|
+
if (args.take !== void 0)
|
|
532
|
+
s += ` LIMIT ${ctx.param(intParam(nonNegativeInt(args.take, "take")))}`;
|
|
533
|
+
return s;
|
|
534
|
+
}
|
|
535
|
+
function intParam(n) {
|
|
536
|
+
return neo4j3.int(n);
|
|
537
|
+
}
|
|
538
|
+
function compileProjection(ctx, model, alias, args, extraEntries = []) {
|
|
539
|
+
if (args.select !== void 0 && args.include !== void 0) {
|
|
540
|
+
throw new CyphraValidationError("Use either select or include, not both.");
|
|
541
|
+
}
|
|
542
|
+
const scalars = [];
|
|
543
|
+
const rels = [];
|
|
544
|
+
const allScalars = model.fields.filter((f) => f.kind === "scalar");
|
|
545
|
+
const takeRelations = (spec, label) => {
|
|
546
|
+
for (const [key, v] of Object.entries(spec)) {
|
|
547
|
+
if (v === void 0 || v === false) continue;
|
|
548
|
+
const f = model.fields.find((x) => x.name === key);
|
|
549
|
+
if (!f) throw new CyphraValidationError(`Unknown field "${model.name}.${key}" in ${label}.`);
|
|
550
|
+
if (f.kind === "scalar") {
|
|
551
|
+
if (label === "include") {
|
|
552
|
+
throw new CyphraValidationError(`include only takes relations ("${key}" is a scalar).`);
|
|
553
|
+
}
|
|
554
|
+
scalars.push(f);
|
|
555
|
+
} else {
|
|
556
|
+
rels.push({ field: f, args: isPlainObject(v) ? v : {} });
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
};
|
|
560
|
+
if (args.select !== void 0) {
|
|
561
|
+
if (!isPlainObject(args.select)) throw new CyphraValidationError("select must be an object.");
|
|
562
|
+
takeRelations(args.select, "select");
|
|
563
|
+
} else {
|
|
564
|
+
scalars.push(...allScalars);
|
|
565
|
+
if (args.include !== void 0) {
|
|
566
|
+
if (!isPlainObject(args.include))
|
|
567
|
+
throw new CyphraValidationError("include must be an object.");
|
|
568
|
+
takeRelations(args.include, "include");
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
const entries = scalars.map((f) => `.${q(f.name)}`);
|
|
572
|
+
const relShapes = [];
|
|
573
|
+
for (const { field, args: sub } of rels) {
|
|
574
|
+
const target = ctx.node(field.target);
|
|
575
|
+
const m = ctx.variable();
|
|
576
|
+
const r = ctx.variable("r");
|
|
577
|
+
const edgeModel = field.edge ? ctx.schema.relationships.find((x) => x.name === field.edge) : void 0;
|
|
578
|
+
const inner = compileProjection(
|
|
579
|
+
ctx,
|
|
580
|
+
target,
|
|
581
|
+
m,
|
|
582
|
+
sub,
|
|
583
|
+
edgeModel ? [`${q("$edge")}: properties(${r})`] : []
|
|
584
|
+
);
|
|
585
|
+
const item = inner.expr;
|
|
586
|
+
const where = compileWhere(ctx, target, m, sub.where);
|
|
587
|
+
const paging = compilePaging(ctx, target, m, sub);
|
|
588
|
+
let body = `MATCH ${relationPattern(ctx, alias, field, m, r)}`;
|
|
589
|
+
if (where) body += ` WHERE ${where}`;
|
|
590
|
+
if (paging) body += ` WITH ${m}, ${r}${paging}`;
|
|
591
|
+
body += ` RETURN ${item}`;
|
|
592
|
+
const collected = `COLLECT { ${body} }`;
|
|
593
|
+
entries.push(`${q(field.name)}: ${field.many ? collected : `head(${collected})`}`);
|
|
594
|
+
relShapes.push({
|
|
595
|
+
field,
|
|
596
|
+
shape: inner.shape,
|
|
597
|
+
...edgeModel ? { edge: edgeModel.properties } : {}
|
|
598
|
+
});
|
|
599
|
+
}
|
|
600
|
+
entries.push(...extraEntries);
|
|
601
|
+
return {
|
|
602
|
+
expr: `${alias}{${entries.join(", ")}}`,
|
|
603
|
+
shape: { model, scalars, relations: relShapes }
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
function decodeRow(shape, row) {
|
|
607
|
+
if (row === null || row === void 0) return null;
|
|
608
|
+
const src = row;
|
|
609
|
+
const out = {};
|
|
610
|
+
for (const f of shape.scalars) out[f.name] = decodeScalar(f, src[f.name]);
|
|
611
|
+
for (const r of shape.relations) {
|
|
612
|
+
const decodeItem = (v2) => {
|
|
613
|
+
const item = decodeRow(r.shape, v2);
|
|
614
|
+
if (item && r.edge) {
|
|
615
|
+
const rawEdge = v2["$edge"] ?? {};
|
|
616
|
+
const edge = {};
|
|
617
|
+
for (const p of r.edge) edge[p.name] = decodeScalar(p, rawEdge[p.name]);
|
|
618
|
+
item.$edge = edge;
|
|
619
|
+
}
|
|
620
|
+
return item;
|
|
621
|
+
};
|
|
622
|
+
const v = src[r.field.name];
|
|
623
|
+
out[r.field.name] = r.field.many ? (v ?? []).map(decodeItem) : decodeItem(v);
|
|
624
|
+
}
|
|
625
|
+
return out;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
// src/orm/engine.ts
|
|
629
|
+
function isPlainObject2(v) {
|
|
630
|
+
return typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Date);
|
|
631
|
+
}
|
|
632
|
+
function toCount(v) {
|
|
633
|
+
return isInt2(v) ? integerToNumber(v) : Number(v ?? 0);
|
|
634
|
+
}
|
|
635
|
+
var ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
|
|
636
|
+
function createCuid() {
|
|
637
|
+
const bytes = getRandomValues(new Uint8Array(24));
|
|
638
|
+
let s = ALPHABET[bytes[0] % 26];
|
|
639
|
+
for (let i = 1; i < 24; i++) s += ALPHABET[bytes[i] % 36];
|
|
640
|
+
return s;
|
|
641
|
+
}
|
|
642
|
+
function asArray(v) {
|
|
643
|
+
return Array.isArray(v) ? v : [v];
|
|
644
|
+
}
|
|
645
|
+
var ModelEngine = class _ModelEngine {
|
|
646
|
+
constructor(schema, model, runner) {
|
|
647
|
+
this.schema = schema;
|
|
648
|
+
this.model = model;
|
|
649
|
+
this.runner = runner;
|
|
650
|
+
}
|
|
651
|
+
schema;
|
|
652
|
+
model;
|
|
653
|
+
runner;
|
|
654
|
+
ctx() {
|
|
655
|
+
return new QueryContext(this.schema);
|
|
656
|
+
}
|
|
657
|
+
get label() {
|
|
658
|
+
return q(this.model.label);
|
|
659
|
+
}
|
|
660
|
+
// -------------------------------------------------------------------------
|
|
661
|
+
// Reads
|
|
662
|
+
// -------------------------------------------------------------------------
|
|
663
|
+
async readMany(exec, args) {
|
|
664
|
+
const ctx = this.ctx();
|
|
665
|
+
const where = compileWhere(ctx, this.model, "n", args.where);
|
|
666
|
+
const paging = compilePaging(ctx, this.model, "n", args);
|
|
667
|
+
const { expr, shape } = compileProjection(ctx, this.model, "n", args);
|
|
668
|
+
let text = `MATCH (n:${this.label})`;
|
|
669
|
+
if (where) text += ` WHERE ${where}`;
|
|
670
|
+
if (paging) text += ` WITH n${paging}`;
|
|
671
|
+
text += ` RETURN ${expr} AS row`;
|
|
672
|
+
const order = compileOrderBy(this.model, "n", args.orderBy);
|
|
673
|
+
if (order) text += ` ORDER BY ${order}`;
|
|
674
|
+
const rows = await exec(text, ctx.params);
|
|
675
|
+
return rows.map((r) => decodeRow(shape, r.row));
|
|
676
|
+
}
|
|
677
|
+
async readById(exec, id, args) {
|
|
678
|
+
const ctx = this.ctx();
|
|
679
|
+
const { expr, shape } = compileProjection(ctx, this.model, "n", args);
|
|
680
|
+
const rows = await exec(
|
|
681
|
+
`MATCH (n:${this.label}) WHERE elementId(n) = ${ctx.param(id)} RETURN ${expr} AS row`,
|
|
682
|
+
ctx.params
|
|
683
|
+
);
|
|
684
|
+
if (!rows[0]) throw new NotFoundError(`${this.model.name} disappeared during the operation.`);
|
|
685
|
+
return decodeRow(shape, rows[0].row);
|
|
686
|
+
}
|
|
687
|
+
assertUnique(where, op) {
|
|
688
|
+
const ok = isPlainObject2(where) && this.model.uniqueFields.some((k) => {
|
|
689
|
+
const v = where[k];
|
|
690
|
+
return v !== void 0 && v !== null && !isPlainObject2(v);
|
|
691
|
+
});
|
|
692
|
+
if (!ok) {
|
|
693
|
+
throw new CyphraValidationError(
|
|
694
|
+
`${this.model.name}.${op}: where must set at least one unique field (${this.model.uniqueFields.join(", ") || "none declared \u2014 add @id or @unique"}).`
|
|
695
|
+
);
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
async findId(exec, where, op) {
|
|
699
|
+
this.assertUnique(where, op);
|
|
700
|
+
const ctx = this.ctx();
|
|
701
|
+
const w = compileWhere(ctx, this.model, "n", where);
|
|
702
|
+
const rows = await exec(
|
|
703
|
+
`MATCH (n:${this.label})${w ? ` WHERE ${w}` : ""} RETURN elementId(n) AS id LIMIT 1`,
|
|
704
|
+
ctx.params
|
|
705
|
+
);
|
|
706
|
+
return rows[0]?.id ?? null;
|
|
707
|
+
}
|
|
708
|
+
findMany(args = {}) {
|
|
709
|
+
return this.runner.read((exec) => this.readMany(exec, args));
|
|
710
|
+
}
|
|
711
|
+
async findFirst(args = {}) {
|
|
712
|
+
const rows = await this.findMany({ ...args, take: 1 });
|
|
713
|
+
return rows[0] ?? null;
|
|
714
|
+
}
|
|
715
|
+
async findUnique(args) {
|
|
716
|
+
this.assertUnique(args.where, "findUnique");
|
|
717
|
+
const rows = await this.findMany({ ...args, take: 1, skip: void 0, orderBy: void 0 });
|
|
718
|
+
return rows[0] ?? null;
|
|
719
|
+
}
|
|
720
|
+
async findUniqueOrThrow(args) {
|
|
721
|
+
const row = await this.findUnique(args);
|
|
722
|
+
if (!row)
|
|
723
|
+
throw new NotFoundError(`No ${this.model.name} matches ${JSON.stringify(args.where)}.`);
|
|
724
|
+
return row;
|
|
725
|
+
}
|
|
726
|
+
count(args = {}) {
|
|
727
|
+
return this.runner.read(async (exec) => {
|
|
728
|
+
const ctx = this.ctx();
|
|
729
|
+
const w = compileWhere(ctx, this.model, "n", args.where);
|
|
730
|
+
const rows = await exec(
|
|
731
|
+
`MATCH (n:${this.label})${w ? ` WHERE ${w}` : ""} RETURN count(n) AS c`,
|
|
732
|
+
ctx.params
|
|
733
|
+
);
|
|
734
|
+
return toCount(rows[0]?.c);
|
|
735
|
+
});
|
|
736
|
+
}
|
|
737
|
+
// -------------------------------------------------------------------------
|
|
738
|
+
// Write helpers
|
|
739
|
+
// -------------------------------------------------------------------------
|
|
740
|
+
node(name) {
|
|
741
|
+
return new QueryContext(this.schema).node(name);
|
|
742
|
+
}
|
|
743
|
+
engineFor(model) {
|
|
744
|
+
return model === this.model ? this : new _ModelEngine(this.schema, model, this.runner);
|
|
745
|
+
}
|
|
746
|
+
/** Encode scalar data for CREATE, applying defaults and checking required fields. */
|
|
747
|
+
static createProps(owner, fields, data) {
|
|
748
|
+
const props = {};
|
|
749
|
+
for (const f of fields) {
|
|
750
|
+
const v = data[f.name];
|
|
751
|
+
if (v !== void 0 && v !== null) {
|
|
752
|
+
props[f.name] = encodeScalar(f, v, owner);
|
|
753
|
+
continue;
|
|
754
|
+
}
|
|
755
|
+
if (v === null && !f.optional && !f.list) {
|
|
756
|
+
throw new CyphraValidationError(`${owner}.${f.name} is required and cannot be null.`);
|
|
757
|
+
}
|
|
758
|
+
if (v === void 0 && f.default) {
|
|
759
|
+
const d = f.default;
|
|
760
|
+
const value = d.kind === "literal" ? d.value : d.fn === "uuid" ? randomUUID() : d.fn === "cuid" ? createCuid() : /* @__PURE__ */ new Date();
|
|
761
|
+
props[f.name] = encodeScalar(f, value, owner);
|
|
762
|
+
continue;
|
|
763
|
+
}
|
|
764
|
+
if (v === void 0 && !f.optional && !f.list) {
|
|
765
|
+
throw new CyphraValidationError(`${owner}.${f.name} is required.`);
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
return props;
|
|
769
|
+
}
|
|
770
|
+
splitData(data, op) {
|
|
771
|
+
if (!isPlainObject2(data))
|
|
772
|
+
throw new CyphraValidationError(`${this.model.name}.${op}: data must be an object.`);
|
|
773
|
+
const scalars = {};
|
|
774
|
+
const relations = {};
|
|
775
|
+
for (const [k, v] of Object.entries(data)) {
|
|
776
|
+
if (v === void 0) continue;
|
|
777
|
+
const f = this.model.fields.find((x) => x.name === k);
|
|
778
|
+
if (!f)
|
|
779
|
+
throw new CyphraValidationError(`Unknown field "${this.model.name}.${k}" in ${op} data.`);
|
|
780
|
+
(f.kind === "scalar" ? scalars : relations)[k] = v;
|
|
781
|
+
}
|
|
782
|
+
return { scalars, relations };
|
|
783
|
+
}
|
|
784
|
+
edgeProps(rel, input) {
|
|
785
|
+
if (input === void 0) {
|
|
786
|
+
if (!rel.edge) return {};
|
|
787
|
+
input = {};
|
|
788
|
+
}
|
|
789
|
+
const edgeModel = rel.edge ? this.schema.relationships.find((r) => r.name === rel.edge) : void 0;
|
|
790
|
+
if (!edgeModel) {
|
|
791
|
+
throw new CyphraValidationError(
|
|
792
|
+
`${this.model.name}.${rel.name}: $edge given but no relationship model types this edge.`
|
|
793
|
+
);
|
|
794
|
+
}
|
|
795
|
+
if (!isPlainObject2(input)) throw new CyphraValidationError("$edge must be an object.");
|
|
796
|
+
for (const k of Object.keys(input)) {
|
|
797
|
+
if (!edgeModel.properties.some((p) => p.name === k)) {
|
|
798
|
+
throw new CyphraValidationError(`Unknown edge property "${edgeModel.name}.${k}".`);
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
return _ModelEngine.createProps(edgeModel.name, edgeModel.properties, input);
|
|
802
|
+
}
|
|
803
|
+
edgeText(ctx, rel, a, b, props) {
|
|
804
|
+
const p = Object.keys(props).length ? ` ${ctx.param(props)}` : "";
|
|
805
|
+
const edge = `[r:${q(rel.relType)}${p}]`;
|
|
806
|
+
return rel.direction === "OUT" ? `(${a})-${edge}->(${b})` : `(${a})<-${edge}-(${b})`;
|
|
807
|
+
}
|
|
808
|
+
/** CREATE a node with nested relation writes; returns its elementId. */
|
|
809
|
+
async createNode(exec, data) {
|
|
810
|
+
const { scalars, relations } = this.splitData(data, "create");
|
|
811
|
+
const fields = this.model.fields.filter((f) => f.kind === "scalar");
|
|
812
|
+
const props = _ModelEngine.createProps(this.model.name, fields, scalars);
|
|
813
|
+
const ctx = this.ctx();
|
|
814
|
+
const rows = await exec(
|
|
815
|
+
`CREATE (n:${this.label} ${ctx.param(props)}) RETURN elementId(n) AS id`,
|
|
816
|
+
ctx.params
|
|
817
|
+
);
|
|
818
|
+
const id = rows[0].id;
|
|
819
|
+
for (const [k, v] of Object.entries(relations)) {
|
|
820
|
+
await this.writeRelation(exec, id, relationField(this.model, k), v, "create");
|
|
821
|
+
}
|
|
822
|
+
return id;
|
|
823
|
+
}
|
|
824
|
+
async connect(exec, id, rel, item) {
|
|
825
|
+
if (!isPlainObject2(item))
|
|
826
|
+
throw new CyphraValidationError(`${rel.name}.connect expects unique where objects.`);
|
|
827
|
+
const { $edge, ...where } = item;
|
|
828
|
+
const target = this.node(rel.target);
|
|
829
|
+
this.engineFor(target).assertUnique(where, `${this.model.name}.${rel.name}.connect`);
|
|
830
|
+
const ctx = this.ctx();
|
|
831
|
+
const w = compileWhere(ctx, target, "b", where);
|
|
832
|
+
const edge = this.edgeText(ctx, rel, "a", "b", this.edgeProps(rel, $edge));
|
|
833
|
+
const rows = await exec(
|
|
834
|
+
`MATCH (a) WHERE elementId(a) = ${ctx.param(id)} MATCH (b:${q(target.label)})${w ? ` WHERE ${w}` : ""} WITH a, b LIMIT 1 CREATE ${edge} RETURN count(r) AS c`,
|
|
835
|
+
ctx.params
|
|
836
|
+
);
|
|
837
|
+
if (toCount(rows[0]?.c) === 0) {
|
|
838
|
+
throw new NotFoundError(`connect: no ${target.name} matches ${JSON.stringify(where)}.`);
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
async createRelated(exec, id, rel, item) {
|
|
842
|
+
if (!isPlainObject2(item))
|
|
843
|
+
throw new CyphraValidationError(`${rel.name}.create expects objects.`);
|
|
844
|
+
const { $edge, ...data } = item;
|
|
845
|
+
const props = this.edgeProps(rel, $edge);
|
|
846
|
+
const childId = await this.engineFor(this.node(rel.target)).createNode(exec, data);
|
|
847
|
+
const ctx = this.ctx();
|
|
848
|
+
await exec(
|
|
849
|
+
`MATCH (a), (b) WHERE elementId(a) = ${ctx.param(id)} AND elementId(b) = ${ctx.param(childId)} CREATE ${this.edgeText(ctx, rel, "a", "b", props)}`,
|
|
850
|
+
ctx.params
|
|
851
|
+
);
|
|
852
|
+
}
|
|
853
|
+
async deleteEdges(exec, id, rel, where) {
|
|
854
|
+
const target = this.node(rel.target);
|
|
855
|
+
const ctx = this.ctx();
|
|
856
|
+
const w = where ? compileWhere(ctx, target, "b", where) : null;
|
|
857
|
+
const rows = await exec(
|
|
858
|
+
`MATCH ${relationPattern(ctx, "a", rel, "b", "r")} WHERE elementId(a) = ${ctx.param(id)}${w ? ` AND ${w}` : ""} DELETE r RETURN count(*) AS c`,
|
|
859
|
+
ctx.params
|
|
860
|
+
);
|
|
861
|
+
return toCount(rows[0]?.c);
|
|
862
|
+
}
|
|
863
|
+
async writeRelation(exec, id, rel, spec, mode) {
|
|
864
|
+
if (!isPlainObject2(spec)) {
|
|
865
|
+
throw new CyphraValidationError(
|
|
866
|
+
`${this.model.name}.${rel.name}: relation writes take { create, connect, \u2026 }.`
|
|
867
|
+
);
|
|
868
|
+
}
|
|
869
|
+
const allowed = mode === "create" ? ["create", "connect"] : ["create", "connect", "disconnect", "set"];
|
|
870
|
+
for (const k of Object.keys(spec)) {
|
|
871
|
+
if (!allowed.includes(k) || k === "set" && !rel.many) {
|
|
872
|
+
throw new CyphraValidationError(
|
|
873
|
+
`${this.model.name}.${rel.name}: unsupported relation operation "${k}".`
|
|
874
|
+
);
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
const { create, connect, disconnect, set } = spec;
|
|
878
|
+
if (!rel.many) {
|
|
879
|
+
for (const [k, v] of [
|
|
880
|
+
["create", create],
|
|
881
|
+
["connect", connect]
|
|
882
|
+
]) {
|
|
883
|
+
if (Array.isArray(v))
|
|
884
|
+
throw new CyphraValidationError(
|
|
885
|
+
`${rel.name}.${k}: to-one relations take a single object.`
|
|
886
|
+
);
|
|
887
|
+
}
|
|
888
|
+
if ([create, connect].filter((x) => x !== void 0).length > 1) {
|
|
889
|
+
throw new CyphraValidationError(
|
|
890
|
+
`${rel.name}: use only one of create / connect on a to-one relation.`
|
|
891
|
+
);
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
if (rel.many) {
|
|
895
|
+
if (disconnect !== void 0) {
|
|
896
|
+
for (const item of asArray(disconnect)) {
|
|
897
|
+
if (!isPlainObject2(item))
|
|
898
|
+
throw new CyphraValidationError(`${rel.name}.disconnect expects unique where objects.`);
|
|
899
|
+
this.engineFor(this.node(rel.target)).assertUnique(
|
|
900
|
+
item,
|
|
901
|
+
`${this.model.name}.${rel.name}.disconnect`
|
|
902
|
+
);
|
|
903
|
+
await this.deleteEdges(exec, id, rel, item);
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
if (set !== void 0) {
|
|
907
|
+
if (!Array.isArray(set))
|
|
908
|
+
throw new CyphraValidationError(`${rel.name}.set expects an array.`);
|
|
909
|
+
await this.deleteEdges(exec, id, rel);
|
|
910
|
+
for (const item of set) await this.connect(exec, id, rel, item);
|
|
911
|
+
}
|
|
912
|
+
} else if (disconnect === true || mode === "update" && (create !== void 0 || connect !== void 0)) {
|
|
913
|
+
await this.deleteEdges(exec, id, rel);
|
|
914
|
+
} else if (disconnect !== void 0 && disconnect !== false) {
|
|
915
|
+
throw new CyphraValidationError(
|
|
916
|
+
`${rel.name}.disconnect on a to-one relation takes a boolean.`
|
|
917
|
+
);
|
|
918
|
+
}
|
|
919
|
+
if (connect !== void 0)
|
|
920
|
+
for (const item of asArray(connect)) await this.connect(exec, id, rel, item);
|
|
921
|
+
if (create !== void 0)
|
|
922
|
+
for (const item of asArray(create)) await this.createRelated(exec, id, rel, item);
|
|
923
|
+
}
|
|
924
|
+
/** Compile scalar `data` of an update into `SET` assignments for variable `n`. */
|
|
925
|
+
setClauses(ctx, scalars) {
|
|
926
|
+
const sets = [];
|
|
927
|
+
for (const [k, v] of Object.entries(scalars)) {
|
|
928
|
+
const f = scalarField(this.model, k);
|
|
929
|
+
const ref = `n.${q(k)}`;
|
|
930
|
+
if (isPlainObject2(v) && !f.list) {
|
|
931
|
+
if (f.type !== "Int" && f.type !== "Float") {
|
|
932
|
+
throw new CyphraValidationError(
|
|
933
|
+
`${this.model.name}.${k}: object updates are only for numbers.`
|
|
934
|
+
);
|
|
935
|
+
}
|
|
936
|
+
for (const [op, amount] of Object.entries(v)) {
|
|
937
|
+
if (amount === void 0) continue;
|
|
938
|
+
const sym = { increment: "+", decrement: "-", multiply: "*" }[op];
|
|
939
|
+
if (!sym) throw new CyphraValidationError(`Unknown number update "${op}".`);
|
|
940
|
+
sets.push(
|
|
941
|
+
`${ref} = ${ref} ${sym} ${ctx.param(encodeScalar(f, amount, this.model.name))}`
|
|
942
|
+
);
|
|
943
|
+
}
|
|
944
|
+
continue;
|
|
945
|
+
}
|
|
946
|
+
sets.push(`${ref} = ${ctx.param(encodeScalar(f, v, this.model.name))}`);
|
|
947
|
+
}
|
|
948
|
+
return sets;
|
|
949
|
+
}
|
|
950
|
+
async updateNode(exec, id, data) {
|
|
951
|
+
const { scalars, relations } = this.splitData(data, "update");
|
|
952
|
+
const ctx = this.ctx();
|
|
953
|
+
const sets = this.setClauses(ctx, scalars);
|
|
954
|
+
if (sets.length) {
|
|
955
|
+
await exec(
|
|
956
|
+
`MATCH (n) WHERE elementId(n) = ${ctx.param(id)} SET ${sets.join(", ")}`,
|
|
957
|
+
ctx.params
|
|
958
|
+
);
|
|
959
|
+
}
|
|
960
|
+
for (const [k, v] of Object.entries(relations)) {
|
|
961
|
+
await this.writeRelation(exec, id, relationField(this.model, k), v, "update");
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
// -------------------------------------------------------------------------
|
|
965
|
+
// Writes
|
|
966
|
+
// -------------------------------------------------------------------------
|
|
967
|
+
create(args) {
|
|
968
|
+
return this.runner.write(async (exec) => {
|
|
969
|
+
const id = await this.createNode(exec, args.data);
|
|
970
|
+
return this.readById(exec, id, args);
|
|
971
|
+
});
|
|
972
|
+
}
|
|
973
|
+
createMany(args) {
|
|
974
|
+
if (!Array.isArray(args.data))
|
|
975
|
+
throw new CyphraValidationError("createMany: data must be an array.");
|
|
976
|
+
const fields = this.model.fields.filter((f) => f.kind === "scalar");
|
|
977
|
+
const rows = args.data.map((d) => {
|
|
978
|
+
const { scalars, relations } = this.splitData(d, "createMany");
|
|
979
|
+
if (Object.keys(relations).length) {
|
|
980
|
+
throw new CyphraValidationError("createMany does not support nested relation writes.");
|
|
981
|
+
}
|
|
982
|
+
return _ModelEngine.createProps(this.model.name, fields, scalars);
|
|
983
|
+
});
|
|
984
|
+
if (rows.length === 0) return Promise.resolve({ count: 0 });
|
|
985
|
+
return this.runner.write(async (exec) => {
|
|
986
|
+
const ctx = this.ctx();
|
|
987
|
+
const res = await exec(
|
|
988
|
+
`UNWIND ${ctx.param(rows)} AS row CREATE (n:${this.label}) SET n = row RETURN count(n) AS c`,
|
|
989
|
+
ctx.params
|
|
990
|
+
);
|
|
991
|
+
return { count: toCount(res[0]?.c) };
|
|
992
|
+
});
|
|
993
|
+
}
|
|
994
|
+
update(args) {
|
|
995
|
+
return this.runner.write(async (exec) => {
|
|
996
|
+
const id = await this.findId(exec, args.where, "update");
|
|
997
|
+
if (!id)
|
|
998
|
+
throw new NotFoundError(
|
|
999
|
+
`update: no ${this.model.name} matches ${JSON.stringify(args.where)}.`
|
|
1000
|
+
);
|
|
1001
|
+
await this.updateNode(exec, id, args.data);
|
|
1002
|
+
return this.readById(exec, id, args);
|
|
1003
|
+
});
|
|
1004
|
+
}
|
|
1005
|
+
updateMany(args) {
|
|
1006
|
+
return this.runner.write(async (exec) => {
|
|
1007
|
+
const { scalars, relations } = this.splitData(args.data, "updateMany");
|
|
1008
|
+
if (Object.keys(relations).length) {
|
|
1009
|
+
throw new CyphraValidationError("updateMany does not support relation writes.");
|
|
1010
|
+
}
|
|
1011
|
+
const ctx = this.ctx();
|
|
1012
|
+
const w = compileWhere(ctx, this.model, "n", args.where);
|
|
1013
|
+
const sets = this.setClauses(ctx, scalars);
|
|
1014
|
+
const res = await exec(
|
|
1015
|
+
`MATCH (n:${this.label})${w ? ` WHERE ${w}` : ""}${sets.length ? ` SET ${sets.join(", ")}` : ""} RETURN count(n) AS c`,
|
|
1016
|
+
ctx.params
|
|
1017
|
+
);
|
|
1018
|
+
return { count: toCount(res[0]?.c) };
|
|
1019
|
+
});
|
|
1020
|
+
}
|
|
1021
|
+
upsert(args) {
|
|
1022
|
+
return this.runner.write(async (exec) => {
|
|
1023
|
+
const existing = await this.findId(exec, args.where, "upsert");
|
|
1024
|
+
let id;
|
|
1025
|
+
if (existing) {
|
|
1026
|
+
id = existing;
|
|
1027
|
+
await this.updateNode(exec, id, args.update);
|
|
1028
|
+
} else {
|
|
1029
|
+
id = await this.createNode(exec, args.create);
|
|
1030
|
+
}
|
|
1031
|
+
return this.readById(exec, id, args);
|
|
1032
|
+
});
|
|
1033
|
+
}
|
|
1034
|
+
delete(args) {
|
|
1035
|
+
return this.runner.write(async (exec) => {
|
|
1036
|
+
const id = await this.findId(exec, args.where, "delete");
|
|
1037
|
+
if (!id)
|
|
1038
|
+
throw new NotFoundError(
|
|
1039
|
+
`delete: no ${this.model.name} matches ${JSON.stringify(args.where)}.`
|
|
1040
|
+
);
|
|
1041
|
+
const row = await this.readById(exec, id, args);
|
|
1042
|
+
const ctx = this.ctx();
|
|
1043
|
+
await exec(`MATCH (n) WHERE elementId(n) = ${ctx.param(id)} DETACH DELETE n`, ctx.params);
|
|
1044
|
+
return row;
|
|
1045
|
+
});
|
|
1046
|
+
}
|
|
1047
|
+
deleteMany(args = {}) {
|
|
1048
|
+
return this.runner.write(async (exec) => {
|
|
1049
|
+
const ctx = this.ctx();
|
|
1050
|
+
const w = compileWhere(ctx, this.model, "n", args.where);
|
|
1051
|
+
const res = await exec(
|
|
1052
|
+
`MATCH (n:${this.label})${w ? ` WHERE ${w}` : ""} DETACH DELETE n RETURN count(*) AS c`,
|
|
1053
|
+
ctx.params
|
|
1054
|
+
);
|
|
1055
|
+
return { count: toCount(res[0]?.c) };
|
|
1056
|
+
});
|
|
1057
|
+
}
|
|
1058
|
+
};
|
|
1059
|
+
|
|
1060
|
+
// src/orm/client.ts
|
|
1061
|
+
function delegateKey(name) {
|
|
1062
|
+
return name.charAt(0).toLowerCase() + name.slice(1);
|
|
1063
|
+
}
|
|
1064
|
+
function txExecutor(tx, debug) {
|
|
1065
|
+
return async (text, params) => {
|
|
1066
|
+
if (debug) console.debug("[cyphra] cypher:", text, "param keys:", Object.keys(params));
|
|
1067
|
+
const res = await tx.run(text, params);
|
|
1068
|
+
return res.records.map((r) => r.toObject());
|
|
1069
|
+
};
|
|
1070
|
+
}
|
|
1071
|
+
function buildDelegates(schema, runner) {
|
|
1072
|
+
const out = {};
|
|
1073
|
+
for (const node of schema.nodes) {
|
|
1074
|
+
const key = delegateKey(node.name);
|
|
1075
|
+
if (key.startsWith("$")) throw new Error(`Model name "${node.name}" is reserved.`);
|
|
1076
|
+
out[key] = new ModelEngine(schema, node, runner);
|
|
1077
|
+
}
|
|
1078
|
+
return out;
|
|
1079
|
+
}
|
|
1080
|
+
function rawFor(runner) {
|
|
1081
|
+
return async (strings, ...values) => {
|
|
1082
|
+
const { text, params } = compileCypher2(strings, values);
|
|
1083
|
+
const rows = await runner.write((exec) => exec(text, params));
|
|
1084
|
+
return rows.map((r) => toNative(r));
|
|
1085
|
+
};
|
|
1086
|
+
}
|
|
1087
|
+
function createOrm(schema, options) {
|
|
1088
|
+
const owns = !("client" in options);
|
|
1089
|
+
const client = "client" in options ? options.client : new CyphraClient(options);
|
|
1090
|
+
const debug = options.debug ?? false;
|
|
1091
|
+
const runner = {
|
|
1092
|
+
read: (fn) => client.withReadTransaction((tx) => fn(txExecutor(tx, debug))),
|
|
1093
|
+
write: (fn) => client.withWriteTransaction((tx) => fn(txExecutor(tx, debug)))
|
|
1094
|
+
};
|
|
1095
|
+
const transaction = (fn) => client.withWriteTransaction((tx) => {
|
|
1096
|
+
const exec = txExecutor(tx, debug);
|
|
1097
|
+
const inTx = { read: (f) => f(exec), write: (f) => f(exec) };
|
|
1098
|
+
const txClient = { ...buildDelegates(schema, inTx), $cypher: rawFor(inTx) };
|
|
1099
|
+
return fn(txClient);
|
|
1100
|
+
});
|
|
1101
|
+
return {
|
|
1102
|
+
...buildDelegates(schema, runner),
|
|
1103
|
+
$cypher: rawFor(runner),
|
|
1104
|
+
$transaction: transaction,
|
|
1105
|
+
$client: client,
|
|
1106
|
+
$schema: schema,
|
|
1107
|
+
$disconnect: async () => {
|
|
1108
|
+
if (owns) await client.close();
|
|
1109
|
+
}
|
|
1110
|
+
};
|
|
1111
|
+
}
|
|
158
1112
|
export {
|
|
159
1113
|
CyphraClient,
|
|
1114
|
+
CyphraError,
|
|
1115
|
+
CyphraValidationError,
|
|
1116
|
+
NotFoundError,
|
|
1117
|
+
createCuid,
|
|
1118
|
+
createOrm,
|
|
1119
|
+
toNative,
|
|
160
1120
|
toPlainRecord,
|
|
161
1121
|
toPlainRecords
|
|
162
1122
|
};
|