@cyphra/runtime 0.3.0 → 0.5.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.js CHANGED
@@ -15,14 +15,21 @@ async function toPlainRecord(result) {
15
15
  // src/client.ts
16
16
  var CyphraClient = class {
17
17
  driver;
18
+ ownsDriver;
18
19
  database;
19
20
  debug;
20
21
  constructor(opts) {
21
- this.driver = neo4j.driver(
22
- opts.uri,
23
- neo4j.auth.basic(opts.user, opts.password),
24
- opts.driverConfig
25
- );
22
+ if (opts.driver) {
23
+ this.driver = opts.driver;
24
+ this.ownsDriver = false;
25
+ } else {
26
+ this.driver = neo4j.driver(
27
+ opts.uri,
28
+ neo4j.auth.basic(opts.user, opts.password),
29
+ opts.driverConfig
30
+ );
31
+ this.ownsDriver = true;
32
+ }
26
33
  this.database = opts.database;
27
34
  this.debug = opts.debug ?? false;
28
35
  }
@@ -150,9 +157,12 @@ var CyphraClient = class {
150
157
  await session.close();
151
158
  }
152
159
  }
153
- /** Close the driver (call on shutdown). */
160
+ /**
161
+ * Close the driver (call on shutdown). A driver passed in with `{ driver }` is left open: its
162
+ * owner closes it.
163
+ */
154
164
  async close() {
155
- await this.driver.close();
165
+ if (this.ownsDriver) await this.driver.close();
156
166
  }
157
167
  };
158
168
 
@@ -161,7 +171,7 @@ import { compileCypher as compileCypher2 } from "@cyphra/query";
161
171
 
162
172
  // src/orm/engine.ts
163
173
  import { randomUUID, getRandomValues } from "crypto";
164
- import { isInt as isInt2 } from "neo4j-driver";
174
+ import { isInt as isInt3 } from "neo4j-driver";
165
175
 
166
176
  // src/orm/compile.ts
167
177
  import neo4j3 from "neo4j-driver";
@@ -350,7 +360,8 @@ var SCALAR_OPS = /* @__PURE__ */ new Set([
350
360
  "gte",
351
361
  "contains",
352
362
  "startsWith",
353
- "endsWith"
363
+ "endsWith",
364
+ "mode"
354
365
  ]);
355
366
  var LIST_OPS = /* @__PURE__ */ new Set(["has", "hasEvery", "hasSome", "isEmpty", "equals"]);
356
367
  function and(parts) {
@@ -381,34 +392,49 @@ function compileListFilter(ctx, model, field, ref, filter) {
381
392
  }
382
393
  return and(parts);
383
394
  }
