@cyphra/runtime 0.6.0 → 0.8.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 +195 -16
- package/dist/index.js +396 -14
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -211,11 +211,56 @@ function utcDateTime(d) {
|
|
|
211
211
|
0
|
|
212
212
|
);
|
|
213
213
|
}
|
|
214
|
-
|
|
214
|
+
var BIGINT_MIN = -(2n ** 63n);
|
|
215
|
+
var BIGINT_MAX = 2n ** 63n - 1n;
|
|
216
|
+
function encodeBigInt(value, where) {
|
|
217
|
+
let b;
|
|
218
|
+
if (typeof value === "bigint") b = value;
|
|
219
|
+
else if (typeof value === "number" && Number.isSafeInteger(value)) b = BigInt(value);
|
|
220
|
+
else if (isInt(value)) b = BigInt(value.toString());
|
|
221
|
+
if (b === void 0) {
|
|
222
|
+
throw new CyphraValidationError(
|
|
223
|
+
`${where}: expected BigInt (a bigint), got ${describe(value)}.`
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
if (b < BIGINT_MIN || b > BIGINT_MAX) {
|
|
227
|
+
throw new CyphraValidationError(
|
|
228
|
+
`${where}: ${b} is outside the 64-bit integer range (-2^63 to 2^63-1).`
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
return neo4j2.int(b.toString());
|
|
232
|
+
}
|
|
233
|
+
function encodeJson(value, where) {
|
|
234
|
+
let text;
|
|
235
|
+
try {
|
|
236
|
+
text = JSON.stringify(value);
|
|
237
|
+
} catch (e) {
|
|
238
|
+
throw new CyphraValidationError(
|
|
239
|
+
`${where}: value is not JSON-serializable (${e instanceof Error ? e.message : String(e)}).`
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
if (text === void 0) {
|
|
243
|
+
throw new CyphraValidationError(`${where}: expected a JSON value, got ${describe(value)}.`);
|
|
244
|
+
}
|
|
245
|
+
return text;
|
|
246
|
+
}
|
|
247
|
+
function encodeOne(field, value, where) {
|
|
248
|
+
const type = field.type;
|
|
215
249
|
switch (type) {
|
|
216
250
|
case "String":
|
|
217
251
|
if (typeof value !== "string") break;
|
|
218
252
|
return value;
|
|
253
|
+
case "Enum": {
|
|
254
|
+
const values = field.enumValues ?? [];
|
|
255
|
+
if (typeof value === "string" && values.includes(value)) return value;
|
|
256
|
+
throw new CyphraValidationError(
|
|
257
|
+
`${where}: expected one of ${values.map((v) => JSON.stringify(v)).join(", ")} (enum ${field.enum}), got ${typeof value === "string" ? JSON.stringify(value) : describe(value)}.`
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
case "BigInt":
|
|
261
|
+
return encodeBigInt(value, where);
|
|
262
|
+
case "Json":
|
|
263
|
+
return encodeJson(value, where);
|
|
219
264
|
case "Boolean":
|
|
220
265
|
if (typeof value !== "boolean") break;
|
|
221
266
|
return value;
|
|
@@ -239,6 +284,26 @@ function encodeOne(type, value, where) {
|
|
|
239
284
|
}
|
|
240
285
|
throw new CyphraValidationError(`${where}: expected ${type}, got ${describe(value)}.`);
|
|
241
286
|
}
|
|
287
|
+
function encodeVector(value, dimensions, where) {
|
|
288
|
+
if (!Array.isArray(value) && !ArrayBuffer.isView(value)) {
|
|
289
|
+
throw new CyphraValidationError(
|
|
290
|
+
`${where}: expected a vector (number[] of length ${dimensions}), got ${describe(value)}.`
|
|
291
|
+
);
|
|
292
|
+
}
|
|
293
|
+
const arr = Array.from(value);
|
|
294
|
+
if (arr.length !== dimensions) {
|
|
295
|
+
throw new CyphraValidationError(
|
|
296
|
+
`${where}: expected a vector of ${dimensions} dimensions, got ${arr.length}.`
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
for (let i = 0; i < arr.length; i++) {
|
|
300
|
+
const x = arr[i];
|
|
301
|
+
if (typeof x !== "number" || !Number.isFinite(x)) {
|
|
302
|
+
throw new CyphraValidationError(`${where}[${i}]: expected a finite number.`);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
return arr;
|
|
306
|
+
}
|
|
242
307
|
function describe(v) {
|
|
243
308
|
if (v === null) return "null";
|
|
244
309
|
if (v instanceof Date) return "Date";
|
|
@@ -253,19 +318,52 @@ function encodeScalar(field, value, owner) {
|
|
|
253
318
|
}
|
|
254
319
|
return null;
|
|
255
320
|
}
|
|
321
|
+
if (field.type === "Vector") return encodeVector(value, field.dimensions ?? 0, where);
|
|
256
322
|
if (field.list) {
|
|
257
323
|
if (!Array.isArray(value)) {
|
|
258
324
|
throw new CyphraValidationError(`${where}: expected an array.`);
|
|
259
325
|
}
|
|
260
|
-
return value.map((v, i) => encodeOne(field
|
|
326
|
+
return value.map((v, i) => encodeOne(field, v, `${where}[${i}]`));
|
|
261
327
|
}
|
|
262
|
-
return encodeOne(field
|
|
328
|
+
return encodeOne(field, value, where);
|
|
329
|
+
}
|
|
330
|
+
function defaultLiteralValue(field, d) {
|
|
331
|
+
if (field.type === "BigInt") return BigInt(d.value);
|
|
332
|
+
if (field.type === "Json") return JSON.parse(String(d.value));
|
|
333
|
+
return d.value;
|
|
263
334
|
}
|
|
264
335
|
function encodeFilterValue(field, value, owner) {
|
|
265
|
-
|
|
336
|
+
if (field.type === "Vector") {
|
|
337
|
+
throw new CyphraValidationError(
|
|
338
|
+
`${owner}.${field.name}: Vector fields can only be filtered on null (use findSimilar to search them).`
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
return encodeOne(field, value, `${owner}.${field.name}`);
|
|
342
|
+
}
|
|
343
|
+
function decodeBigInt(value) {
|
|
344
|
+
if (isInt(value)) return BigInt(value.toString());
|
|
345
|
+
if (typeof value === "number") {
|
|
346
|
+
if (!Number.isSafeInteger(value)) {
|
|
347
|
+
throw new RangeError(
|
|
348
|
+
`Neo4j value ${value} is not an exact 64-bit integer (BigInt overflow?).`
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
return BigInt(value);
|
|
352
|
+
}
|
|
353
|
+
return value;
|
|
354
|
+
}
|
|
355
|
+
function decodeJson(value) {
|
|
356
|
+
if (typeof value !== "string") return toNative(value);
|
|
357
|
+
try {
|
|
358
|
+
return JSON.parse(value);
|
|
359
|
+
} catch {
|
|
360
|
+
return value;
|
|
361
|
+
}
|
|
266
362
|
}
|
|
267
363
|
function decodeOne(type, value) {
|
|
268
364
|
if (value === null || value === void 0) return null;
|
|
365
|
+
if (type === "BigInt") return decodeBigInt(value);
|
|
366
|
+
if (type === "Json") return decodeJson(value);
|
|
269
367
|
if (isInt(value)) {
|
|
270
368
|
return integerToNumber(value);
|
|
271
369
|
}
|
|
@@ -279,6 +377,10 @@ function decodeOne(type, value) {
|
|
|
279
377
|
return value;
|
|
280
378
|
}
|
|
281
379
|
function decodeScalar(field, value) {
|
|
380
|
+
if (field.type === "Vector") {
|
|
381
|
+
if (value === null || value === void 0) return null;
|
|
382
|
+
return Array.from(value, (x) => isInt(x) ? integerToNumber(x) : x);
|
|
383
|
+
}
|
|
282
384
|
if (field.list) {
|
|
283
385
|
if (value === null || value === void 0) return [];
|
|
284
386
|
return value.map((v) => decodeOne(field.type, v));
|
|
@@ -395,8 +497,37 @@ function compileListFilter(ctx, model, field, ref, filter) {
|
|
|
395
497
|
}
|
|
396
498
|
return and(parts);
|
|
397
499
|
}
|
|
500
|
+
function compileVectorFilter(model, field, ref, filter) {
|
|
501
|
+
if (filter === null) return `${ref} IS NULL`;
|
|
502
|
+
const keys = isPlainObject(filter) ? Object.keys(filter).filter((k) => filter[k] !== void 0) : [];
|
|
503
|
+
if (isPlainObject(filter) && keys.every((k) => (k === "equals" || k === "not") && filter[k] === null)) {
|
|
504
|
+
const parts = keys.map((k) => k === "equals" ? `${ref} IS NULL` : `${ref} IS NOT NULL`);
|
|
505
|
+
return and(parts);
|
|
506
|
+
}
|
|
507
|
+
throw new CyphraValidationError(
|
|
508
|
+
`${model.name}.${field.name}: Vector fields can only be filtered on null (null, { equals: null }, { not: null }); use findSimilar to search them.`
|
|
509
|
+
);
|
|
510
|
+
}
|
|
511
|
+
function compileJsonFilter(ctx, model, field, ref, filter) {
|
|
512
|
+
if (filter === null) return `${ref} IS NULL`;
|
|
513
|
+
if (!isPlainObject(filter) || Object.keys(filter).some((k) => k !== "equals" && k !== "not")) {
|
|
514
|
+
throw new CyphraValidationError(
|
|
515
|
+
`${model.name}.${field.name}: Json fields filter with null, { equals } or { not } only.`
|
|
516
|
+
);
|
|
517
|
+
}
|
|
518
|
+
const parts = [];
|
|
519
|
+
for (const [op, v] of Object.entries(filter)) {
|
|
520
|
+
if (v === void 0) continue;
|
|
521
|
+
const value = v === null ? null : ctx.param(encodeFilterValue(field, v, model.name));
|
|
522
|
+
if (op === "equals") parts.push(value === null ? `${ref} IS NULL` : `${ref} = ${value}`);
|
|
523
|
+
else parts.push(value === null ? `${ref} IS NOT NULL` : `${ref} <> ${value}`);
|
|
524
|
+
}
|
|
525
|
+
return and(parts);
|
|
526
|
+
}
|
|
398
527
|
function compileScalarFilter(ctx, model, field, ref, filter, inheritedMode = "default") {
|
|
399
528
|
if (filter === void 0) return null;
|
|
529
|
+
if (field.type === "Vector") return compileVectorFilter(model, field, ref, filter);
|
|
530
|
+
if (field.type === "Json") return compileJsonFilter(ctx, model, field, ref, filter);
|
|
400
531
|
if (field.list) return compileListFilter(ctx, model, field, ref, filter);
|
|
401
532
|
const enc = (v) => encodeFilterValue(field, v, model.name);
|
|
402
533
|
if (filter === null) return `${ref} IS NULL`;
|
|
@@ -557,6 +688,22 @@ function sortDirection(dir, what) {
|
|
|
557
688
|
}
|
|
558
689
|
return dir.toUpperCase();
|
|
559
690
|
}
|
|
691
|
+
function compileRelatedScalar(ctx, model, alias, rel, name) {
|
|
692
|
+
const target = ctx.node(rel.target);
|
|
693
|
+
const f = scalarField(target, name);
|
|
694
|
+
if (!f) {
|
|
695
|
+
throw new CyphraValidationError(
|
|
696
|
+
`orderBy ${model.name}.${rel.name}: unknown scalar field "${target.name}.${name}".`
|
|
697
|
+
);
|
|
698
|
+
}
|
|
699
|
+
if (f.type === "Vector" || f.type === "Json" || f.list) {
|
|
700
|
+
throw new CyphraValidationError(
|
|
701
|
+
`orderBy ${model.name}.${rel.name}.${name}: list, Vector and Json fields cannot be sorted.`
|
|
702
|
+
);
|
|
703
|
+
}
|
|
704
|
+
const m = ctx.variable();
|
|
705
|
+
return `head(COLLECT { MATCH ${relationPattern(ctx, alias, rel, m)} RETURN ${m}.${q(name)} })`;
|
|
706
|
+
}
|
|
560
707
|
function compileOrderBy(ctx, model, alias, orderBy) {
|
|
561
708
|
if (orderBy === void 0 || orderBy === null) return null;
|
|
562
709
|
const list = Array.isArray(orderBy) ? orderBy : [orderBy];
|
|
@@ -566,6 +713,24 @@ function compileOrderBy(ctx, model, alias, orderBy) {
|
|
|
566
713
|
for (const [key, dir] of Object.entries(item)) {
|
|
567
714
|
if (dir === void 0) continue;
|
|
568
715
|
const rel = relationField(model, key);
|
|
716
|
+
if (rel && !rel.many) {
|
|
717
|
+
if (!isPlainObject(dir)) {
|
|
718
|
+
throw new CyphraValidationError(
|
|
719
|
+
`orderBy ${model.name}.${key} takes { <field>: "asc" | "desc" }.`
|
|
720
|
+
);
|
|
721
|
+
}
|
|
722
|
+
for (const [name, d] of Object.entries(dir)) {
|
|
723
|
+
if (d === void 0) continue;
|
|
724
|
+
if (name === "_count") {
|
|
725
|
+
throw new CyphraValidationError(
|
|
726
|
+
`${model.name}.${key} is a to-one relation; only to-many relations can be counted.`
|
|
727
|
+
);
|
|
728
|
+
}
|
|
729
|
+
const expr = compileRelatedScalar(ctx, model, alias, rel, name);
|
|
730
|
+
parts.push(`${expr} ${sortDirection(d, `${model.name}.${key}.${name}`)}`);
|
|
731
|
+
}
|
|
732
|
+
continue;
|
|
733
|
+
}
|
|
569
734
|
if (rel) {
|
|
570
735
|
if (!isPlainObject(dir) || Object.keys(dir).some((k) => k !== "_count")) {
|
|
571
736
|
throw new CyphraValidationError(
|
|
@@ -577,7 +742,12 @@ function compileOrderBy(ctx, model, alias, orderBy) {
|
|
|
577
742
|
parts.push(`${compileRelationCount(ctx, model, alias, rel)} ${d}`);
|
|
578
743
|
continue;
|
|
579
744
|
}
|
|
580
|
-
scalarOrThrow(model, key);
|
|
745
|
+
const sortType = scalarOrThrow(model, key).type;
|
|
746
|
+
if (sortType === "Vector" || sortType === "Json") {
|
|
747
|
+
throw new CyphraValidationError(
|
|
748
|
+
`orderBy ${model.name}.${key}: ${sortType} fields cannot be sorted.`
|
|
749
|
+
);
|
|
750
|
+
}
|
|
581
751
|
parts.push(`${alias}.${q(key)} ${sortDirection(dir, `${model.name}.${key}`)}`);
|
|
582
752
|
}
|
|
583
753
|
}
|
|
@@ -755,8 +925,8 @@ function decodeRow(shape, row) {
|
|
|
755
925
|
import { isInt as isInt2 } from "neo4j-driver";
|
|
756
926
|
var AGGREGATES = ["_count", "_sum", "_avg", "_min", "_max"];
|
|
757
927
|
var AGG_SET = new Set(AGGREGATES);
|
|
758
|
-
var NUMERIC = /* @__PURE__ */ new Set(["Int", "Float"]);
|
|
759
|
-
var ORDERABLE = /* @__PURE__ */ new Set(["Int", "Float", "String", "DateTime", "Date"]);
|
|
928
|
+
var NUMERIC = /* @__PURE__ */ new Set(["Int", "Float", "BigInt"]);
|
|
929
|
+
var ORDERABLE = /* @__PURE__ */ new Set(["Int", "Float", "BigInt", "String", "Enum", "DateTime", "Date"]);
|
|
760
930
|
function isPlainObject2(v) {
|
|
761
931
|
return typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Date);
|
|
762
932
|
}
|
|
@@ -770,7 +940,7 @@ function aggTarget(model, op, name) {
|
|
|
770
940
|
if (op === "_count") return f;
|
|
771
941
|
const ok = !f.list && (op === "_sum" || op === "_avg" ? NUMERIC : ORDERABLE).has(f.type);
|
|
772
942
|
if (!ok) {
|
|
773
|
-
const allowed = op === "_sum" || op === "_avg" ? "Int and
|
|
943
|
+
const allowed = op === "_sum" || op === "_avg" ? "Int, Float and BigInt" : "Int, Float, BigInt, String, enum, DateTime and Date";
|
|
774
944
|
throw new CyphraValidationError(
|
|
775
945
|
`${op} is not valid on ${model.name}.${name} (${f.type}${f.list ? "[]" : ""}); it takes ${allowed} fields.`
|
|
776
946
|
);
|
|
@@ -803,8 +973,9 @@ function decodeAgg(op, target, v) {
|
|
|
803
973
|
function aggResultField(op, target) {
|
|
804
974
|
const base = target === "_all" ? void 0 : target;
|
|
805
975
|
const name = `${base?.name ?? "_all"}.${op}`;
|
|
806
|
-
const type = op === "_count" ? "Int" : op === "
|
|
976
|
+
const type = op === "_count" ? "Int" : op === "_avg" || op === "_sum" && base.type !== "BigInt" ? "Float" : base.type;
|
|
807
977
|
return {
|
|
978
|
+
...op === "_min" || op === "_max" ? base : {},
|
|
808
979
|
kind: "scalar",
|
|
809
980
|
name,
|
|
810
981
|
type,
|
|
@@ -1429,6 +1600,200 @@ function compileShortestPath(ctx, model, args, cap, all) {
|
|
|
1429
1600
|
};
|
|
1430
1601
|
}
|
|
1431
1602
|
|
|
1603
|
+
// src/orm/vector.ts
|
|
1604
|
+
var ARG_KEYS3 = /* @__PURE__ */ new Set([
|
|
1605
|
+
"field",
|
|
1606
|
+
"vector",
|
|
1607
|
+
"k",
|
|
1608
|
+
"where",
|
|
1609
|
+
"select",
|
|
1610
|
+
"include",
|
|
1611
|
+
"minScore",
|
|
1612
|
+
"candidates",
|
|
1613
|
+
"maxCandidates",
|
|
1614
|
+
"exact"
|
|
1615
|
+
]);
|
|
1616
|
+
var CANDIDATE_GROWTH = 4;
|
|
1617
|
+
function positiveInt(v, name, op) {
|
|
1618
|
+
if (typeof v !== "number" || !Number.isInteger(v) || v < 1) {
|
|
1619
|
+
throw new CyphraValidationError(`${op}: ${name} must be a positive integer.`);
|
|
1620
|
+
}
|
|
1621
|
+
return v;
|
|
1622
|
+
}
|
|
1623
|
+
function toScore(v) {
|
|
1624
|
+
return typeof v === "number" ? v : Number(v);
|
|
1625
|
+
}
|
|
1626
|
+
function vectorField(model, name, op) {
|
|
1627
|
+
const indexed = model.fields.filter(
|
|
1628
|
+
(f2) => f2.kind === "scalar" && Boolean(f2.vectorIndex)
|
|
1629
|
+
);
|
|
1630
|
+
if (typeof name !== "string") {
|
|
1631
|
+
throw new CyphraValidationError(
|
|
1632
|
+
`${op}: field is required (${indexed.map((f2) => f2.name).join(", ") || `${model.name} has no @vectorIndex field`}).`
|
|
1633
|
+
);
|
|
1634
|
+
}
|
|
1635
|
+
const f = model.fields.find((x) => x.name === name);
|
|
1636
|
+
if (!f || f.kind !== "scalar" || f.type !== "Vector") {
|
|
1637
|
+
throw new CyphraValidationError(`${op}: ${model.name}.${name} is not a Vector field.`);
|
|
1638
|
+
}
|
|
1639
|
+
if (!f.vectorIndex) {
|
|
1640
|
+
throw new CyphraValidationError(
|
|
1641
|
+
`${op}: ${model.name}.${name} has no @vectorIndex; declare one to search it.`
|
|
1642
|
+
);
|
|
1643
|
+
}
|
|
1644
|
+
return f;
|
|
1645
|
+
}
|
|
1646
|
+
async function findSimilar(exec, ctxFactory, model, args) {
|
|
1647
|
+
const op = `${model.name}.findSimilar`;
|
|
1648
|
+
for (const key of Object.keys(args)) {
|
|
1649
|
+
if (!ARG_KEYS3.has(key)) throw new CyphraValidationError(`${op}: unknown argument "${key}".`);
|
|
1650
|
+
}
|
|
1651
|
+
const field = vectorField(model, args.field, op);
|
|
1652
|
+
const index = field.vectorIndex;
|
|
1653
|
+
const vector = encodeVector(args.vector, field.dimensions ?? 0, `${op} vector`);
|
|
1654
|
+
if (args.k === void 0) throw new CyphraValidationError(`${op}: k is required.`);
|
|
1655
|
+
const k = positiveInt(args.k, "k", op);
|
|
1656
|
+
const minScore = args.minScore;
|
|
1657
|
+
if (minScore !== void 0 && (typeof minScore !== "number" || !Number.isFinite(minScore))) {
|
|
1658
|
+
throw new CyphraValidationError(`${op}: minScore must be a finite number.`);
|
|
1659
|
+
}
|
|
1660
|
+
if (args.exact !== void 0 && typeof args.exact !== "boolean") {
|
|
1661
|
+
throw new CyphraValidationError(`${op}: exact must be a boolean.`);
|
|
1662
|
+
}
|
|
1663
|
+
const ctx = ctxFactory();
|
|
1664
|
+
const where = compileWhere(ctx, model, "n", args.where);
|
|
1665
|
+
const candidates = args.candidates === void 0 ? where ? Math.max(10 * k, 100) : k : positiveInt(args.candidates, "candidates", op);
|
|
1666
|
+
if (candidates < k) {
|
|
1667
|
+
throw new CyphraValidationError(`${op}: candidates must be at least k (${k}).`);
|
|
1668
|
+
}
|
|
1669
|
+
const maxCandidates = args.maxCandidates === void 0 ? Number.POSITIVE_INFINITY : positiveInt(args.maxCandidates, "maxCandidates", op);
|
|
1670
|
+
if (maxCandidates < candidates) {
|
|
1671
|
+
throw new CyphraValidationError(`${op}: maxCandidates must be at least candidates.`);
|
|
1672
|
+
}
|
|
1673
|
+
const prop = q(field.name);
|
|
1674
|
+
const vec = ctx.param(vector);
|
|
1675
|
+
const limit = ctx.param(intParam(k));
|
|
1676
|
+
const scoreOk = minScore === void 0 ? null : `score >= ${ctx.param(minScore)}`;
|
|
1677
|
+
const { expr, shape } = compileProjection(ctx, model, "n", args);
|
|
1678
|
+
const decode = (rows) => rows.map((r) => ({ ...decodeRow(shape, r.row), $score: toScore(r.score) })).sort((a, b) => b.$score - a.$score).slice(0, k);
|
|
1679
|
+
if (args.exact === true) {
|
|
1680
|
+
const fn = index.similarity === "euclidean" ? "vector.similarity.euclidean" : "vector.similarity.cosine";
|
|
1681
|
+
const filters = [
|
|
1682
|
+
`n.${prop} IS NOT NULL`,
|
|
1683
|
+
`size(n.${prop}) = ${ctx.param(intParam(vector.length))}`
|
|
1684
|
+
];
|
|
1685
|
+
if (where) filters.push(`(${where})`);
|
|
1686
|
+
let text2 = `MATCH (n:${q(model.label)}) WHERE ${filters.join(" AND ")}`;
|
|
1687
|
+
text2 += ` WITH n, ${fn}(n.${prop}, ${vec}) AS score`;
|
|
1688
|
+
if (scoreOk) text2 += ` WHERE ${scoreOk}`;
|
|
1689
|
+
text2 += ` WITH n, score ORDER BY score DESC LIMIT ${limit}`;
|
|
1690
|
+
text2 += ` RETURN ${expr} AS row, score ORDER BY score DESC`;
|
|
1691
|
+
const rows = await exec(text2, ctx.params);
|
|
1692
|
+
return decode(rows);
|
|
1693
|
+
}
|
|
1694
|
+
const name = ctx.param(index.name);
|
|
1695
|
+
const call = (count2) => `CALL db.index.vector.queryNodes(${name}, ${count2}, ${vec}) YIELD node, score`;
|
|
1696
|
+
if (!where) {
|
|
1697
|
+
let text2 = `${call(ctx.param(intParam(candidates)))} WITH node AS n, score`;
|
|
1698
|
+
if (scoreOk) text2 += ` WHERE ${scoreOk}`;
|
|
1699
|
+
text2 += ` WITH n, score ORDER BY score DESC LIMIT ${limit}`;
|
|
1700
|
+
text2 += ` RETURN ${expr} AS row, score ORDER BY score DESC`;
|
|
1701
|
+
const rows = await exec(text2, ctx.params);
|
|
1702
|
+
return decode(rows);
|
|
1703
|
+
}
|
|
1704
|
+
const count = "$cyphraCandidates";
|
|
1705
|
+
const filter = [scoreOk, where].filter(Boolean).join(" AND ");
|
|
1706
|
+
const text = `${call(count)} WITH collect({n: node, s: score}) AS hits CALL { WITH hits UNWIND hits AS h WITH h.n AS n, h.s AS score WHERE ${filter} WITH n, score ORDER BY score DESC LIMIT ${limit} RETURN collect({row: ${expr}, score: score}) AS rows } RETURN size(hits) AS fetched, hits[-1].s AS lowest, rows`;
|
|
1707
|
+
let asked = Math.min(candidates, maxCandidates);
|
|
1708
|
+
for (; ; ) {
|
|
1709
|
+
const [res] = await exec(text, { ...ctx.params, cyphraCandidates: intParam(asked) });
|
|
1710
|
+
const rows = res?.rows ?? [];
|
|
1711
|
+
const fetched = decodeCount(res?.fetched);
|
|
1712
|
+
const lowest = res?.lowest;
|
|
1713
|
+
const exhausted = fetched < asked || asked >= maxCandidates || minScore !== void 0 && lowest !== null && lowest !== void 0 && toScore(lowest) < minScore;
|
|
1714
|
+
if (rows.length >= k || exhausted) return decode(rows);
|
|
1715
|
+
asked = Math.min(asked * CANDIDATE_GROWTH, maxCandidates);
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
|
|
1719
|
+
// src/orm/fulltext.ts
|
|
1720
|
+
var ARG_KEYS4 = /* @__PURE__ */ new Set([
|
|
1721
|
+
"index",
|
|
1722
|
+
"query",
|
|
1723
|
+
"mode",
|
|
1724
|
+
"where",
|
|
1725
|
+
"minScore",
|
|
1726
|
+
"skip",
|
|
1727
|
+
"take",
|
|
1728
|
+
"select",
|
|
1729
|
+
"include"
|
|
1730
|
+
]);
|
|
1731
|
+
var MODES = ["lucene", "terms", "phrase"];
|
|
1732
|
+
var LUCENE_SPECIAL = /[+\-&|!(){}[\]^"~*?:\\/]/g;
|
|
1733
|
+
var LUCENE_OPERATORS = /\b(AND|OR|NOT)\b/g;
|
|
1734
|
+
function escapeLucene(text) {
|
|
1735
|
+
return text.replace(LUCENE_SPECIAL, "\\$&").replace(LUCENE_OPERATORS, "\\$1");
|
|
1736
|
+
}
|
|
1737
|
+
function luceneQuery(query, mode) {
|
|
1738
|
+
if (mode === "terms") return escapeLucene(query);
|
|
1739
|
+
if (mode === "phrase") return `"${escapeLucene(query)}"`;
|
|
1740
|
+
return query;
|
|
1741
|
+
}
|
|
1742
|
+
async function search(exec, ctxFactory, model, args) {
|
|
1743
|
+
const op = `${model.name}.search`;
|
|
1744
|
+
for (const key of Object.keys(args)) {
|
|
1745
|
+
if (!ARG_KEYS4.has(key)) throw new CyphraValidationError(`${op}: unknown argument "${key}".`);
|
|
1746
|
+
}
|
|
1747
|
+
const indexes = model.fulltextIndexes ?? [];
|
|
1748
|
+
const names = indexes.map((i) => i.name);
|
|
1749
|
+
if (typeof args.index !== "string") {
|
|
1750
|
+
throw new CyphraValidationError(
|
|
1751
|
+
`${op}: index is required (${names.join(", ") || `${model.name} has no @@fulltext index`}).`
|
|
1752
|
+
);
|
|
1753
|
+
}
|
|
1754
|
+
if (!names.includes(args.index)) {
|
|
1755
|
+
throw new CyphraValidationError(
|
|
1756
|
+
`${op}: ${JSON.stringify(args.index)} is not a full-text index of ${model.name} (${names.join(", ") || "declare one with @@fulltext"}).`
|
|
1757
|
+
);
|
|
1758
|
+
}
|
|
1759
|
+
if (typeof args.query !== "string") {
|
|
1760
|
+
throw new CyphraValidationError(`${op}: query must be a string.`);
|
|
1761
|
+
}
|
|
1762
|
+
const mode = args.mode ?? "lucene";
|
|
1763
|
+
if (!MODES.includes(mode)) {
|
|
1764
|
+
throw new CyphraValidationError(`${op}: mode must be ${MODES.join(", ")}.`);
|
|
1765
|
+
}
|
|
1766
|
+
const minScore = args.minScore;
|
|
1767
|
+
if (minScore !== void 0 && (typeof minScore !== "number" || !Number.isFinite(minScore))) {
|
|
1768
|
+
throw new CyphraValidationError(`${op}: minScore must be a finite number.`);
|
|
1769
|
+
}
|
|
1770
|
+
const skip = args.skip === void 0 ? void 0 : nonNegativeInt(args.skip, `${op}: skip`);
|
|
1771
|
+
const take = args.take === void 0 ? void 0 : nonNegativeInt(args.take, `${op}: take`);
|
|
1772
|
+
const ctx = ctxFactory();
|
|
1773
|
+
const where = compileWhere(ctx, model, "n", args.where);
|
|
1774
|
+
const { expr, shape } = compileProjection(ctx, model, "n", args);
|
|
1775
|
+
if (args.query.trim() === "" || take === 0) return [];
|
|
1776
|
+
const name = ctx.param(args.index);
|
|
1777
|
+
const query = ctx.param(luceneQuery(args.query, mode));
|
|
1778
|
+
const filters = [
|
|
1779
|
+
...minScore === void 0 ? [] : [`score >= ${ctx.param(minScore)}`],
|
|
1780
|
+
...where ? [`(${where})`] : []
|
|
1781
|
+
];
|
|
1782
|
+
const options = filters.length === 0 && take !== void 0 ? `, {limit: ${ctx.param(intParam((skip ?? 0) + take))}}` : "";
|
|
1783
|
+
let text = `CALL db.index.fulltext.queryNodes(${name}, ${query}${options}) YIELD node, score`;
|
|
1784
|
+
text += " WITH node AS n, score";
|
|
1785
|
+
if (filters.length) text += ` WHERE ${filters.join(" AND ")}`;
|
|
1786
|
+
text += " WITH n, score ORDER BY score DESC";
|
|
1787
|
+
if (skip !== void 0) text += ` SKIP ${ctx.param(intParam(skip))}`;
|
|
1788
|
+
if (take !== void 0) text += ` LIMIT ${ctx.param(intParam(take))}`;
|
|
1789
|
+
text += ` RETURN ${expr} AS row, score ORDER BY score DESC`;
|
|
1790
|
+
const rows = await exec(text, ctx.params);
|
|
1791
|
+
return rows.map((r) => ({
|
|
1792
|
+
...decodeRow(shape, r.row),
|
|
1793
|
+
$score: typeof r.score === "number" ? r.score : Number(r.score)
|
|
1794
|
+
}));
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1432
1797
|
// src/orm/engine.ts
|
|
1433
1798
|
function isPlainObject5(v) {
|
|
1434
1799
|
return typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Date);
|
|
@@ -1593,6 +1958,21 @@ var ModelEngine = class _ModelEngine {
|
|
|
1593
1958
|
return c.decode(await exec(c.text, c.params));
|
|
1594
1959
|
});
|
|
1595
1960
|
}
|
|
1961
|
+
/** Nearest neighbours on a `@vectorIndex` field; see {@link findSimilar}. */
|
|
1962
|
+
findSimilar(args) {
|
|
1963
|
+
return this.runner.read(async (exec) => {
|
|
1964
|
+
if (!isPlainObject5(args))
|
|
1965
|
+
throw new CyphraValidationError("findSimilar args must be an object.");
|
|
1966
|
+
return findSimilar(exec, () => this.ctx(), this.model, args);
|
|
1967
|
+
});
|
|
1968
|
+
}
|
|
1969
|
+
/** Full-text search through a `@@fulltext` index; see {@link search}. */
|
|
1970
|
+
search(args) {
|
|
1971
|
+
return this.runner.read(async (exec) => {
|
|
1972
|
+
if (!isPlainObject5(args)) throw new CyphraValidationError("search args must be an object.");
|
|
1973
|
+
return search(exec, () => this.ctx(), this.model, args);
|
|
1974
|
+
});
|
|
1975
|
+
}
|
|
1596
1976
|
// -------------------------------------------------------------------------
|
|
1597
1977
|
// Write helpers
|
|
1598
1978
|
// -------------------------------------------------------------------------
|
|
@@ -1616,7 +1996,7 @@ var ModelEngine = class _ModelEngine {
|
|
|
1616
1996
|
}
|
|
1617
1997
|
if (v === void 0 && f.default) {
|
|
1618
1998
|
const d = f.default;
|
|
1619
|
-
const value = d.kind === "literal" ? d
|
|
1999
|
+
const value = d.kind === "literal" ? defaultLiteralValue(f, d) : d.fn === "uuid" ? randomUUID() : d.fn === "cuid" ? createCuid() : /* @__PURE__ */ new Date();
|
|
1620
2000
|
props[f.name] = encodeScalar(f, value, owner);
|
|
1621
2001
|
continue;
|
|
1622
2002
|
}
|
|
@@ -1828,8 +2208,8 @@ var ModelEngine = class _ModelEngine {
|
|
|
1828
2208
|
for (const [k, v] of Object.entries(scalars)) {
|
|
1829
2209
|
const f = scalarField(this.model, k);
|
|
1830
2210
|
const ref = `n.${q(k)}`;
|
|
1831
|
-
if (isPlainObject5(v) && !f.list) {
|
|
1832
|
-
if (f.type !== "Int" && f.type !== "Float") {
|
|
2211
|
+
if (isPlainObject5(v) && !f.list && f.type !== "Json") {
|
|
2212
|
+
if (f.type !== "Int" && f.type !== "Float" && f.type !== "BigInt") {
|
|
1833
2213
|
throw new CyphraValidationError(
|
|
1834
2214
|
`${this.model.name}.${k}: object updates are only for numbers.`
|
|
1835
2215
|
);
|
|
@@ -1871,7 +2251,8 @@ var ModelEngine = class _ModelEngine {
|
|
|
1871
2251
|
return this.readById(exec, id, args);
|
|
1872
2252
|
});
|
|
1873
2253
|
}
|
|
1874
|
-
|
|
2254
|
+
// `async` so that invalid data rejects the returned promise instead of throwing synchronously.
|
|
2255
|
+
async createMany(args) {
|
|
1875
2256
|
if (!Array.isArray(args.data))
|
|
1876
2257
|
throw new CyphraValidationError("createMany: data must be an array.");
|
|
1877
2258
|
const fields = this.model.fields.filter((f) => f.kind === "scalar");
|
|
@@ -1882,7 +2263,7 @@ var ModelEngine = class _ModelEngine {
|
|
|
1882
2263
|
}
|
|
1883
2264
|
return _ModelEngine.createProps(this.model.name, fields, scalars);
|
|
1884
2265
|
});
|
|
1885
|
-
if (rows.length === 0) return
|
|
2266
|
+
if (rows.length === 0) return { count: 0 };
|
|
1886
2267
|
return this.runner.write(async (exec) => {
|
|
1887
2268
|
const ctx = this.ctx();
|
|
1888
2269
|
const res = await exec(
|
|
@@ -2082,6 +2463,7 @@ export {
|
|
|
2082
2463
|
NotFoundError,
|
|
2083
2464
|
createCuid,
|
|
2084
2465
|
createOrm,
|
|
2466
|
+
escapeLucene,
|
|
2085
2467
|
toNative,
|
|
2086
2468
|
toPlainRecord,
|
|
2087
2469
|
toPlainRecords
|