384
- function compileScalarFilter(ctx, model, field, ref, filter) {
395
+ function compileScalarFilter(ctx, model, field, ref, filter, inheritedMode = "default") {
385
396
  if (filter === void 0) return null;
386
397
  if (field.list) return compileListFilter(ctx, model, field, ref, filter);
387
398
  const enc = (v) => encodeFilterValue(field, v, model.name);
388
399
  if (filter === null) return `${ref} IS NULL`;
389
400
  if (!isPlainObject(filter)) return `${ref} = ${ctx.param(enc(filter))}`;
401
+ const mode = filter.mode ?? inheritedMode;
402
+ if (mode !== "default" && mode !== "insensitive") {
403
+ throw new CyphraValidationError(
404
+ `${model.name}.${field.name}: mode must be "default" or "insensitive".`
405
+ );
406
+ }
407
+ if (mode === "insensitive" && field.type !== "String") {
408
+ throw new CyphraValidationError(
409
+ `${model.name}.${field.name}: mode "insensitive" is only valid on String fields.`
410
+ );
411
+ }
412
+ const insensitive = mode === "insensitive";
413
+ const lhs = insensitive ? `toLower(${ref})` : ref;
414
+ const fold = (v) => insensitive && typeof v === "string" ? v.toLowerCase() : v;
415
+ const encFold = (v) => fold(enc(v));
390
416
  const parts = [];
391
417
  for (const [op, v] of Object.entries(filter)) {
392
- if (v === void 0) continue;
418
+ if (v === void 0 || op === "mode") continue;
393
419
  if (!SCALAR_OPS.has(op)) {
394
420
  throw new CyphraValidationError(`Unknown filter "${op}" on ${model.name}.${field.name}.`);
395
421
  }
396
422
  switch (op) {
397
423
  case "equals":
398
- parts.push(v === null ? `${ref} IS NULL` : `${ref} = ${ctx.param(enc(v))}`);
424
+ parts.push(v === null ? `${ref} IS NULL` : `${lhs} = ${ctx.param(encFold(v))}`);
399
425
  break;
400
426
  case "not":
401
427
  if (v === null) parts.push(`${ref} IS NOT NULL`);
402
428
  else if (isPlainObject(v)) {
403
- const inner = compileScalarFilter(ctx, model, field, ref, v);
429
+ const inner = compileScalarFilter(ctx, model, field, ref, v, mode);
404
430
  if (inner) parts.push(`NOT (${inner})`);
405
- } else parts.push(`${ref} <> ${ctx.param(enc(v))}`);
431
+ } else parts.push(`${lhs} <> ${ctx.param(encFold(v))}`);
406
432
  break;
407
433
  case "in":
408
434
  case "notIn": {
409
435
  if (!Array.isArray(v)) throw new CyphraValidationError(`${op} expects an array.`);
410
- const p = ctx.param(v.map(enc));
411
- parts.push(op === "in" ? `${ref} IN ${p}` : `NOT ${ref} IN ${p}`);
436
+ const p = ctx.param(v.map(encFold));
437
+ parts.push(op === "in" ? `${lhs} IN ${p}` : `NOT ${lhs} IN ${p}`);
412
438
  break;
413
439
  }
414
440
  case "lt":
@@ -426,7 +452,7 @@ function compileScalarFilter(ctx, model, field, ref, filter) {
426
452
  throw new CyphraValidationError(`${op} is only valid on String fields.`);
427
453
  }
428
454
  const kw = { contains: "CONTAINS", startsWith: "STARTS WITH", endsWith: "ENDS WITH" }[op];
429
- parts.push(`${ref} ${kw} ${ctx.param(v)}`);
455
+ parts.push(`${lhs} ${kw} ${ctx.param(fold(v))}`);
430
456
  break;
431
457
  }
432
458
  }
@@ -637,12 +663,389 @@ function decodeRow(shape, row) {
637
663
  return out;
638
664
  }
639
665
 
640
- // src/orm/engine.ts
666
+ // src/orm/aggregate.ts
667
+ import { isInt as isInt2 } from "neo4j-driver";
668
+ var AGGREGATES = ["_count", "_sum", "_avg", "_min", "_max"];
669
+ var AGG_SET = new Set(AGGREGATES);
670
+ var NUMERIC = /* @__PURE__ */ new Set(["Int", "Float"]);
671
+ var ORDERABLE = /* @__PURE__ */ new Set(["Int", "Float", "String", "DateTime", "Date"]);
641
672
  function isPlainObject2(v) {
642
673
  return typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Date);
643
674
  }
675
+ function aggTarget(model, op, name) {
676
+ if (name === "_all") {
677
+ if (op !== "_count") throw new CyphraValidationError(`${op} does not take "_all".`);
678
+ return "_all";
679
+ }
680
+ const f = scalarField(model, name);
681
+ if (!f) throw new CyphraValidationError(`Unknown scalar field "${model.name}.${name}" in ${op}.`);
682
+ if (op === "_count") return f;
683
+ const ok = !f.list && (op === "_sum" || op === "_avg" ? NUMERIC : ORDERABLE).has(f.type);
684
+ if (!ok) {
685
+ const allowed = op === "_sum" || op === "_avg" ? "Int and Float" : "Int, Float, String, DateTime and Date";
686
+ throw new CyphraValidationError(
687
+ `${op} is not valid on ${model.name}.${name} (${f.type}${f.list ? "[]" : ""}); it takes ${allowed} fields.`
688
+ );
689
+ }
690
+ return f;
691
+ }
692
+ function aggExpr(alias, op, target) {
693
+ if (target === "_all") return `count(${alias})`;
694
+ const ref = `${alias}.${q(target.name)}`;
695
+ switch (op) {
696
+ case "_count":
697
+ return `count(${ref})`;
698
+ // Cypher's sum() is 0 on an empty set; SQL (and Prisma) return null.
699
+ case "_sum":
700
+ return `CASE WHEN count(${ref}) = 0 THEN null ELSE sum(${ref}) END`;
701
+ case "_avg":
702
+ return `avg(${ref})`;
703
+ case "_min":
704
+ return `min(${ref})`;
705
+ case "_max":
706
+ return `max(${ref})`;
707
+ }
708
+ }
709
+ function decodeAgg(op, target, v) {
710
+ if (op === "_count") return isInt2(v) ? integerToNumber(v) : Number(v ?? 0);
711
+ if (v === null || v === void 0) return null;
712
+ if (op === "_avg") return isInt2(v) ? integerToNumber(v) : Number(v);
713
+ return decodeScalar(target, v);
714
+ }
715
+ function aggResultField(op, target) {
716
+ const base = target === "_all" ? void 0 : target;
717
+ const name = `${base?.name ?? "_all"}.${op}`;
718
+ const type = op === "_count" ? "Int" : op === "_sum" || op === "_avg" ? "Float" : base.type;
719
+ return {
720
+ kind: "scalar",
721
+ name,
722
+ type,
723
+ optional: op !== "_count",
724
+ list: false,
725
+ id: false,
726
+ unique: false,
727
+ index: false
728
+ };
729
+ }
730
+ var AggColumns = class {
731
+ constructor(ctx, alias) {
732
+ this.ctx = ctx;
733
+ this.alias = alias;
734
+ }
735
+ ctx;
736
+ alias;
737
+ columns = [];
738
+ aliases = [];
739
+ byExpr = /* @__PURE__ */ new Map();
740
+ add(op, target) {
741
+ const expr = aggExpr(this.alias, op, target);
742
+ let v = this.byExpr.get(expr);
743
+ if (!v) {
744
+ v = this.ctx.variable("a");
745
+ this.byExpr.set(expr, v);
746
+ this.columns.push(`${expr} AS ${v}`);
747
+ this.aliases.push(v);
748
+ }
749
+ return v;
750
+ }
751
+ };
752
+ function asFlag(v, where) {
753
+ if (v === void 0 || v === false) return false;
754
+ if (v === true) return true;
755
+ throw new CyphraValidationError(`${where} must be true or false.`);
756
+ }
757
+ function compileSelection(model, args, cols) {
758
+ const out = [];
759
+ for (const op of AGGREGATES) {
760
+ const spec = args[op];
761
+ if (spec === void 0 || spec === false) continue;
762
+ if (op === "_count" && spec === true) {
763
+ out.push({ op, key: null, target: "_all", column: cols.add(op, "_all") });
764
+ continue;
765
+ }
766
+ if (!isPlainObject2(spec)) {
767
+ throw new CyphraValidationError(
768
+ `${op} must be an object of fields${op === "_count" ? " or true" : ""}.`
769
+ );
770
+ }
771
+ for (const [name, flag] of Object.entries(spec)) {
772
+ if (!asFlag(flag, `${op}.${name}`)) continue;
773
+ const target = aggTarget(model, op, name);
774
+ out.push({ op, key: name, target, column: cols.add(op, target) });
775
+ }
776
+ if (out.every((o) => o.op !== op)) {
777
+ out.push({ op, key: "", target: "_all", column: "" });
778
+ }
779
+ }
780
+ return out;
781
+ }
782
+ function decodeSelection(outputs, row, into) {
783
+ for (const o of outputs) {
784
+ if (o.key === null) {
785
+ into[o.op] = decodeAgg(o.op, o.target, row[o.column]);
786
+ continue;
787
+ }
788
+ const bucket = into[o.op] ??= {};
789
+ if (o.key !== "") bucket[o.key] = decodeAgg(o.op, o.target, row[o.column]);
790
+ }
791
+ }
792
+ function compileAggregate(ctx, model, args) {
793
+ checkKeys(args, ["where", "orderBy", "skip", "take", ...AGGREGATES], "aggregate");
794
+ const whereClause = compileWhere(ctx, model, "n", args.where);
795
+ const cols = new AggColumns(ctx, "n");
796
+ const outputs = compileSelection(model, args, cols);
797
+ const paging = compilePaging(ctx, model, "n", args);
798
+ let text = `MATCH (n:${q(model.label)})`;
799
+ if (whereClause) text += ` WHERE ${whereClause}`;
800
+ if (paging) text += ` WITH n${paging}`;
801
+ text += ` RETURN ${cols.columns.length ? cols.columns.join(", ") : "count(n) AS _"}`;
802
+ return {
803
+ text,
804
+ params: ctx.params,
805
+ decode: (rows) => {
806
+ const out = {};
807
+ decodeSelection(outputs, rows[0] ?? {}, out);
808
+ return out;
809
+ }
810
+ };
811
+ }
812
+ function checkKeys(args, allowed, op) {
813
+ for (const k of Object.keys(args)) {
814
+ if (args[k] !== void 0 && !allowed.includes(k)) {
815
+ throw new CyphraValidationError(`Unknown ${op} argument "${k}".`);
816
+ }
817
+ }
818
+ }
819
+ function compileGroupKeys(ctx, model, by) {
820
+ const list = Array.isArray(by) ? by : [by];
821
+ if (list.length === 0 || list.some((x) => typeof x !== "string")) {
822
+ throw new CyphraValidationError(
823
+ "groupBy: by must be a field name or a non-empty array of them."
824
+ );
825
+ }
826
+ const keys = [];
827
+ const related = [];
828
+ const relVars = /* @__PURE__ */ new Map();
829
+ const keyColumns = [];
830
+ for (const path of new Set(list)) {
831
+ const dot = path.indexOf(".");
832
+ const column = ctx.variable("k");
833
+ if (dot === -1) {
834
+ const field2 = scalarField(model, path);
835
+ if (!field2) {
836
+ throw new CyphraValidationError(
837
+ `Unknown scalar field "${model.name}.${path}" in groupBy.by.`
838
+ );
839
+ }
840
+ keys.push({ path, column, field: field2 });
841
+ keyColumns.push(`n.${q(field2.name)} AS ${column}`);
842
+ continue;
843
+ }
844
+ const relName = path.slice(0, dot);
845
+ const fieldName = path.slice(dot + 1);
846
+ const relation = relationField(model, relName);
847
+ if (!relation) {
848
+ throw new CyphraValidationError(`Unknown relation "${model.name}.${relName}" in groupBy.by.`);
849
+ }
850
+ if (relation.many) {
851
+ throw new CyphraValidationError(
852
+ `groupBy.by "${path}": only fields of to-one relations can be grouped by (${model.name}.${relName} is a list).`
853
+ );
854
+ }
855
+ const target = ctx.node(relation.target);
856
+ const field = scalarField(target, fieldName);
857
+ if (!field) {
858
+ throw new CyphraValidationError(
859
+ `Unknown scalar field "${target.name}.${fieldName}" in groupBy.by.`
860
+ );
861
+ }
862
+ let g = relVars.get(relName);
863
+ if (!g) {
864
+ g = ctx.variable("g");
865
+ relVars.set(relName, g);
866
+ const m = ctx.variable();
867
+ related.push(
868
+ `head(COLLECT { MATCH ${relationPattern(ctx, "n", relation, m)} RETURN ${m} }) AS ${g}`
869
+ );
870
+ }
871
+ keys.push({ path, column, field, relation });
872
+ keyColumns.push(`${g}.${q(field.name)} AS ${column}`);
873
+ }
874
+ return { keys, related, keyColumns };
875
+ }
876
+ function keyFor(keys, path, clause) {
877
+ const k = keys.find((x) => x.path === path);
878
+ if (!k) throw new CyphraValidationError(`groupBy ${clause}: "${path}" must be listed in by.`);
879
+ return k;
880
+ }
881
+ function compileHaving(ctx, model, keys, cols, having) {
882
+ if (having === void 0 || having === null) return null;
883
+ if (!isPlainObject2(having)) throw new CyphraValidationError("groupBy having must be an object.");
884
+ const parts = [];
885
+ for (const [key, value] of Object.entries(having)) {
886
+ if (value === void 0) continue;
887
+ if (key === "AND" || key === "OR" || key === "NOT") {
888
+ const list = Array.isArray(value) ? value : [value];
889
+ const compiled = list.map((h) => compileHaving(ctx, model, keys, cols, h)).filter((x) => Boolean(x));
890
+ if (key === "AND") {
891
+ if (compiled.length) parts.push(compiled.map((x) => `(${x})`).join(" AND "));
892
+ } else if (key === "OR") {
893
+ if (list.length === 0) parts.push("false");
894
+ else if (compiled.length === list.length)
895
+ parts.push(compiled.map((x) => `(${x})`).join(" OR "));
896
+ } else for (const c of compiled) parts.push(`NOT (${c})`);
897
+ continue;
898
+ }
899
+ const field = scalarField(model, key);
900
+ if (field) {
901
+ const rest = {};
902
+ let hasRest = !isPlainObject2(value);
903
+ if (isPlainObject2(value)) {
904
+ for (const [op, filter] of Object.entries(value)) {
905
+ if (filter === void 0) continue;
906
+ if (AGG_SET.has(op)) {
907
+ const agg = op;
908
+ const target = aggTarget(model, agg, key);
909
+ const c = compileScalarFilter(
910
+ ctx,
911
+ model,
912
+ aggResultField(agg, target),
913
+ cols.add(agg, target),
914
+ filter
915
+ );
916
+ if (c) parts.push(c);
917
+ } else {
918
+ rest[op] = filter;
919
+ hasRest = true;
920
+ }
921
+ }
922
+ }
923
+ if (hasRest) {
924
+ const k = keyFor(keys, key, "having");
925
+ const c = compileScalarFilter(
926
+ ctx,
927
+ model,
928
+ field,
929
+ k.column,
930
+ isPlainObject2(value) ? rest : value
931
+ );
932
+ if (c) parts.push(c);
933
+ }
934
+ continue;
935
+ }
936
+ const rel = relationField(model, key);
937
+ if (rel && !rel.many) {
938
+ if (!isPlainObject2(value)) {
939
+ throw new CyphraValidationError(
940
+ `groupBy having.${key} must be an object of ${rel.target} fields.`
941
+ );
942
+ }
943
+ const target = ctx.node(rel.target);
944
+ for (const [name, filter] of Object.entries(value)) {
945
+ const k = keyFor(keys, `${key}.${name}`, "having");
946
+ const c = compileScalarFilter(ctx, target, k.field, k.column, filter);
947
+ if (c) parts.push(c);
948
+ }
949
+ continue;
950
+ }
951
+ throw new CyphraValidationError(`Unknown field "${model.name}.${key}" in having.`);
952
+ }
953
+ if (parts.length === 0) return null;
954
+ return parts.length === 1 ? parts[0] : parts.map((x) => `(${x})`).join(" AND ");
955
+ }
956
+ function sortDir(dir, where) {
957
+ if (dir !== "asc" && dir !== "desc") {
958
+ throw new CyphraValidationError(`orderBy ${where} must be "asc" or "desc".`);
959
+ }
960
+ return dir.toUpperCase();
961
+ }
962
+ function compileGroupOrder(model, keys, cols, orderBy) {
963
+ if (orderBy === void 0 || orderBy === null) return null;
964
+ const list = Array.isArray(orderBy) ? orderBy : [orderBy];
965
+ const parts = [];
966
+ for (const item of list) {
967
+ if (!isPlainObject2(item)) throw new CyphraValidationError("orderBy entries must be objects.");
968
+ for (const [key, dir] of Object.entries(item)) {
969
+ if (dir === void 0) continue;
970
+ if (AGG_SET.has(key)) {
971
+ const op = key;
972
+ if (!isPlainObject2(dir)) {
973
+ throw new CyphraValidationError(`orderBy ${op} must be an object of fields.`);
974
+ }
975
+ for (const [name, d] of Object.entries(dir)) {
976
+ if (d === void 0) continue;
977
+ parts.push(`${cols.add(op, aggTarget(model, op, name))} ${sortDir(d, `${op}.${name}`)}`);
978
+ }
979
+ continue;
980
+ }
981
+ if (isPlainObject2(dir)) {
982
+ const rel = relationField(model, key);
983
+ if (!rel || rel.many) {
984
+ throw new CyphraValidationError(
985
+ `Unknown to-one relation "${model.name}.${key}" in orderBy.`
986
+ );
987
+ }
988
+ for (const [name, d] of Object.entries(dir)) {
989
+ if (d === void 0) continue;
990
+ parts.push(
991
+ `${keyFor(keys, `${key}.${name}`, "orderBy").column} ${sortDir(d, `${key}.${name}`)}`
992
+ );
993
+ }
994
+ continue;
995
+ }
996
+ if (!scalarField(model, key)) {
997
+ throw new CyphraValidationError(`Unknown field "${model.name}.${key}" in orderBy.`);
998
+ }
999
+ parts.push(`${keyFor(keys, key, "orderBy").column} ${sortDir(dir, key)}`);
1000
+ }
1001
+ }
1002
+ return parts.length ? parts.join(", ") : null;
1003
+ }
1004
+ function compileGroupBy(ctx, model, args) {
1005
+ checkKeys(args, ["by", "where", "having", "orderBy", "skip", "take", ...AGGREGATES], "groupBy");
1006
+ const whereClause = compileWhere(ctx, model, "n", args.where);
1007
+ const { keys, related, keyColumns } = compileGroupKeys(ctx, model, args.by);
1008
+ const cols = new AggColumns(ctx, "n");
1009
+ const outputs = compileSelection(model, args, cols);
1010
+ const having = compileHaving(ctx, model, keys, cols, args.having);
1011
+ const order = compileGroupOrder(model, keys, cols, args.orderBy);
1012
+ if (cols.columns.length === 0) cols.add("_count", "_all");
1013
+ let text = `MATCH (n:${q(model.label)})`;
1014
+ if (whereClause) text += ` WHERE ${whereClause}`;
1015
+ if (related.length) text += ` WITH n, ${related.join(", ")}`;
1016
+ text += ` WITH ${[...keyColumns, ...cols.columns].join(", ")}`;
1017
+ if (having) text += ` WHERE ${having}`;
1018
+ const returned = [...keys.map((k) => k.column), ...cols.aliases];
1019
+ text += ` RETURN ${returned.join(", ")}`;
1020
+ if (order) text += ` ORDER BY ${order}`;
1021
+ if (args.skip !== void 0)
1022
+ text += ` SKIP ${ctx.param(intParam(nonNegativeInt(args.skip, "skip")))}`;
1023
+ if (args.take !== void 0)
1024
+ text += ` LIMIT ${ctx.param(intParam(nonNegativeInt(args.take, "take")))}`;
1025
+ return {
1026
+ text,
1027
+ params: ctx.params,
1028
+ decode: (rows) => rows.map((row) => {
1029
+ const out = {};
1030
+ for (const k of keys) {
1031
+ const v = decodeScalar(k.field, row[k.column]);
1032
+ if (k.relation) {
1033
+ const bucket = out[k.relation.name] ??= {};
1034
+ bucket[k.field.name] = v;
1035
+ } else out[k.field.name] = v;
1036
+ }
1037
+ decodeSelection(outputs, row, out);
1038
+ return out;
1039
+ })
1040
+ };
1041
+ }
1042
+
1043
+ // src/orm/engine.ts
1044
+ function isPlainObject3(v) {
1045
+ return typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Date);
1046
+ }
644
1047
  function toCount(v) {
645
- return isInt2(v) ? integerToNumber(v) : Number(v ?? 0);
1048
+ return isInt3(v) ? integerToNumber(v) : Number(v ?? 0);
646
1049
  }
647
1050
  var ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
648
1051
  function createCuid() {
@@ -704,9 +1107,9 @@ var ModelEngine = class _ModelEngine {
704
1107
  return decodeRow(shape, rows[0].row);
705
1108
  }
706
1109
  assertUnique(where, op) {
707
- const ok = isPlainObject2(where) && this.model.uniqueFields.some((k) => {
1110
+ const ok = isPlainObject3(where) && this.model.uniqueFields.some((k) => {
708
1111
  const v = where[k];
709
- return v !== void 0 && v !== null && !isPlainObject2(v);
1112
+ return v !== void 0 && v !== null && !isPlainObject3(v);
710
1113
  });
711
1114
  if (!ok) {
712
1115
  throw new CyphraValidationError(
@@ -753,6 +1156,23 @@ var ModelEngine = class _ModelEngine {
753
1156
  return toCount(rows[0]?.c);
754
1157
  });
755
1158
  }
1159
+ /** One statement; see {@link compileAggregate}. */
1160
+ aggregate(args = {}) {
1161
+ return this.runner.read(async (exec) => {
1162
+ if (!isPlainObject3(args))
1163
+ throw new CyphraValidationError("aggregate args must be an object.");
1164
+ const c = compileAggregate(this.ctx(), this.model, args);
1165
+ return c.decode(await exec(c.text, c.params));
1166
+ });
1167
+ }
1168
+ /** One statement; see {@link compileGroupBy}. */
1169
+ groupBy(args) {
1170
+ return this.runner.read(async (exec) => {
1171
+ if (!isPlainObject3(args)) throw new CyphraValidationError("groupBy args must be an object.");
1172
+ const c = compileGroupBy(this.ctx(), this.model, args);
1173
+ return c.decode(await exec(c.text, c.params));
1174
+ });
1175
+ }
756
1176
  // -------------------------------------------------------------------------
757
1177
  // Write helpers
758
1178
  // -------------------------------------------------------------------------
@@ -787,7 +1207,7 @@ var ModelEngine = class _ModelEngine {
787
1207
  return props;
788
1208
  }
789
1209
  splitData(data, op) {
790
- if (!isPlainObject2(data))
1210
+ if (!isPlainObject3(data))
791
1211
  throw new CyphraValidationError(`${this.model.name}.${op}: data must be an object.`);
792
1212
  const scalars = {};
793
1213
  const relations = {};
@@ -811,7 +1231,7 @@ var ModelEngine = class _ModelEngine {
811
1231
  `${this.model.name}.${rel.name}: $edge given but no relationship model types this edge.`
812
1232
  );
813
1233
  }
814
- if (!isPlainObject2(input)) throw new CyphraValidationError("$edge must be an object.");
1234
+ if (!isPlainObject3(input)) throw new CyphraValidationError("$edge must be an object.");
815
1235
  for (const k of Object.keys(input)) {
816
1236
  if (!edgeModel.properties.some((p) => p.name === k)) {
817
1237
  throw new CyphraValidationError(`Unknown edge property "${edgeModel.name}.${k}".`);
@@ -830,7 +1250,7 @@ var ModelEngine = class _ModelEngine {
830
1250
  }
831
1251
  /** Only the `$edge` properties the caller set (no defaults), for updating an existing edge. */
832
1252
  explicitEdgeProps(rel, input) {
833
- if (!rel.edge || !isPlainObject2(input)) return {};
1253
+ if (!rel.edge || !isPlainObject3(input)) return {};
834
1254
  const edgeModel = this.schema.relationships.find((r) => r.name === rel.edge);
835
1255
  const props = {};
836
1256
  for (const f of edgeModel.properties) {
@@ -867,7 +1287,7 @@ var ModelEngine = class _ModelEngine {
867
1287
  * defaults, e.g. `@default(now())`, are kept).
868
1288
  */
869
1289
  async connect(exec, id, rel, item) {
870
- if (!isPlainObject2(item))
1290
+ if (!isPlainObject3(item))
871
1291
  throw new CyphraValidationError(`${rel.name}.connect expects unique where objects.`);
872
1292
  const { $edge, ...where } = item;
873
1293
  const target = this.node(rel.target);
@@ -900,7 +1320,7 @@ var ModelEngine = class _ModelEngine {
900
1320
  }
901
1321
  }
902
1322
  async createRelated(exec, id, rel, item) {
903
- if (!isPlainObject2(item))
1323
+ if (!isPlainObject3(item))
904
1324
  throw new CyphraValidationError(`${rel.name}.create expects objects.`);
905
1325
  const { $edge, ...data } = item;
906
1326
  const props = this.edgeProps(rel, $edge);
@@ -922,7 +1342,7 @@ var ModelEngine = class _ModelEngine {
922
1342
  return toCount(rows[0]?.c);
923
1343
  }
924
1344
  async writeRelation(exec, id, rel, spec, mode) {
925
- if (!isPlainObject2(spec)) {
1345
+ if (!isPlainObject3(spec)) {
926
1346
  throw new CyphraValidationError(
927
1347
  `${this.model.name}.${rel.name}: relation writes take { create, connect, \u2026 }.`
928
1348
  );
@@ -955,7 +1375,7 @@ var ModelEngine = class _ModelEngine {
955
1375
  if (rel.many) {
956
1376
  if (disconnect !== void 0) {
957
1377
  for (const item of asArray(disconnect)) {
958
- if (!isPlainObject2(item))
1378
+ if (!isPlainObject3(item))
959
1379
  throw new CyphraValidationError(`${rel.name}.disconnect expects unique where objects.`);
960
1380
  this.engineFor(this.node(rel.target)).assertUnique(
961
1381
  item,
@@ -988,7 +1408,7 @@ var ModelEngine = class _ModelEngine {
988
1408
  for (const [k, v] of Object.entries(scalars)) {
989
1409
  const f = scalarField(this.model, k);
990
1410
  const ref = `n.${q(k)}`;
991
- if (isPlainObject2(v) && !f.list) {
1411
+ if (isPlainObject3(v) && !f.list) {
992
1412
  if (f.type !== "Int" && f.type !== "Float") {
993
1413
  throw new CyphraValidationError(
994
1414
  `${this.model.name}.${k}: object updates are only for numbers.`
@@ -1095,7 +1515,7 @@ var ModelEngine = class _ModelEngine {
1095
1515
  const where = args.where;
1096
1516
  const key = this.model.uniqueFields.find((k) => {
1097
1517
  const v = where[k];
1098
- return v !== void 0 && v !== null && !isPlainObject2(v);
1518
+ return v !== void 0 && v !== null && !isPlainObject3(v);
1099
1519
  });
1100
1520
  const keyField = scalarField(this.model, key);
1101
1521
  const create = this.splitData(args.create, "upsert create");