@cyphra/graphql 0.0.0-stage → 0.6.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/LICENSE +21 -0
- package/README.md +37 -2
- package/dist/index.d.ts +339 -0
- package/dist/index.js +4292 -0
- package/dist/index.js.map +1 -0
- package/package.json +62 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,4292 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __export = (target, all) => {
|
|
3
|
+
for (var name in all)
|
|
4
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
// src/v7/index.ts
|
|
8
|
+
var v7_exports = {};
|
|
9
|
+
__export(v7_exports, {
|
|
10
|
+
UnsupportedTypeDefsError: () => UnsupportedTypeDefsError,
|
|
11
|
+
buildV7Schema: () => buildV7Schema,
|
|
12
|
+
contextFor: () => contextFor,
|
|
13
|
+
cursorToOffset: () => cursorToOffset,
|
|
14
|
+
cyphraSchema: () => cyphraSchema,
|
|
15
|
+
makeSchema: () => makeSchema,
|
|
16
|
+
offsetToCursor: () => offsetToCursor,
|
|
17
|
+
readTypeDefs: () => readTypeDefs
|
|
18
|
+
});
|
|
19
|
+
import {
|
|
20
|
+
isObjectType
|
|
21
|
+
} from "graphql";
|
|
22
|
+
import { resolveSchema as resolveSchema2 } from "@cyphra/schema";
|
|
23
|
+
|
|
24
|
+
// src/import/convert.ts
|
|
25
|
+
import {
|
|
26
|
+
GraphQLError,
|
|
27
|
+
Kind as Kind2,
|
|
28
|
+
parse,
|
|
29
|
+
print
|
|
30
|
+
} from "graphql";
|
|
31
|
+
|
|
32
|
+
// src/import/mappings.ts
|
|
33
|
+
import { Kind } from "graphql";
|
|
34
|
+
var NOT_YET = "is not supported by Cyphra yet";
|
|
35
|
+
var SCALARS = {
|
|
36
|
+
ID: { type: "String" },
|
|
37
|
+
String: { type: "String" },
|
|
38
|
+
Int: { type: "Int" },
|
|
39
|
+
Float: { type: "Float" },
|
|
40
|
+
Boolean: { type: "Boolean" },
|
|
41
|
+
DateTime: { type: "DateTime" },
|
|
42
|
+
Date: { type: "Date" },
|
|
43
|
+
BigInt: { unsupported: `BigInt ${NOT_YET}` },
|
|
44
|
+
Time: { unsupported: `Time ${NOT_YET}` },
|
|
45
|
+
LocalTime: { unsupported: `LocalTime ${NOT_YET}` },
|
|
46
|
+
LocalDateTime: { unsupported: `LocalDateTime ${NOT_YET}` },
|
|
47
|
+
Duration: { unsupported: `Duration ${NOT_YET}` },
|
|
48
|
+
Point: { unsupported: `Point ${NOT_YET}` },
|
|
49
|
+
CartesianPoint: { unsupported: `CartesianPoint ${NOT_YET}` }
|
|
50
|
+
};
|
|
51
|
+
var ENUM_FIELD = {
|
|
52
|
+
type: "String",
|
|
53
|
+
note: "enums are not supported by Cyphra yet: mapped to String, allowed values are not enforced"
|
|
54
|
+
};
|
|
55
|
+
var CUSTOM_SCALAR_FIELD = {
|
|
56
|
+
unsupported: "custom scalars are not supported by Cyphra"
|
|
57
|
+
};
|
|
58
|
+
var ID = { name: "id", args: [] };
|
|
59
|
+
var UNIQUE = { name: "unique", args: [] };
|
|
60
|
+
function defaultFn(fn) {
|
|
61
|
+
return { name: "default", args: [{ key: "fn", value: { kind: "identifier", value: fn } }] };
|
|
62
|
+
}
|
|
63
|
+
function defaultLiteral(value) {
|
|
64
|
+
const v = typeof value === "string" ? { kind: "string", value } : typeof value === "number" ? { kind: "number", value } : { kind: "boolean", value };
|
|
65
|
+
return { name: "default", args: [{ key: "value", value: v }] };
|
|
66
|
+
}
|
|
67
|
+
function arg(d, name) {
|
|
68
|
+
return d.arguments?.find((a) => a.name.value === name)?.value;
|
|
69
|
+
}
|
|
70
|
+
function stringArg(d, name) {
|
|
71
|
+
const v = arg(d, name);
|
|
72
|
+
return v?.kind === Kind.STRING ? v.value : void 0;
|
|
73
|
+
}
|
|
74
|
+
function enumListArg(d, name) {
|
|
75
|
+
const v = arg(d, name);
|
|
76
|
+
if (!v) return void 0;
|
|
77
|
+
const items = v.kind === Kind.LIST ? v.values : [v];
|
|
78
|
+
return items.flatMap((i) => i.kind === Kind.ENUM || i.kind === Kind.STRING ? [i.value] : []);
|
|
79
|
+
}
|
|
80
|
+
var API_ONLY = "API setting of @neo4j/graphql, no effect on the data model";
|
|
81
|
+
var AUTH = "authorization rules are not part of a Cyphra schema: enforce them in your resolvers or services";
|
|
82
|
+
function issue(severity, feature, message) {
|
|
83
|
+
return { severity, feature, message };
|
|
84
|
+
}
|
|
85
|
+
function defaultFromValue(v, ctx) {
|
|
86
|
+
if (ctx.list) return { error: "Cyphra has no defaults for list fields" };
|
|
87
|
+
switch (ctx.type) {
|
|
88
|
+
case "String":
|
|
89
|
+
if (v.kind === Kind.STRING) return v.value;
|
|
90
|
+
if (ctx.isEnum && v.kind === Kind.ENUM) return v.value;
|
|
91
|
+
break;
|
|
92
|
+
case "Int":
|
|
93
|
+
if (v.kind === Kind.INT) return Number(v.value);
|
|
94
|
+
break;
|
|
95
|
+
case "Float":
|
|
96
|
+
if (v.kind === Kind.INT || v.kind === Kind.FLOAT) return Number(v.value);
|
|
97
|
+
break;
|
|
98
|
+
case "Boolean":
|
|
99
|
+
if (v.kind === Kind.BOOLEAN) return v.value;
|
|
100
|
+
break;
|
|
101
|
+
case "DateTime":
|
|
102
|
+
case "Date":
|
|
103
|
+
return { error: `Cyphra only supports @default(now()) on ${ctx.type} fields` };
|
|
104
|
+
}
|
|
105
|
+
return { error: `the default does not match type ${ctx.graphqlType}` };
|
|
106
|
+
}
|
|
107
|
+
var FIELD_DIRECTIVES = {
|
|
108
|
+
id: {
|
|
109
|
+
kind: "scalar",
|
|
110
|
+
apply: (_d, ctx) => {
|
|
111
|
+
if (ctx.graphqlType !== "ID" || ctx.list) {
|
|
112
|
+
return {
|
|
113
|
+
issues: [
|
|
114
|
+
issue("unsupported", "@id", "@id is only valid on ID fields in v7; not converted")
|
|
115
|
+
]
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
if (ctx.owner === "relationship") {
|
|
119
|
+
return {
|
|
120
|
+
decorators: [defaultFn("uuid")],
|
|
121
|
+
required: true,
|
|
122
|
+
issues: [
|
|
123
|
+
issue(
|
|
124
|
+
"changed",
|
|
125
|
+
"@id",
|
|
126
|
+
"Cyphra has no @id on relationship properties: kept as @default(uuid())"
|
|
127
|
+
)
|
|
128
|
+
]
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
if (ctx.nodeHasId) {
|
|
132
|
+
return {
|
|
133
|
+
decorators: [UNIQUE, defaultFn("uuid")],
|
|
134
|
+
required: true,
|
|
135
|
+
issues: [
|
|
136
|
+
issue(
|
|
137
|
+
"changed",
|
|
138
|
+
"@id",
|
|
139
|
+
"a Cyphra node has one @id: this one became @unique @default(uuid())"
|
|
140
|
+
)
|
|
141
|
+
]
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
return {
|
|
145
|
+
decorators: [ID, defaultFn("uuid")],
|
|
146
|
+
required: true,
|
|
147
|
+
takesId: true,
|
|
148
|
+
issues: [
|
|
149
|
+
issue(
|
|
150
|
+
"changed",
|
|
151
|
+
"@id",
|
|
152
|
+
"became @id @default(uuid()); Cyphra also adds a uniqueness constraint, which v7 @id does not"
|
|
153
|
+
)
|
|
154
|
+
]
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
},
|
|
158
|
+
timestamp: {
|
|
159
|
+
kind: "scalar",
|
|
160
|
+
apply: (d, ctx) => {
|
|
161
|
+
const ops = enumListArg(d, "operations") ?? ["CREATE", "UPDATE"];
|
|
162
|
+
if (ctx.type !== "DateTime" || ctx.list) {
|
|
163
|
+
return {
|
|
164
|
+
issues: [issue("unsupported", "@timestamp", "@timestamp is only converted on DateTime")]
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
if (!ops.includes("CREATE")) {
|
|
168
|
+
return {
|
|
169
|
+
required: false,
|
|
170
|
+
issues: [
|
|
171
|
+
issue(
|
|
172
|
+
"unsupported",
|
|
173
|
+
"@timestamp",
|
|
174
|
+
"update timestamps are not set automatically by Cyphra: field made optional, set it when you update"
|
|
175
|
+
)
|
|
176
|
+
]
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
const issues = ops.includes("UPDATE") ? [
|
|
180
|
+
issue(
|
|
181
|
+
"changed",
|
|
182
|
+
"@timestamp",
|
|
183
|
+
"became @default(now()) (set on create); Cyphra does not refresh it on update, set it when you update"
|
|
184
|
+
)
|
|
185
|
+
] : [];
|
|
186
|
+
return { decorators: [defaultFn("now")], issues };
|
|
187
|
+
}
|
|
188
|
+
},
|
|
189
|
+
default: {
|
|
190
|
+
kind: "scalar",
|
|
191
|
+
apply: (d, ctx) => {
|
|
192
|
+
const v = arg(d, "value");
|
|
193
|
+
const value = v ? defaultFromValue(v, ctx) : { error: "missing value" };
|
|
194
|
+
if (typeof value === "object") {
|
|
195
|
+
return { issues: [issue("unsupported", "@default", `${value.error}; not converted`)] };
|
|
196
|
+
}
|
|
197
|
+
return { decorators: [defaultLiteral(value)] };
|
|
198
|
+
}
|
|
199
|
+
},
|
|
200
|
+
unique: {
|
|
201
|
+
kind: "scalar",
|
|
202
|
+
apply: () => ({
|
|
203
|
+
decorators: [UNIQUE],
|
|
204
|
+
issues: [
|
|
205
|
+
issue(
|
|
206
|
+
"changed",
|
|
207
|
+
"@unique",
|
|
208
|
+
"@unique was removed in @neo4j/graphql v7; Cyphra keeps it and creates the uniqueness constraint"
|
|
209
|
+
)
|
|
210
|
+
]
|
|
211
|
+
})
|
|
212
|
+
},
|
|
213
|
+
relayId: {
|
|
214
|
+
kind: "scalar",
|
|
215
|
+
apply: () => ({
|
|
216
|
+
decorators: [UNIQUE],
|
|
217
|
+
issues: [
|
|
218
|
+
issue(
|
|
219
|
+
"changed",
|
|
220
|
+
"@relayId",
|
|
221
|
+
"became @unique; Cyphra has no Relay global IDs (the field keeps its plain value)"
|
|
222
|
+
)
|
|
223
|
+
]
|
|
224
|
+
})
|
|
225
|
+
},
|
|
226
|
+
alias: {
|
|
227
|
+
kind: "scalar",
|
|
228
|
+
apply: (d) => {
|
|
229
|
+
const property = stringArg(d, "property");
|
|
230
|
+
if (!property || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(property)) {
|
|
231
|
+
return {
|
|
232
|
+
issues: [
|
|
233
|
+
issue("unsupported", "@alias", "the property name is not an identifier; not renamed")
|
|
234
|
+
]
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
return {
|
|
238
|
+
rename: property,
|
|
239
|
+
issues: [
|
|
240
|
+
issue(
|
|
241
|
+
"changed",
|
|
242
|
+
"@alias",
|
|
243
|
+
`Cyphra field names are the Neo4j property names: renamed to "${property}"`
|
|
244
|
+
)
|
|
245
|
+
]
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
},
|
|
249
|
+
cypher: {
|
|
250
|
+
kind: "drop",
|
|
251
|
+
message: "@cypher fields are computed by a Cypher query: not converted, write it as a query"
|
|
252
|
+
},
|
|
253
|
+
customResolver: {
|
|
254
|
+
kind: "drop",
|
|
255
|
+
message: "@customResolver fields are computed in code: not converted"
|
|
256
|
+
},
|
|
257
|
+
populatedBy: {
|
|
258
|
+
kind: "report",
|
|
259
|
+
severity: "unsupported",
|
|
260
|
+
message: "@populatedBy callbacks are not supported: set the value in your code"
|
|
261
|
+
},
|
|
262
|
+
coalesce: {
|
|
263
|
+
kind: "report",
|
|
264
|
+
severity: "unsupported",
|
|
265
|
+
message: "@coalesce read fallbacks are not supported"
|
|
266
|
+
},
|
|
267
|
+
authentication: { kind: "report", severity: "unsupported", message: AUTH },
|
|
268
|
+
authorization: { kind: "report", severity: "unsupported", message: AUTH },
|
|
269
|
+
subscriptionsAuthorization: { kind: "report", severity: "unsupported", message: AUTH },
|
|
270
|
+
selectable: { kind: "report", severity: "ignored", message: API_ONLY },
|
|
271
|
+
settable: { kind: "report", severity: "ignored", message: API_ONLY },
|
|
272
|
+
filterable: { kind: "report", severity: "ignored", message: API_ONLY },
|
|
273
|
+
sortable: { kind: "report", severity: "ignored", message: API_ONLY },
|
|
274
|
+
private: { kind: "report", severity: "ignored", message: API_ONLY },
|
|
275
|
+
jwtClaim: { kind: "report", severity: "ignored", message: API_ONLY },
|
|
276
|
+
deprecated: { kind: "report", severity: "ignored", message: "GraphQL deprecation, no effect" }
|
|
277
|
+
};
|
|
278
|
+
function reportType(severity, message) {
|
|
279
|
+
return (d) => ({ issues: [issue(severity, `@${d.name.value}`, message)] });
|
|
280
|
+
}
|
|
281
|
+
var TYPE_DIRECTIVES = {
|
|
282
|
+
node: (d, typeName) => {
|
|
283
|
+
const labels2 = enumListArg(d, "labels");
|
|
284
|
+
if (!labels2 || labels2.length === 0) return {};
|
|
285
|
+
const [first, ...rest] = labels2;
|
|
286
|
+
const issues = [];
|
|
287
|
+
let rename;
|
|
288
|
+
if (first !== typeName) {
|
|
289
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(first)) {
|
|
290
|
+
rename = first;
|
|
291
|
+
issues.push(
|
|
292
|
+
issue(
|
|
293
|
+
"changed",
|
|
294
|
+
"@node(labels)",
|
|
295
|
+
`a Cyphra node's name is its label: renamed to "${first}"`
|
|
296
|
+
)
|
|
297
|
+
);
|
|
298
|
+
} else {
|
|
299
|
+
issues.push(
|
|
300
|
+
issue(
|
|
301
|
+
"unsupported",
|
|
302
|
+
"@node(labels)",
|
|
303
|
+
`label "${first}" is not an identifier (dynamic labels are not supported); kept "${typeName}"`
|
|
304
|
+
)
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
if (rest.length > 0) {
|
|
309
|
+
issues.push(
|
|
310
|
+
issue(
|
|
311
|
+
"unsupported",
|
|
312
|
+
"@node(labels)",
|
|
313
|
+
`extra labels ${rest.map((l) => `"${l}"`).join(", ")} are not supported: Cyphra nodes have one label`
|
|
314
|
+
)
|
|
315
|
+
);
|
|
316
|
+
}
|
|
317
|
+
return rename ? { rename, issues } : { issues };
|
|
318
|
+
},
|
|
319
|
+
fulltext: reportType(
|
|
320
|
+
"unsupported",
|
|
321
|
+
"fulltext indexes are not supported: create them in a migration"
|
|
322
|
+
),
|
|
323
|
+
vector: reportType("unsupported", "vector indexes are not supported: create them in a migration"),
|
|
324
|
+
authentication: reportType("unsupported", AUTH),
|
|
325
|
+
authorization: reportType("unsupported", AUTH),
|
|
326
|
+
subscriptionsAuthorization: reportType("unsupported", AUTH),
|
|
327
|
+
plural: reportType("ignored", API_ONLY),
|
|
328
|
+
query: reportType("ignored", API_ONLY),
|
|
329
|
+
mutation: reportType("ignored", API_ONLY),
|
|
330
|
+
subscription: reportType("ignored", API_ONLY),
|
|
331
|
+
limit: reportType("ignored", API_ONLY),
|
|
332
|
+
groupBy: reportType("ignored", API_ONLY),
|
|
333
|
+
deprecated: reportType("ignored", "GraphQL deprecation, no effect")
|
|
334
|
+
};
|
|
335
|
+
var RELATIONSHIP_API_ARGS = ["nestedOperations", "aggregate"];
|
|
336
|
+
|
|
337
|
+
// src/import/convert.ts
|
|
338
|
+
var GraphQLImportError = class extends Error {
|
|
339
|
+
name = "GraphQLImportError";
|
|
340
|
+
};
|
|
341
|
+
var ROOT_TYPES = /* @__PURE__ */ new Set(["Query", "Mutation", "Subscription"]);
|
|
342
|
+
function unwrap(t) {
|
|
343
|
+
let nonNull = false;
|
|
344
|
+
let list2 = false;
|
|
345
|
+
let nested = false;
|
|
346
|
+
let cur = t;
|
|
347
|
+
if (cur.kind === Kind2.NON_NULL_TYPE) {
|
|
348
|
+
nonNull = true;
|
|
349
|
+
cur = cur.type;
|
|
350
|
+
}
|
|
351
|
+
if (cur.kind === Kind2.LIST_TYPE) {
|
|
352
|
+
list2 = true;
|
|
353
|
+
cur = cur.type.kind === Kind2.NON_NULL_TYPE ? cur.type.type : cur.type;
|
|
354
|
+
if (cur.kind === Kind2.LIST_TYPE) nested = true;
|
|
355
|
+
}
|
|
356
|
+
while (cur.kind !== Kind2.NAMED_TYPE) cur = cur.type;
|
|
357
|
+
return { named: cur.name.value, list: list2, nonNull, nested };
|
|
358
|
+
}
|
|
359
|
+
function directive(dirs, name) {
|
|
360
|
+
return dirs?.find((d) => d.name.value === name);
|
|
361
|
+
}
|
|
362
|
+
function kindOf(def) {
|
|
363
|
+
switch (def.kind) {
|
|
364
|
+
case Kind2.OBJECT_TYPE_DEFINITION:
|
|
365
|
+
return { kind: "object", extension: false };
|
|
366
|
+
case Kind2.OBJECT_TYPE_EXTENSION:
|
|
367
|
+
return { kind: "object", extension: true };
|
|
368
|
+
case Kind2.INTERFACE_TYPE_DEFINITION:
|
|
369
|
+
return { kind: "interface", extension: false };
|
|
370
|
+
case Kind2.INTERFACE_TYPE_EXTENSION:
|
|
371
|
+
return { kind: "interface", extension: true };
|
|
372
|
+
case Kind2.UNION_TYPE_DEFINITION:
|
|
373
|
+
return { kind: "union", extension: false };
|
|
374
|
+
case Kind2.UNION_TYPE_EXTENSION:
|
|
375
|
+
return { kind: "union", extension: true };
|
|
376
|
+
case Kind2.ENUM_TYPE_DEFINITION:
|
|
377
|
+
return { kind: "enum", extension: false };
|
|
378
|
+
case Kind2.ENUM_TYPE_EXTENSION:
|
|
379
|
+
return { kind: "enum", extension: true };
|
|
380
|
+
case Kind2.SCALAR_TYPE_DEFINITION:
|
|
381
|
+
return { kind: "scalar", extension: false };
|
|
382
|
+
case Kind2.SCALAR_TYPE_EXTENSION:
|
|
383
|
+
return { kind: "scalar", extension: true };
|
|
384
|
+
case Kind2.INPUT_OBJECT_TYPE_DEFINITION:
|
|
385
|
+
return { kind: "input", extension: false };
|
|
386
|
+
case Kind2.INPUT_OBJECT_TYPE_EXTENSION:
|
|
387
|
+
return { kind: "input", extension: true };
|
|
388
|
+
default:
|
|
389
|
+
return void 0;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
function directivesOf(def) {
|
|
393
|
+
return "directives" in def && def.directives || [];
|
|
394
|
+
}
|
|
395
|
+
function collectTypes(sources) {
|
|
396
|
+
const types = /* @__PURE__ */ new Map();
|
|
397
|
+
const extensions = [];
|
|
398
|
+
for (const src of sources) {
|
|
399
|
+
let doc;
|
|
400
|
+
try {
|
|
401
|
+
doc = parse(src.body);
|
|
402
|
+
} catch (err) {
|
|
403
|
+
if (err instanceof GraphQLError) {
|
|
404
|
+
const loc = err.locations?.[0];
|
|
405
|
+
const where = loc ? `${src.name}:${loc.line}:${loc.column}` : src.name;
|
|
406
|
+
throw new GraphQLImportError(`${where}: ${err.message}`);
|
|
407
|
+
}
|
|
408
|
+
throw err;
|
|
409
|
+
}
|
|
410
|
+
for (const def of doc.definitions) {
|
|
411
|
+
const k = kindOf(def);
|
|
412
|
+
if (!k || !("name" in def) || !def.name) continue;
|
|
413
|
+
const name = def.name.value;
|
|
414
|
+
if (k.extension) {
|
|
415
|
+
extensions.push({ name, def, source: src.name });
|
|
416
|
+
continue;
|
|
417
|
+
}
|
|
418
|
+
if (k.kind === "scalar" && SCALARS[name]) continue;
|
|
419
|
+
if (types.has(name) || SCALARS[name]) {
|
|
420
|
+
throw new GraphQLImportError(`${src.name}: type "${name}" is defined more than once.`);
|
|
421
|
+
}
|
|
422
|
+
types.set(name, {
|
|
423
|
+
name,
|
|
424
|
+
kind: k.kind,
|
|
425
|
+
directives: [...directivesOf(def)],
|
|
426
|
+
fields: [
|
|
427
|
+
...(def.kind === Kind2.OBJECT_TYPE_DEFINITION || def.kind === Kind2.INTERFACE_TYPE_DEFINITION ? def.fields : void 0) ?? []
|
|
428
|
+
],
|
|
429
|
+
source: src.name
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
for (const ext of extensions) {
|
|
434
|
+
const base = types.get(ext.name);
|
|
435
|
+
if (!base) {
|
|
436
|
+
throw new GraphQLImportError(`${ext.source}: cannot extend unknown type "${ext.name}".`);
|
|
437
|
+
}
|
|
438
|
+
const def = ext.def;
|
|
439
|
+
base.directives.push(...directivesOf(def));
|
|
440
|
+
if ((def.kind === Kind2.OBJECT_TYPE_EXTENSION || def.kind === Kind2.INTERFACE_TYPE_EXTENSION) && def.fields) {
|
|
441
|
+
base.fields.push(...def.fields);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
return types;
|
|
445
|
+
}
|
|
446
|
+
function checkReferences(types) {
|
|
447
|
+
for (const t of types.values()) {
|
|
448
|
+
if (t.kind !== "object" && t.kind !== "interface") continue;
|
|
449
|
+
for (const f of t.fields) {
|
|
450
|
+
const { named } = unwrap(f.type);
|
|
451
|
+
if (!types.has(named) && !SCALARS[named]) {
|
|
452
|
+
throw new GraphQLImportError(
|
|
453
|
+
`${t.source}: field "${t.name}.${f.name.value}" has unknown type "${named}".`
|
|
454
|
+
);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
function convertGraphQLTypeDefs(input) {
|
|
460
|
+
const sources = typeof input === "string" ? [{ name: "typeDefs", body: input }] : input;
|
|
461
|
+
const types = collectTypes(sources);
|
|
462
|
+
checkReferences(types);
|
|
463
|
+
const issues = [];
|
|
464
|
+
const report = (at, d) => issues.push({ at, ...d });
|
|
465
|
+
const notes = /* @__PURE__ */ new Map();
|
|
466
|
+
const note = (decl, line) => {
|
|
467
|
+
const list2 = notes.get(decl) ?? [];
|
|
468
|
+
list2.push(line);
|
|
469
|
+
notes.set(decl, list2);
|
|
470
|
+
};
|
|
471
|
+
const nodeTypes = [];
|
|
472
|
+
const propsTypes = /* @__PURE__ */ new Map();
|
|
473
|
+
const nodeName = /* @__PURE__ */ new Map();
|
|
474
|
+
for (const t of types.values()) {
|
|
475
|
+
if (t.kind === "object" && directive(t.directives, "node")) {
|
|
476
|
+
nodeTypes.push(t);
|
|
477
|
+
continue;
|
|
478
|
+
}
|
|
479
|
+
if (t.kind === "object" && directive(t.directives, "relationshipProperties")) {
|
|
480
|
+
propsTypes.set(t.name, t);
|
|
481
|
+
continue;
|
|
482
|
+
}
|
|
483
|
+
switch (t.kind) {
|
|
484
|
+
case "enum":
|
|
485
|
+
if ("unsupported" in ENUM_FIELD) {
|
|
486
|
+
report(t.name, {
|
|
487
|
+
severity: "unsupported",
|
|
488
|
+
feature: "enum",
|
|
489
|
+
message: ENUM_FIELD.unsupported
|
|
490
|
+
});
|
|
491
|
+
} else if (ENUM_FIELD.note) {
|
|
492
|
+
report(t.name, { severity: "changed", feature: "enum", message: ENUM_FIELD.note });
|
|
493
|
+
}
|
|
494
|
+
break;
|
|
495
|
+
case "interface":
|
|
496
|
+
report(t.name, {
|
|
497
|
+
severity: "unsupported",
|
|
498
|
+
feature: "interface",
|
|
499
|
+
message: "interfaces are not supported by Cyphra yet: implementing @node types are converted with their own fields; relationships to the interface are not"
|
|
500
|
+
});
|
|
501
|
+
break;
|
|
502
|
+
case "union":
|
|
503
|
+
report(t.name, {
|
|
504
|
+
severity: "unsupported",
|
|
505
|
+
feature: "union",
|
|
506
|
+
message: "unions are not supported by Cyphra yet: relationships to the union are not converted"
|
|
507
|
+
});
|
|
508
|
+
break;
|
|
509
|
+
case "scalar":
|
|
510
|
+
report(t.name, {
|
|
511
|
+
severity: "unsupported",
|
|
512
|
+
feature: "scalar",
|
|
513
|
+
message: "custom scalars are not supported by Cyphra: fields of this type are not converted"
|
|
514
|
+
});
|
|
515
|
+
break;
|
|
516
|
+
case "input":
|
|
517
|
+
report(t.name, {
|
|
518
|
+
severity: "ignored",
|
|
519
|
+
feature: "input",
|
|
520
|
+
message: "input types are part of the GraphQL API, not the data model"
|
|
521
|
+
});
|
|
522
|
+
break;
|
|
523
|
+
case "object":
|
|
524
|
+
if (ROOT_TYPES.has(t.name)) {
|
|
525
|
+
report(t.name, {
|
|
526
|
+
severity: "unsupported",
|
|
527
|
+
feature: t.name,
|
|
528
|
+
message: `custom ${t.name} fields (@cypher, resolvers) are not converted: write them as Cyphra queries`
|
|
529
|
+
});
|
|
530
|
+
} else if (directive(t.directives, "jwt")) {
|
|
531
|
+
report(t.name, {
|
|
532
|
+
severity: "ignored",
|
|
533
|
+
feature: "@jwt",
|
|
534
|
+
message: "JWT payload type, used by authorization rules only"
|
|
535
|
+
});
|
|
536
|
+
} else {
|
|
537
|
+
report(t.name, {
|
|
538
|
+
severity: "unsupported",
|
|
539
|
+
feature: "@node",
|
|
540
|
+
message: "object type without @node is not a node in v7 (e.g. a @cypher result type): not converted"
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
break;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
const usedNames = new Set(types.keys());
|
|
547
|
+
for (const t of nodeTypes) {
|
|
548
|
+
let name = t.name;
|
|
549
|
+
for (const d of t.directives) {
|
|
550
|
+
const n = d.name.value;
|
|
551
|
+
if (n === "relationshipProperties") {
|
|
552
|
+
report(t.name, {
|
|
553
|
+
severity: "unsupported",
|
|
554
|
+
feature: "@relationshipProperties",
|
|
555
|
+
message: "a type cannot be both @node and @relationshipProperties: kept as a node"
|
|
556
|
+
});
|
|
557
|
+
continue;
|
|
558
|
+
}
|
|
559
|
+
const rule = TYPE_DIRECTIVES[n];
|
|
560
|
+
if (!rule) {
|
|
561
|
+
report(t.name, {
|
|
562
|
+
severity: "unsupported",
|
|
563
|
+
feature: `@${n}`,
|
|
564
|
+
message: `unknown directive @${n}: not converted`
|
|
565
|
+
});
|
|
566
|
+
continue;
|
|
567
|
+
}
|
|
568
|
+
const effect = rule(d, t.name);
|
|
569
|
+
for (const i of effect.issues ?? []) report(t.name, i);
|
|
570
|
+
if (effect.rename && effect.rename !== name) {
|
|
571
|
+
if (usedNames.has(effect.rename) || [...nodeName.values()].includes(effect.rename)) {
|
|
572
|
+
report(t.name, {
|
|
573
|
+
severity: "unsupported",
|
|
574
|
+
feature: "@node(labels)",
|
|
575
|
+
message: `cannot rename to "${effect.rename}": the name is taken; kept "${t.name}"`
|
|
576
|
+
});
|
|
577
|
+
} else {
|
|
578
|
+
name = effect.rename;
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
nodeName.set(t.name, name);
|
|
583
|
+
}
|
|
584
|
+
const usages = [];
|
|
585
|
+
const declarations = [];
|
|
586
|
+
for (const t of nodeTypes) {
|
|
587
|
+
const declName = nodeName.get(t.name);
|
|
588
|
+
const fields = [];
|
|
589
|
+
let hasId = false;
|
|
590
|
+
for (const f of t.fields) {
|
|
591
|
+
const at = `${t.name}.${f.name.value}`;
|
|
592
|
+
const u = unwrap(f.type);
|
|
593
|
+
const target = types.get(u.named);
|
|
594
|
+
const isRelation = Boolean(directive(f.directives, "relationship")) || target !== void 0 && (target.kind === "object" || target.kind === "interface" || target.kind === "union");
|
|
595
|
+
if (dropComputed(f, at, report)) {
|
|
596
|
+
note(declName, skippedLine(f, "computed field"));
|
|
597
|
+
continue;
|
|
598
|
+
}
|
|
599
|
+
if (isRelation) {
|
|
600
|
+
const rel = convertRelation(f, u, at, t.name, types, nodeName, report);
|
|
601
|
+
if (!rel) {
|
|
602
|
+
note(declName, skippedLine(f, "relationship not converted"));
|
|
603
|
+
continue;
|
|
604
|
+
}
|
|
605
|
+
fields.push(rel.field);
|
|
606
|
+
if (rel.usage) usages.push(rel.usage);
|
|
607
|
+
continue;
|
|
608
|
+
}
|
|
609
|
+
const scalar = convertScalar(f, u, at, "node", hasId, types, report);
|
|
610
|
+
if (!scalar) {
|
|
611
|
+
note(declName, skippedLine(f, "type not supported"));
|
|
612
|
+
continue;
|
|
613
|
+
}
|
|
614
|
+
if (scalar.takesId) hasId = true;
|
|
615
|
+
fields.push(scalar.field);
|
|
616
|
+
}
|
|
617
|
+
declarations.push({
|
|
618
|
+
kind: "Node",
|
|
619
|
+
name: declName,
|
|
620
|
+
fields: dedupeNames(fields, t.name, report)
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
const relationships = [];
|
|
624
|
+
const takenTriples = /* @__PURE__ */ new Map();
|
|
625
|
+
const allNames = new Set(declarations.map((d) => d.name));
|
|
626
|
+
for (const props of propsTypes.values()) {
|
|
627
|
+
const triples = [];
|
|
628
|
+
for (const u of usages.filter((x) => x.propsType === props.name)) {
|
|
629
|
+
const key = `${u.relType}|${u.start}|${u.end}`;
|
|
630
|
+
const owner = takenTriples.get(key);
|
|
631
|
+
if (owner && owner !== props.name) {
|
|
632
|
+
report(u.at, {
|
|
633
|
+
severity: "unsupported",
|
|
634
|
+
feature: "@relationship(properties)",
|
|
635
|
+
message: `${u.relType} from ${u.start} to ${u.end} already has properties "${owner}": "${props.name}" not attached`
|
|
636
|
+
});
|
|
637
|
+
continue;
|
|
638
|
+
}
|
|
639
|
+
if (!owner) {
|
|
640
|
+
takenTriples.set(key, props.name);
|
|
641
|
+
triples.push(u);
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
if (triples.length === 0) {
|
|
645
|
+
report(props.name, {
|
|
646
|
+
severity: "ignored",
|
|
647
|
+
feature: "@relationshipProperties",
|
|
648
|
+
message: "not used by any converted @relationship: not converted"
|
|
649
|
+
});
|
|
650
|
+
continue;
|
|
651
|
+
}
|
|
652
|
+
const scalarFields = [];
|
|
653
|
+
const propNotes = [];
|
|
654
|
+
for (const f of props.fields) {
|
|
655
|
+
const at = `${props.name}.${f.name.value}`;
|
|
656
|
+
if (dropComputed(f, at, report)) {
|
|
657
|
+
propNotes.push(skippedLine(f, "computed field"));
|
|
658
|
+
continue;
|
|
659
|
+
}
|
|
660
|
+
const u = unwrap(f.type);
|
|
661
|
+
const target = types.get(u.named);
|
|
662
|
+
if (directive(f.directives, "relationship") || target && (target.kind === "object" || target.kind === "interface" || target.kind === "union")) {
|
|
663
|
+
report(at, {
|
|
664
|
+
severity: "unsupported",
|
|
665
|
+
feature: "relationship properties",
|
|
666
|
+
message: "relationship properties can only be scalars: not converted"
|
|
667
|
+
});
|
|
668
|
+
propNotes.push(skippedLine(f, "not a scalar"));
|
|
669
|
+
continue;
|
|
670
|
+
}
|
|
671
|
+
const scalar = convertScalar(f, u, at, "relationship", false, types, report);
|
|
672
|
+
if (!scalar) {
|
|
673
|
+
propNotes.push(skippedLine(f, "type not supported"));
|
|
674
|
+
continue;
|
|
675
|
+
}
|
|
676
|
+
scalarFields.push(scalar.field);
|
|
677
|
+
}
|
|
678
|
+
const unique = dedupeNames(scalarFields, props.name, report);
|
|
679
|
+
for (const u of triples) {
|
|
680
|
+
let name = props.name;
|
|
681
|
+
if (triples.length > 1) {
|
|
682
|
+
name = `${props.name}${u.start}${u.end}`;
|
|
683
|
+
report(props.name, {
|
|
684
|
+
severity: "changed",
|
|
685
|
+
feature: "@relationshipProperties",
|
|
686
|
+
message: `used by several node pairs: written as relationship "${name}" for ${u.relType} from ${u.start} to ${u.end}`
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
let n = 2;
|
|
690
|
+
const base = name;
|
|
691
|
+
while (allNames.has(name)) name = `${base}${n++}`;
|
|
692
|
+
allNames.add(name);
|
|
693
|
+
relationships.push({
|
|
694
|
+
kind: "Relationship",
|
|
695
|
+
name,
|
|
696
|
+
relType: u.relType,
|
|
697
|
+
from: u.start,
|
|
698
|
+
to: u.end,
|
|
699
|
+
fields: unique
|
|
700
|
+
});
|
|
701
|
+
if (propNotes.length) notes.set(name, [...propNotes]);
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
return {
|
|
705
|
+
document: { kind: "Document", declarations: [...declarations, ...relationships] },
|
|
706
|
+
issues,
|
|
707
|
+
notes
|
|
708
|
+
};
|
|
709
|
+
}
|
|
710
|
+
function skippedLine(f, why) {
|
|
711
|
+
return `${f.name.value}: ${print(f.type)} (not converted: ${why})`;
|
|
712
|
+
}
|
|
713
|
+
function dropComputed(f, at, report) {
|
|
714
|
+
for (const d of f.directives ?? []) {
|
|
715
|
+
const rule = FIELD_DIRECTIVES[d.name.value];
|
|
716
|
+
if (rule?.kind === "drop") {
|
|
717
|
+
report(at, { severity: "unsupported", feature: `@${d.name.value}`, message: rule.message });
|
|
718
|
+
return true;
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
return false;
|
|
722
|
+
}
|
|
723
|
+
function dedupeNames(fields, typeName, report) {
|
|
724
|
+
const seen = /* @__PURE__ */ new Set();
|
|
725
|
+
const out = [];
|
|
726
|
+
for (const f of fields) {
|
|
727
|
+
if (seen.has(f.name)) {
|
|
728
|
+
report(`${typeName}.${f.name}`, {
|
|
729
|
+
severity: "unsupported",
|
|
730
|
+
feature: "field name",
|
|
731
|
+
message: `two fields map to the property "${f.name}": kept the first`
|
|
732
|
+
});
|
|
733
|
+
continue;
|
|
734
|
+
}
|
|
735
|
+
seen.add(f.name);
|
|
736
|
+
out.push(f);
|
|
737
|
+
}
|
|
738
|
+
return out;
|
|
739
|
+
}
|
|
740
|
+
function scalarMapping(named, types) {
|
|
741
|
+
const builtin = SCALARS[named];
|
|
742
|
+
if (builtin) return builtin;
|
|
743
|
+
const t = types.get(named);
|
|
744
|
+
if (t?.kind === "enum") return { ...ENUM_FIELD, isEnum: true };
|
|
745
|
+
return CUSTOM_SCALAR_FIELD;
|
|
746
|
+
}
|
|
747
|
+
var DECORATOR_ORDER = ["id", "unique", "index", "default"];
|
|
748
|
+
function convertScalar(f, u, at, owner, nodeHasId, types, report) {
|
|
749
|
+
if (u.nested) {
|
|
750
|
+
report(at, {
|
|
751
|
+
severity: "unsupported",
|
|
752
|
+
feature: "nested list",
|
|
753
|
+
message: "lists of lists are not supported: not converted"
|
|
754
|
+
});
|
|
755
|
+
return void 0;
|
|
756
|
+
}
|
|
757
|
+
const mapping = scalarMapping(u.named, types);
|
|
758
|
+
if ("unsupported" in mapping) {
|
|
759
|
+
report(at, {
|
|
760
|
+
severity: "unsupported",
|
|
761
|
+
feature: u.named,
|
|
762
|
+
message: `${mapping.unsupported}: not converted`
|
|
763
|
+
});
|
|
764
|
+
return void 0;
|
|
765
|
+
}
|
|
766
|
+
let name = f.name.value;
|
|
767
|
+
let optional = !u.nonNull;
|
|
768
|
+
let takesId = false;
|
|
769
|
+
const decorators = [];
|
|
770
|
+
for (const d of f.directives ?? []) {
|
|
771
|
+
const n = d.name.value;
|
|
772
|
+
if (n === "relationship") continue;
|
|
773
|
+
const rule = FIELD_DIRECTIVES[n];
|
|
774
|
+
if (!rule) {
|
|
775
|
+
report(at, {
|
|
776
|
+
severity: "unsupported",
|
|
777
|
+
feature: `@${n}`,
|
|
778
|
+
message: `unknown directive @${n}: not converted`
|
|
779
|
+
});
|
|
780
|
+
continue;
|
|
781
|
+
}
|
|
782
|
+
if (rule.kind === "report") {
|
|
783
|
+
report(at, { severity: rule.severity, feature: `@${n}`, message: rule.message });
|
|
784
|
+
continue;
|
|
785
|
+
}
|
|
786
|
+
if (rule.kind !== "scalar") continue;
|
|
787
|
+
const effect = rule.apply(d, {
|
|
788
|
+
owner,
|
|
789
|
+
graphqlType: u.named,
|
|
790
|
+
type: mapping.type,
|
|
791
|
+
list: u.list,
|
|
792
|
+
isEnum: Boolean(mapping.isEnum),
|
|
793
|
+
nodeHasId: nodeHasId || takesId
|
|
794
|
+
});
|
|
795
|
+
for (const i of effect.issues ?? []) report(at, i);
|
|
796
|
+
for (const dec of effect.decorators ?? []) {
|
|
797
|
+
if (decorators.some((x) => x.name === dec.name)) {
|
|
798
|
+
report(at, {
|
|
799
|
+
severity: "unsupported",
|
|
800
|
+
feature: `@${n}`,
|
|
801
|
+
message: `conflicts with another directive setting @${dec.name}: kept the first`
|
|
802
|
+
});
|
|
803
|
+
continue;
|
|
804
|
+
}
|
|
805
|
+
decorators.push(dec);
|
|
806
|
+
}
|
|
807
|
+
if (effect.rename) name = effect.rename;
|
|
808
|
+
if (effect.required !== void 0) optional = !effect.required;
|
|
809
|
+
if (effect.takesId) takesId = true;
|
|
810
|
+
}
|
|
811
|
+
decorators.sort((a, b) => DECORATOR_ORDER.indexOf(a.name) - DECORATOR_ORDER.indexOf(b.name));
|
|
812
|
+
return {
|
|
813
|
+
field: {
|
|
814
|
+
kind: "Scalar",
|
|
815
|
+
name,
|
|
816
|
+
type: u.list ? { name: mapping.type, optional: false, list: true } : { name: mapping.type, optional },
|
|
817
|
+
decorators
|
|
818
|
+
},
|
|
819
|
+
takesId
|
|
820
|
+
};
|
|
821
|
+
}
|
|
822
|
+
function convertRelation(f, u, at, ownerType, types, nodeName, report) {
|
|
823
|
+
const rel = directive(f.directives, "relationship");
|
|
824
|
+
const target = types.get(u.named);
|
|
825
|
+
if (!rel) {
|
|
826
|
+
report(at, {
|
|
827
|
+
severity: "unsupported",
|
|
828
|
+
feature: "@relationship",
|
|
829
|
+
message: "object field without @relationship (or @cypher): not converted"
|
|
830
|
+
});
|
|
831
|
+
return void 0;
|
|
832
|
+
}
|
|
833
|
+
if (!target || target.kind !== "object" || !nodeName.has(u.named)) {
|
|
834
|
+
const what = target?.kind === "interface" || target?.kind === "union" ? target.kind : "type";
|
|
835
|
+
report(at, {
|
|
836
|
+
severity: "unsupported",
|
|
837
|
+
feature: "@relationship",
|
|
838
|
+
message: `relationships to ${what === "type" ? `"${u.named}" (not a @node type)` : `an ${what}`} are not supported yet: not converted`
|
|
839
|
+
});
|
|
840
|
+
return void 0;
|
|
841
|
+
}
|
|
842
|
+
if (u.nested) {
|
|
843
|
+
report(at, {
|
|
844
|
+
severity: "unsupported",
|
|
845
|
+
feature: "nested list",
|
|
846
|
+
message: "lists of lists are not supported: not converted"
|
|
847
|
+
});
|
|
848
|
+
return void 0;
|
|
849
|
+
}
|
|
850
|
+
const relType = stringArg(rel, "type");
|
|
851
|
+
const direction = enumListArg(rel, "direction")?.[0];
|
|
852
|
+
if (!relType || direction !== "IN" && direction !== "OUT") {
|
|
853
|
+
report(at, {
|
|
854
|
+
severity: "unsupported",
|
|
855
|
+
feature: "@relationship",
|
|
856
|
+
message: "@relationship needs type and direction: IN | OUT; not converted"
|
|
857
|
+
});
|
|
858
|
+
return void 0;
|
|
859
|
+
}
|
|
860
|
+
const queryDirection = enumListArg(rel, "queryDirection")?.[0];
|
|
861
|
+
if (queryDirection && queryDirection !== "DIRECTED") {
|
|
862
|
+
report(at, {
|
|
863
|
+
severity: "changed",
|
|
864
|
+
feature: "@relationship(queryDirection)",
|
|
865
|
+
message: `queryDirection ${queryDirection} is not supported: Cyphra follows direction ${direction}`
|
|
866
|
+
});
|
|
867
|
+
}
|
|
868
|
+
for (const a of RELATIONSHIP_API_ARGS) {
|
|
869
|
+
if (rel.arguments?.some((x) => x.name.value === a)) {
|
|
870
|
+
report(at, {
|
|
871
|
+
severity: "ignored",
|
|
872
|
+
feature: `@relationship(${a})`,
|
|
873
|
+
message: "API setting of @neo4j/graphql, no effect on the data model"
|
|
874
|
+
});
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
for (const d of f.directives ?? []) {
|
|
878
|
+
const n = d.name.value;
|
|
879
|
+
if (n === "relationship") continue;
|
|
880
|
+
const rule = FIELD_DIRECTIVES[n];
|
|
881
|
+
if (rule?.kind === "report") {
|
|
882
|
+
report(at, { severity: rule.severity, feature: `@${n}`, message: rule.message });
|
|
883
|
+
} else {
|
|
884
|
+
report(at, {
|
|
885
|
+
severity: "unsupported",
|
|
886
|
+
feature: `@${n}`,
|
|
887
|
+
message: `@${n} is not supported on relationship fields: not converted`
|
|
888
|
+
});
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
const self = nodeName.get(ownerType);
|
|
892
|
+
const other = nodeName.get(u.named);
|
|
893
|
+
const field = {
|
|
894
|
+
kind: "Relational",
|
|
895
|
+
name: f.name.value,
|
|
896
|
+
target: other,
|
|
897
|
+
cardinality: u.list ? "many" : "one",
|
|
898
|
+
optional: u.list ? false : !u.nonNull,
|
|
899
|
+
decorators: [
|
|
900
|
+
{
|
|
901
|
+
name: "relationship",
|
|
902
|
+
args: [
|
|
903
|
+
{ key: "type", value: { kind: "string", value: relType } },
|
|
904
|
+
{ key: "direction", value: { kind: "identifier", value: direction } }
|
|
905
|
+
]
|
|
906
|
+
}
|
|
907
|
+
]
|
|
908
|
+
};
|
|
909
|
+
const propsType = stringArg(rel, "properties");
|
|
910
|
+
if (!propsType) return { field };
|
|
911
|
+
const props = types.get(propsType);
|
|
912
|
+
if (!props || !directive(props.directives, "relationshipProperties")) {
|
|
913
|
+
report(at, {
|
|
914
|
+
severity: "unsupported",
|
|
915
|
+
feature: "@relationship(properties)",
|
|
916
|
+
message: `"${propsType}" is not a @relationshipProperties type: properties not converted`
|
|
917
|
+
});
|
|
918
|
+
return { field };
|
|
919
|
+
}
|
|
920
|
+
const [start, end] = direction === "OUT" ? [self, other] : [other, self];
|
|
921
|
+
return { field, usage: { propsType, relType, start, end, at } };
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
// src/import/print.ts
|
|
925
|
+
import {
|
|
926
|
+
parseSchema,
|
|
927
|
+
printSchemaDocument,
|
|
928
|
+
resolveSchema
|
|
929
|
+
} from "@cyphra/schema";
|
|
930
|
+
var HEADER = "// Imported from @neo4j/graphql type definitions with `cyphra import graphql`.";
|
|
931
|
+
function printDeclaration(decl, notes) {
|
|
932
|
+
const text = printSchemaDocument({ kind: "Document", declarations: [decl] }).trimEnd();
|
|
933
|
+
if (!notes?.length) return text;
|
|
934
|
+
const lines = text.split("\n");
|
|
935
|
+
lines.splice(lines.length - 1, 0, ...notes.map((n) => ` // ${n}`));
|
|
936
|
+
return lines.join("\n");
|
|
937
|
+
}
|
|
938
|
+
function printDeclarations(result, decls) {
|
|
939
|
+
return decls.map((d) => printDeclaration(d, result.notes.get(d.name))).join("\n\n");
|
|
940
|
+
}
|
|
941
|
+
function reviewComment(issues) {
|
|
942
|
+
const review = issues.filter((i) => i.severity !== "ignored");
|
|
943
|
+
if (review.length === 0) return [];
|
|
944
|
+
return [
|
|
945
|
+
"// Review before use (run the import again to see the full report):",
|
|
946
|
+
...review.map((i) => `// - ${i.at}: ${i.message}`)
|
|
947
|
+
];
|
|
948
|
+
}
|
|
949
|
+
function printImportedSchema(result) {
|
|
950
|
+
const head = [HEADER, ...reviewComment(result.issues)].join("\n");
|
|
951
|
+
const body = printDeclarations(result, result.document.declarations);
|
|
952
|
+
return body ? `${head}
|
|
953
|
+
|
|
954
|
+
${body}
|
|
955
|
+
` : `${head}
|
|
956
|
+
`;
|
|
957
|
+
}
|
|
958
|
+
function formatField(field) {
|
|
959
|
+
const text = printSchemaDocument({
|
|
960
|
+
kind: "Document",
|
|
961
|
+
declarations: [{ kind: "Node", name: "X", fields: [field] }]
|
|
962
|
+
});
|
|
963
|
+
return text.split("\n")[1].trim();
|
|
964
|
+
}
|
|
965
|
+
function nodeCloseBrace(source, name) {
|
|
966
|
+
let depth = 0;
|
|
967
|
+
let inTarget = false;
|
|
968
|
+
for (let i = 0; i < source.length; i++) {
|
|
969
|
+
const c = source[i];
|
|
970
|
+
if (c === "/" && source[i + 1] === "/") {
|
|
971
|
+
while (i < source.length && source[i] !== "\n") i++;
|
|
972
|
+
continue;
|
|
973
|
+
}
|
|
974
|
+
if (c === '"') {
|
|
975
|
+
for (i++; i < source.length && source[i] !== '"'; i++) if (source[i] === "\\") i++;
|
|
976
|
+
continue;
|
|
977
|
+
}
|
|
978
|
+
if (depth === 0 && /[A-Za-z_]/.test(c) && (i === 0 || !/[A-Za-z0-9_]/.test(source[i - 1]))) {
|
|
979
|
+
const m = /^(node|relationship)\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(source.slice(i));
|
|
980
|
+
if (m) {
|
|
981
|
+
inTarget = m[1] === "node" && m[2] === name;
|
|
982
|
+
i += m[0].length - 1;
|
|
983
|
+
continue;
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
if (c === "{") depth++;
|
|
987
|
+
else if (c === "}") {
|
|
988
|
+
depth--;
|
|
989
|
+
if (depth === 0 && inTarget) return i;
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
return -1;
|
|
993
|
+
}
|
|
994
|
+
function mergeImportedSchema(existing, result) {
|
|
995
|
+
const doc = parseSchema(existing);
|
|
996
|
+
const issues = [];
|
|
997
|
+
const kept = (at, what) => issues.push({
|
|
998
|
+
severity: "changed",
|
|
999
|
+
at,
|
|
1000
|
+
feature: "--merge",
|
|
1001
|
+
message: `${what} already exists with a different definition: kept yours`
|
|
1002
|
+
});
|
|
1003
|
+
let out = existing;
|
|
1004
|
+
const appended = [];
|
|
1005
|
+
for (const decl of result.document.declarations) {
|
|
1006
|
+
const current = doc.declarations.find((d) => d.name === decl.name);
|
|
1007
|
+
if (!current) {
|
|
1008
|
+
appended.push(decl);
|
|
1009
|
+
continue;
|
|
1010
|
+
}
|
|
1011
|
+
if (decl.kind !== "Node" || current.kind !== "Node") {
|
|
1012
|
+
const same = decl.kind === current.kind && printSchemaDocument({ kind: "Document", declarations: [decl] }) === printSchemaDocument({ kind: "Document", declarations: [current] });
|
|
1013
|
+
if (!same)
|
|
1014
|
+
kept(decl.name, `${current.kind === "Node" ? "node" : "relationship"} ${decl.name}`);
|
|
1015
|
+
continue;
|
|
1016
|
+
}
|
|
1017
|
+
const missing = [];
|
|
1018
|
+
for (const f of decl.fields) {
|
|
1019
|
+
const mine = current.fields.find((x) => x.name === f.name);
|
|
1020
|
+
if (!mine) missing.push(f);
|
|
1021
|
+
else if (formatField(mine) !== formatField(f))
|
|
1022
|
+
kept(`${decl.name}.${f.name}`, `field ${f.name}`);
|
|
1023
|
+
}
|
|
1024
|
+
const notes = (result.notes.get(decl.name) ?? []).filter((n) => !out.includes(`// ${n}`));
|
|
1025
|
+
if (missing.length === 0 && notes.length === 0) continue;
|
|
1026
|
+
const close = nodeCloseBrace(out, decl.name);
|
|
1027
|
+
if (close < 0) throw new Error(`Could not find the block of node "${decl.name}".`);
|
|
1028
|
+
const lineStart = out.lastIndexOf("\n", close - 1) + 1;
|
|
1029
|
+
const onOwnLine = out.slice(lineStart, close).trim() === "";
|
|
1030
|
+
const added = [...missing.map(formatField), ...notes.map((n) => `// ${n}`)].map((l) => ` ${l}
|
|
1031
|
+
`).join("");
|
|
1032
|
+
out = onOwnLine ? out.slice(0, lineStart) + added + out.slice(lineStart) : `${out.slice(0, close).trimEnd()}
|
|
1033
|
+
${added}${out.slice(close)}`;
|
|
1034
|
+
}
|
|
1035
|
+
if (appended.length) {
|
|
1036
|
+
out = `${out.trimEnd()}
|
|
1037
|
+
|
|
1038
|
+
${HEADER}
|
|
1039
|
+
|
|
1040
|
+
${printDeclarations(result, appended)}
|
|
1041
|
+
`;
|
|
1042
|
+
}
|
|
1043
|
+
try {
|
|
1044
|
+
resolveSchema(parseSchema(out));
|
|
1045
|
+
} catch (cause) {
|
|
1046
|
+
throw new Error(
|
|
1047
|
+
`Merging the imported models into the existing schema produced an invalid schema: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
1048
|
+
{ cause }
|
|
1049
|
+
);
|
|
1050
|
+
}
|
|
1051
|
+
return { source: out, issues };
|
|
1052
|
+
}
|
|
1053
|
+
var SECTIONS = [
|
|
1054
|
+
{ severity: "unsupported", title: "Not converted" },
|
|
1055
|
+
{ severity: "changed", title: "Converted with differences" },
|
|
1056
|
+
{ severity: "ignored", title: "Ignored (GraphQL API only)" }
|
|
1057
|
+
];
|
|
1058
|
+
function formatImportReport(issues) {
|
|
1059
|
+
const blocks = [];
|
|
1060
|
+
for (const s of SECTIONS) {
|
|
1061
|
+
const items = issues.filter((i) => i.severity === s.severity);
|
|
1062
|
+
if (items.length === 0) continue;
|
|
1063
|
+
const width = Math.min(32, Math.max(...items.map((i) => i.at.length)));
|
|
1064
|
+
blocks.push(
|
|
1065
|
+
[
|
|
1066
|
+
`${s.title} (${items.length}):`,
|
|
1067
|
+
...items.map((i) => ` ${i.at.padEnd(width)} ${i.feature}: ${i.message}`)
|
|
1068
|
+
].join("\n")
|
|
1069
|
+
);
|
|
1070
|
+
}
|
|
1071
|
+
return blocks.join("\n\n");
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
// src/v7/cypher/select.ts
|
|
1075
|
+
import {
|
|
1076
|
+
GraphQLIncludeDirective,
|
|
1077
|
+
GraphQLSkipDirective,
|
|
1078
|
+
Kind as Kind4,
|
|
1079
|
+
getArgumentValues,
|
|
1080
|
+
getDirectiveValues
|
|
1081
|
+
} from "graphql";
|
|
1082
|
+
import neo4j2, { isInt } from "neo4j-driver";
|
|
1083
|
+
|
|
1084
|
+
// src/v7/errors.ts
|
|
1085
|
+
import { GraphQLError as GraphQLError2 } from "graphql";
|
|
1086
|
+
var FOLLOW_UP = {
|
|
1087
|
+
authorization: 74,
|
|
1088
|
+
cypher: 75
|
|
1089
|
+
};
|
|
1090
|
+
function notImplemented(what, issue2) {
|
|
1091
|
+
return new GraphQLError2(`Not implemented yet in @cyphra/graphql (see #${issue2}): ${what}`, {
|
|
1092
|
+
extensions: { code: "NOT_IMPLEMENTED" }
|
|
1093
|
+
});
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
// src/v7/model.ts
|
|
1097
|
+
import {
|
|
1098
|
+
Kind as Kind3,
|
|
1099
|
+
parse as parse2,
|
|
1100
|
+
valueFromASTUntyped
|
|
1101
|
+
} from "graphql";
|
|
1102
|
+
|
|
1103
|
+
// src/v7/naming.ts
|
|
1104
|
+
import pluralizeLib from "pluralize";
|
|
1105
|
+
function upperFirst(s) {
|
|
1106
|
+
return s.charAt(0).toUpperCase() + s.slice(1);
|
|
1107
|
+
}
|
|
1108
|
+
function camelCase(input) {
|
|
1109
|
+
const s = input.replace(/^_+/, "");
|
|
1110
|
+
const words = s.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").split(/[\s_\-.]+/).filter(Boolean);
|
|
1111
|
+
return words.map((w, i) => i === 0 ? w.toLowerCase() : upperFirst(w.toLowerCase())).join("");
|
|
1112
|
+
}
|
|
1113
|
+
function leadingUnderscores(name) {
|
|
1114
|
+
return /^_+/.exec(name)?.[0] ?? "";
|
|
1115
|
+
}
|
|
1116
|
+
function pluralize(word) {
|
|
1117
|
+
return pluralizeLib(word);
|
|
1118
|
+
}
|
|
1119
|
+
function entityPlural(name, pluralOverride) {
|
|
1120
|
+
if (pluralOverride !== void 0)
|
|
1121
|
+
return `${leadingUnderscores(pluralOverride)}${camelCase(pluralOverride)}`;
|
|
1122
|
+
return `${leadingUnderscores(name)}${pluralizeLib(camelCase(name))}`;
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
// src/v7/model.ts
|
|
1126
|
+
var SUPPORTED_SCALARS = [
|
|
1127
|
+
"ID",
|
|
1128
|
+
"String",
|
|
1129
|
+
"Int",
|
|
1130
|
+
"Float",
|
|
1131
|
+
"Boolean",
|
|
1132
|
+
"BigInt",
|
|
1133
|
+
"Date",
|
|
1134
|
+
"DateTime"
|
|
1135
|
+
];
|
|
1136
|
+
var UNSUPPORTED_SCALARS = /* @__PURE__ */ new Set([
|
|
1137
|
+
"LocalDateTime",
|
|
1138
|
+
"Time",
|
|
1139
|
+
"LocalTime",
|
|
1140
|
+
"Duration",
|
|
1141
|
+
"Point",
|
|
1142
|
+
"CartesianPoint"
|
|
1143
|
+
]);
|
|
1144
|
+
var UnsupportedTypeDefsError = class extends Error {
|
|
1145
|
+
name = "UnsupportedTypeDefsError";
|
|
1146
|
+
};
|
|
1147
|
+
function directive2(dirs, name) {
|
|
1148
|
+
return dirs?.find((d) => d.name.value === name);
|
|
1149
|
+
}
|
|
1150
|
+
function arg2(d, name) {
|
|
1151
|
+
return d?.arguments?.find((a) => a.name.value === name)?.value;
|
|
1152
|
+
}
|
|
1153
|
+
function stringArg2(d, name) {
|
|
1154
|
+
const v = arg2(d, name);
|
|
1155
|
+
return v && (v.kind === Kind3.STRING || v.kind === Kind3.ENUM) ? v.value : void 0;
|
|
1156
|
+
}
|
|
1157
|
+
function listArg(d, name) {
|
|
1158
|
+
const v = arg2(d, name);
|
|
1159
|
+
if (!v) return void 0;
|
|
1160
|
+
if (v.kind === Kind3.LIST) {
|
|
1161
|
+
return v.values.flatMap(
|
|
1162
|
+
(x) => x.kind === Kind3.STRING || x.kind === Kind3.ENUM ? [x.value] : []
|
|
1163
|
+
);
|
|
1164
|
+
}
|
|
1165
|
+
if (v.kind === Kind3.STRING || v.kind === Kind3.ENUM) return [v.value];
|
|
1166
|
+
return void 0;
|
|
1167
|
+
}
|
|
1168
|
+
function typeRef(t) {
|
|
1169
|
+
let cur = t;
|
|
1170
|
+
let required = false;
|
|
1171
|
+
if (cur.kind === Kind3.NON_NULL_TYPE) {
|
|
1172
|
+
required = true;
|
|
1173
|
+
cur = cur.type;
|
|
1174
|
+
}
|
|
1175
|
+
if (cur.kind === Kind3.LIST_TYPE) {
|
|
1176
|
+
let inner = cur.type;
|
|
1177
|
+
let elementRequired = false;
|
|
1178
|
+
if (inner.kind === Kind3.NON_NULL_TYPE) {
|
|
1179
|
+
elementRequired = true;
|
|
1180
|
+
inner = inner.type;
|
|
1181
|
+
}
|
|
1182
|
+
if (inner.kind !== Kind3.NAMED_TYPE)
|
|
1183
|
+
throw new UnsupportedTypeDefsError("Nested lists are not supported.");
|
|
1184
|
+
return { name: inner.name.value, list: true, required, elementRequired };
|
|
1185
|
+
}
|
|
1186
|
+
return {
|
|
1187
|
+
name: cur.name.value,
|
|
1188
|
+
list: false,
|
|
1189
|
+
required,
|
|
1190
|
+
elementRequired: false
|
|
1191
|
+
};
|
|
1192
|
+
}
|
|
1193
|
+
var ACCEPTED_FIELD_DIRECTIVES = /* @__PURE__ */ new Set([
|
|
1194
|
+
"id",
|
|
1195
|
+
"default",
|
|
1196
|
+
"timestamp",
|
|
1197
|
+
"cypher",
|
|
1198
|
+
"relationship",
|
|
1199
|
+
"alias",
|
|
1200
|
+
"deprecated",
|
|
1201
|
+
"coalesce",
|
|
1202
|
+
"unique"
|
|
1203
|
+
]);
|
|
1204
|
+
var ACCEPTED_TYPE_DIRECTIVES = /* @__PURE__ */ new Set([
|
|
1205
|
+
"node",
|
|
1206
|
+
"plural",
|
|
1207
|
+
"authentication",
|
|
1208
|
+
"authorization",
|
|
1209
|
+
"relationshipProperties",
|
|
1210
|
+
"jwt"
|
|
1211
|
+
]);
|
|
1212
|
+
function deprecationReason(dirs) {
|
|
1213
|
+
const d = directive2(dirs, "deprecated");
|
|
1214
|
+
if (!d) return void 0;
|
|
1215
|
+
return stringArg2(d, "reason") ?? "No longer supported";
|
|
1216
|
+
}
|
|
1217
|
+
function readAttribute(owner, f, enums) {
|
|
1218
|
+
for (const d of f.directives ?? []) {
|
|
1219
|
+
if (!ACCEPTED_FIELD_DIRECTIVES.has(d.name.value)) {
|
|
1220
|
+
throw new UnsupportedTypeDefsError(
|
|
1221
|
+
`${owner}.${f.name.value}: @${d.name.value} is not supported by @cyphra/graphql yet.`
|
|
1222
|
+
);
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
if (f.arguments?.length) {
|
|
1226
|
+
throw new UnsupportedTypeDefsError(
|
|
1227
|
+
`${owner}.${f.name.value}: field arguments are not supported by @cyphra/graphql yet.`
|
|
1228
|
+
);
|
|
1229
|
+
}
|
|
1230
|
+
const type = typeRef(f.type);
|
|
1231
|
+
const isEnum = enums.has(type.name);
|
|
1232
|
+
if (!isEnum && !SUPPORTED_SCALARS.includes(type.name)) {
|
|
1233
|
+
if (UNSUPPORTED_SCALARS.has(type.name)) {
|
|
1234
|
+
throw new UnsupportedTypeDefsError(
|
|
1235
|
+
`${owner}.${f.name.value}: ${type.name} is not supported by @cyphra/graphql yet.`
|
|
1236
|
+
);
|
|
1237
|
+
}
|
|
1238
|
+
throw new UnsupportedTypeDefsError(
|
|
1239
|
+
`${owner}.${f.name.value}: type ${type.name} is not a supported scalar or enum (fields returning objects need @relationship).`
|
|
1240
|
+
);
|
|
1241
|
+
}
|
|
1242
|
+
const dirs = f.directives;
|
|
1243
|
+
const def = directive2(dirs, "default");
|
|
1244
|
+
const defaultAst = arg2(def, "value");
|
|
1245
|
+
const ts = directive2(dirs, "timestamp");
|
|
1246
|
+
const cypher = directive2(dirs, "cypher");
|
|
1247
|
+
const alias = directive2(dirs, "alias");
|
|
1248
|
+
return {
|
|
1249
|
+
name: f.name.value,
|
|
1250
|
+
property: stringArg2(alias, "property") ?? f.name.value,
|
|
1251
|
+
type,
|
|
1252
|
+
kind: isEnum ? "enum" : "scalar",
|
|
1253
|
+
description: f.description?.value,
|
|
1254
|
+
id: !!directive2(dirs, "id"),
|
|
1255
|
+
defaultAst,
|
|
1256
|
+
defaultValue: defaultAst ? valueFromASTUntyped(defaultAst) : void 0,
|
|
1257
|
+
timestamp: ts ? listArg(ts, "operations") ?? ["CREATE", "UPDATE"] : void 0,
|
|
1258
|
+
cypher: cypher ? {
|
|
1259
|
+
statement: stringArg2(cypher, "statement") ?? "",
|
|
1260
|
+
columnName: stringArg2(cypher, "columnName") ?? ""
|
|
1261
|
+
} : void 0,
|
|
1262
|
+
deprecated: deprecationReason(dirs)
|
|
1263
|
+
};
|
|
1264
|
+
}
|
|
1265
|
+
var ALL_OPERATIONS = [
|
|
1266
|
+
"READ",
|
|
1267
|
+
"AGGREGATE",
|
|
1268
|
+
"CREATE",
|
|
1269
|
+
"UPDATE",
|
|
1270
|
+
"DELETE",
|
|
1271
|
+
"CREATE_RELATIONSHIP",
|
|
1272
|
+
"DELETE_RELATIONSHIP",
|
|
1273
|
+
"SUBSCRIBE"
|
|
1274
|
+
];
|
|
1275
|
+
function readTypeDefs(typeDefs) {
|
|
1276
|
+
const doc = parse2(typeDefs);
|
|
1277
|
+
const objects = [];
|
|
1278
|
+
const enums = /* @__PURE__ */ new Map();
|
|
1279
|
+
for (const def of doc.definitions) {
|
|
1280
|
+
switch (def.kind) {
|
|
1281
|
+
case Kind3.OBJECT_TYPE_DEFINITION:
|
|
1282
|
+
objects.push(def);
|
|
1283
|
+
break;
|
|
1284
|
+
case Kind3.ENUM_TYPE_DEFINITION:
|
|
1285
|
+
enums.set(def.name.value, {
|
|
1286
|
+
name: def.name.value,
|
|
1287
|
+
description: def.description?.value,
|
|
1288
|
+
values: (def.values ?? []).map((v) => ({
|
|
1289
|
+
name: v.name.value,
|
|
1290
|
+
description: v.description?.value,
|
|
1291
|
+
deprecated: deprecationReason(v.directives)
|
|
1292
|
+
}))
|
|
1293
|
+
});
|
|
1294
|
+
break;
|
|
1295
|
+
case Kind3.SCALAR_TYPE_DEFINITION:
|
|
1296
|
+
if (!SUPPORTED_SCALARS.includes(def.name.value)) {
|
|
1297
|
+
throw new UnsupportedTypeDefsError(
|
|
1298
|
+
`scalar ${def.name.value}: custom scalars are not supported by @cyphra/graphql yet.`
|
|
1299
|
+
);
|
|
1300
|
+
}
|
|
1301
|
+
break;
|
|
1302
|
+
case Kind3.DIRECTIVE_DEFINITION:
|
|
1303
|
+
break;
|
|
1304
|
+
default:
|
|
1305
|
+
throw new UnsupportedTypeDefsError(
|
|
1306
|
+
`${def.kind}${"name" in def && def.name ? ` ${def.name.value}` : ""}: not supported by @cyphra/graphql yet (only object types, enums and relationship properties).`
|
|
1307
|
+
);
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
const enumNames = new Set(enums.keys());
|
|
1311
|
+
const properties = /* @__PURE__ */ new Map();
|
|
1312
|
+
const nodeDefs = [];
|
|
1313
|
+
for (const o of objects) {
|
|
1314
|
+
const name = o.name.value;
|
|
1315
|
+
if (["Query", "Mutation", "Subscription"].includes(name)) {
|
|
1316
|
+
throw new UnsupportedTypeDefsError(
|
|
1317
|
+
`type ${name}: custom root fields are not supported by @cyphra/graphql yet.`
|
|
1318
|
+
);
|
|
1319
|
+
}
|
|
1320
|
+
if (o.interfaces?.length) {
|
|
1321
|
+
throw new UnsupportedTypeDefsError(
|
|
1322
|
+
`type ${name}: interfaces are not supported by @cyphra/graphql yet.`
|
|
1323
|
+
);
|
|
1324
|
+
}
|
|
1325
|
+
for (const d of o.directives ?? []) {
|
|
1326
|
+
if (!ACCEPTED_TYPE_DIRECTIVES.has(d.name.value)) {
|
|
1327
|
+
throw new UnsupportedTypeDefsError(
|
|
1328
|
+
`type ${name}: @${d.name.value} is not supported by @cyphra/graphql yet.`
|
|
1329
|
+
);
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
if (directive2(o.directives, "jwt")) continue;
|
|
1333
|
+
if (directive2(o.directives, "relationshipProperties")) {
|
|
1334
|
+
properties.set(name, {
|
|
1335
|
+
name,
|
|
1336
|
+
attributes: (o.fields ?? []).map((f) => readAttribute(name, f, enumNames))
|
|
1337
|
+
});
|
|
1338
|
+
continue;
|
|
1339
|
+
}
|
|
1340
|
+
if (!directive2(o.directives, "node")) {
|
|
1341
|
+
throw new UnsupportedTypeDefsError(
|
|
1342
|
+
`type ${name}: object types without @node are not supported by @cyphra/graphql yet.`
|
|
1343
|
+
);
|
|
1344
|
+
}
|
|
1345
|
+
nodeDefs.push(o);
|
|
1346
|
+
}
|
|
1347
|
+
const nodeNames = new Set(nodeDefs.map((o) => o.name.value));
|
|
1348
|
+
const nodes = nodeDefs.map((o) => {
|
|
1349
|
+
const name = o.name.value;
|
|
1350
|
+
const attributes = [];
|
|
1351
|
+
const relationships = [];
|
|
1352
|
+
for (const f of o.fields ?? []) {
|
|
1353
|
+
const rel = directive2(f.directives, "relationship");
|
|
1354
|
+
if (!rel) {
|
|
1355
|
+
attributes.push(readAttribute(name, f, enumNames));
|
|
1356
|
+
continue;
|
|
1357
|
+
}
|
|
1358
|
+
const t = typeRef(f.type);
|
|
1359
|
+
if (!nodeNames.has(t.name)) {
|
|
1360
|
+
throw new UnsupportedTypeDefsError(
|
|
1361
|
+
`${name}.${f.name.value}: relationships to ${t.name} are not supported by @cyphra/graphql yet (target must be a @node type).`
|
|
1362
|
+
);
|
|
1363
|
+
}
|
|
1364
|
+
for (const a of rel.arguments ?? []) {
|
|
1365
|
+
if (!["type", "direction", "properties"].includes(a.name.value)) {
|
|
1366
|
+
throw new UnsupportedTypeDefsError(
|
|
1367
|
+
`${name}.${f.name.value}: @relationship(${a.name.value}) is not supported by @cyphra/graphql yet.`
|
|
1368
|
+
);
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
const props = stringArg2(rel, "properties");
|
|
1372
|
+
if (props && !properties.has(props)) {
|
|
1373
|
+
throw new UnsupportedTypeDefsError(
|
|
1374
|
+
`${name}.${f.name.value}: properties type ${props} must be a @relationshipProperties type.`
|
|
1375
|
+
);
|
|
1376
|
+
}
|
|
1377
|
+
relationships.push({
|
|
1378
|
+
name: f.name.value,
|
|
1379
|
+
source: name,
|
|
1380
|
+
target: t.name,
|
|
1381
|
+
type: stringArg2(rel, "type") ?? "",
|
|
1382
|
+
direction: stringArg2(rel, "direction") === "IN" ? "IN" : "OUT",
|
|
1383
|
+
properties: props,
|
|
1384
|
+
list: t.list,
|
|
1385
|
+
required: t.required,
|
|
1386
|
+
elementRequired: t.elementRequired,
|
|
1387
|
+
description: f.description?.value,
|
|
1388
|
+
deprecated: deprecationReason(f.directives)
|
|
1389
|
+
});
|
|
1390
|
+
}
|
|
1391
|
+
const nodeDir = directive2(o.directives, "node");
|
|
1392
|
+
const labels2 = listArg(nodeDir, "labels") ?? [name];
|
|
1393
|
+
const pluralDir = directive2(o.directives, "plural");
|
|
1394
|
+
const plural = entityPlural(name, stringArg2(pluralDir, "value"));
|
|
1395
|
+
const authn = directive2(o.directives, "authentication");
|
|
1396
|
+
return {
|
|
1397
|
+
name,
|
|
1398
|
+
description: o.description?.value,
|
|
1399
|
+
labels: labels2,
|
|
1400
|
+
plural,
|
|
1401
|
+
pascalPlural: upperFirst(plural),
|
|
1402
|
+
attributes,
|
|
1403
|
+
relationships,
|
|
1404
|
+
auth: {
|
|
1405
|
+
authentication: authn ? listArg(authn, "operations") ?? ALL_OPERATIONS : void 0,
|
|
1406
|
+
authorization: !!directive2(o.directives, "authorization")
|
|
1407
|
+
}
|
|
1408
|
+
};
|
|
1409
|
+
});
|
|
1410
|
+
const byName = new Map(nodes.map((n) => [n.name, n]));
|
|
1411
|
+
return {
|
|
1412
|
+
nodes,
|
|
1413
|
+
properties,
|
|
1414
|
+
enums,
|
|
1415
|
+
node(name) {
|
|
1416
|
+
const n = byName.get(name);
|
|
1417
|
+
if (!n) throw new Error(`Unknown node type ${name}`);
|
|
1418
|
+
return n;
|
|
1419
|
+
}
|
|
1420
|
+
};
|
|
1421
|
+
}
|
|
1422
|
+
function readNeedsAuth(node) {
|
|
1423
|
+
return node.auth.authorization || (node.auth.authentication?.includes("READ") ?? false);
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
// src/v7/cypher/context.ts
|
|
1427
|
+
var CypherContext = class {
|
|
1428
|
+
params = {};
|
|
1429
|
+
paramCount = 0;
|
|
1430
|
+
varCount = 0;
|
|
1431
|
+
/** Bind a value and return its `$placeholder`. */
|
|
1432
|
+
param(value) {
|
|
1433
|
+
const key = `p${this.paramCount++}`;
|
|
1434
|
+
this.params[key] = value;
|
|
1435
|
+
return `$${key}`;
|
|
1436
|
+
}
|
|
1437
|
+
/** Fresh variable name, e.g. `this0`. */
|
|
1438
|
+
variable(prefix2 = "this") {
|
|
1439
|
+
return `${prefix2}${this.varCount++}`;
|
|
1440
|
+
}
|
|
1441
|
+
};
|
|
1442
|
+
function q(id) {
|
|
1443
|
+
return "`" + id.replace(/`/g, "``") + "`";
|
|
1444
|
+
}
|
|
1445
|
+
function labels(ls) {
|
|
1446
|
+
return ls.map((l) => `:${q(l)}`).join("");
|
|
1447
|
+
}
|
|
1448
|
+
function listAggregate(fn, l) {
|
|
1449
|
+
const sum = `reduce(acc = 0, x IN ${l} | acc + x)`;
|
|
1450
|
+
switch (fn) {
|
|
1451
|
+
case "min":
|
|
1452
|
+
return `reduce(acc = null, x IN ${l} | CASE WHEN acc IS NULL OR x < acc THEN x ELSE acc END)`;
|
|
1453
|
+
case "max":
|
|
1454
|
+
return `reduce(acc = null, x IN ${l} | CASE WHEN acc IS NULL OR x > acc THEN x ELSE acc END)`;
|
|
1455
|
+
case "sum":
|
|
1456
|
+
return sum;
|
|
1457
|
+
case "avg":
|
|
1458
|
+
return `CASE size(${l}) WHEN 0 THEN null ELSE toFloat(${sum}) / size(${l}) END`;
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
function withList(list2, l, body) {
|
|
1462
|
+
return `[${l} IN [${list2}] | ${body(l)}][0]`;
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
// src/v7/cypher/where.ts
|
|
1466
|
+
import neo4j from "neo4j-driver";
|
|
1467
|
+
var LEGACY_OPERATORS = {
|
|
1468
|
+
EQ: "eq",
|
|
1469
|
+
IN: "in",
|
|
1470
|
+
INCLUDES: "includes",
|
|
1471
|
+
CONTAINS: "contains",
|
|
1472
|
+
STARTS_WITH: "startsWith",
|
|
1473
|
+
ENDS_WITH: "endsWith",
|
|
1474
|
+
LT: "lt",
|
|
1475
|
+
LTE: "lte",
|
|
1476
|
+
GT: "gt",
|
|
1477
|
+
GTE: "gte"
|
|
1478
|
+
};
|
|
1479
|
+
var QUANTIFIER_KEYS = {
|
|
1480
|
+
ALL: "all",
|
|
1481
|
+
NONE: "none",
|
|
1482
|
+
SINGLE: "single",
|
|
1483
|
+
SOME: "some"
|
|
1484
|
+
};
|
|
1485
|
+
function isPlainObject(v) {
|
|
1486
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
1487
|
+
}
|
|
1488
|
+
function and(parts) {
|
|
1489
|
+
const ps = parts.filter((p) => p !== void 0);
|
|
1490
|
+
if (ps.length === 0) return void 0;
|
|
1491
|
+
if (ps.length === 1) return ps[0];
|
|
1492
|
+
return ps.map((p) => `(${p})`).join(" AND ");
|
|
1493
|
+
}
|
|
1494
|
+
function encodeValue(attr, value) {
|
|
1495
|
+
if (value === null || value === void 0) return null;
|
|
1496
|
+
if (Array.isArray(value)) return value.map((v) => encodeValue(attr, v));
|
|
1497
|
+
if (attr.kind === "scalar" && attr.type.name === "Int" && typeof value === "number") {
|
|
1498
|
+
return neo4j.int(value);
|
|
1499
|
+
}
|
|
1500
|
+
return value;
|
|
1501
|
+
}
|
|
1502
|
+
function castValue(attr, expr, isList) {
|
|
1503
|
+
if (attr.kind === "scalar" && attr.type.name === "DateTime") {
|
|
1504
|
+
return isList ? `[x IN ${expr} | datetime(x)]` : `datetime(${expr})`;
|
|
1505
|
+
}
|
|
1506
|
+
return expr;
|
|
1507
|
+
}
|
|
1508
|
+
function valueExpr(ctx, attr, value, isList) {
|
|
1509
|
+
return castValue(attr, ctx.param(encodeValue(attr, value)), isList);
|
|
1510
|
+
}
|
|
1511
|
+
function attributePredicate(ctx, expr, attr, op, value) {
|
|
1512
|
+
if (value === void 0) return void 0;
|
|
1513
|
+
if (op === "eq" && value === null) return `${expr} IS NULL`;
|
|
1514
|
+
if (value === null) return void 0;
|
|
1515
|
+
if (attr.type.list) {
|
|
1516
|
+
switch (op) {
|
|
1517
|
+
case "eq":
|
|
1518
|
+
return `${expr} = ${valueExpr(ctx, attr, value, true)}`;
|
|
1519
|
+
case "includes":
|
|
1520
|
+
return `${valueExpr(ctx, attr, value, false)} IN ${expr}`;
|
|
1521
|
+
}
|
|
1522
|
+
throw new Error(`Unsupported list filter operator ${op}`);
|
|
1523
|
+
}
|
|
1524
|
+
switch (op) {
|
|
1525
|
+
case "eq":
|
|
1526
|
+
return `${expr} = ${valueExpr(ctx, attr, value, false)}`;
|
|
1527
|
+
case "in":
|
|
1528
|
+
return `${expr} IN ${valueExpr(ctx, attr, value, true)}`;
|
|
1529
|
+
case "contains":
|
|
1530
|
+
return `${expr} CONTAINS ${valueExpr(ctx, attr, value, false)}`;
|
|
1531
|
+
case "startsWith":
|
|
1532
|
+
return `${expr} STARTS WITH ${valueExpr(ctx, attr, value, false)}`;
|
|
1533
|
+
case "endsWith":
|
|
1534
|
+
return `${expr} ENDS WITH ${valueExpr(ctx, attr, value, false)}`;
|
|
1535
|
+
case "lt":
|
|
1536
|
+
return `${expr} < ${valueExpr(ctx, attr, value, false)}`;
|
|
1537
|
+
case "lte":
|
|
1538
|
+
return `${expr} <= ${valueExpr(ctx, attr, value, false)}`;
|
|
1539
|
+
case "gt":
|
|
1540
|
+
return `${expr} > ${valueExpr(ctx, attr, value, false)}`;
|
|
1541
|
+
case "gte":
|
|
1542
|
+
return `${expr} >= ${valueExpr(ctx, attr, value, false)}`;
|
|
1543
|
+
}
|
|
1544
|
+
throw new Error(`Unsupported filter operator ${op}`);
|
|
1545
|
+
}
|
|
1546
|
+
function attributeFilter(ctx, variable, attributes, key, value) {
|
|
1547
|
+
const direct = attributes.find((a) => a.name === key);
|
|
1548
|
+
if (direct) {
|
|
1549
|
+
if (value === null || value === void 0) return { handled: true };
|
|
1550
|
+
if (direct.cypher) throw notImplemented(`filtering on @cypher field ${key}`, FOLLOW_UP.cypher);
|
|
1551
|
+
const expr = `${variable}.${q(direct.property)}`;
|
|
1552
|
+
const preds = Object.entries(value).map(
|
|
1553
|
+
([op, v]) => attributePredicate(ctx, expr, direct, op, v)
|
|
1554
|
+
);
|
|
1555
|
+
return { handled: true, predicate: and(preds) };
|
|
1556
|
+
}
|
|
1557
|
+
const m = /^(.+)_([A-Z_]+)$/.exec(key);
|
|
1558
|
+
if (m) {
|
|
1559
|
+
const attr = attributes.find((a) => a.name === m[1]);
|
|
1560
|
+
const op = LEGACY_OPERATORS[m[2]];
|
|
1561
|
+
if (attr && op) {
|
|
1562
|
+
if (attr.cypher)
|
|
1563
|
+
throw notImplemented(`filtering on @cypher field ${attr.name}`, FOLLOW_UP.cypher);
|
|
1564
|
+
return {
|
|
1565
|
+
handled: true,
|
|
1566
|
+
predicate: attributePredicate(ctx, `${variable}.${q(attr.property)}`, attr, op, value)
|
|
1567
|
+
};
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
return { handled: false };
|
|
1571
|
+
}
|
|
1572
|
+
function logical(where, key, compile) {
|
|
1573
|
+
const value = where[key];
|
|
1574
|
+
if (key === "AND" || key === "OR") {
|
|
1575
|
+
if (!Array.isArray(value)) return { handled: true };
|
|
1576
|
+
const parts = value.filter(isPlainObject).map(compile);
|
|
1577
|
+
if (key === "AND") return { handled: true, predicate: and(parts) };
|
|
1578
|
+
if (parts.length === 0) return { handled: true };
|
|
1579
|
+
if (parts.some((p) => p === void 0)) return { handled: true, predicate: "true" };
|
|
1580
|
+
return {
|
|
1581
|
+
handled: true,
|
|
1582
|
+
predicate: parts.length === 1 ? parts[0] : parts.map((p) => `(${p})`).join(" OR ")
|
|
1583
|
+
};
|
|
1584
|
+
}
|
|
1585
|
+
if (key === "NOT") {
|
|
1586
|
+
if (!isPlainObject(value)) return { handled: true };
|
|
1587
|
+
const inner = compile(value);
|
|
1588
|
+
return { handled: true, predicate: inner === void 0 ? void 0 : `NOT (${inner})` };
|
|
1589
|
+
}
|
|
1590
|
+
return { handled: false };
|
|
1591
|
+
}
|
|
1592
|
+
function relationshipPattern(model, from, rel, to, relVar = "") {
|
|
1593
|
+
const target = model.node(rel.target);
|
|
1594
|
+
const edge = `[${relVar}:${q(rel.type)}]`;
|
|
1595
|
+
const end = `(${to}${labels(target.labels)})`;
|
|
1596
|
+
return rel.direction === "OUT" ? `(${from})-${edge}->${end}` : `(${from})<-${edge}-${end}`;
|
|
1597
|
+
}
|
|
1598
|
+
function quantified(pattern, quantifier, predicate) {
|
|
1599
|
+
if (predicate === void 0) return void 0;
|
|
1600
|
+
switch (quantifier) {
|
|
1601
|
+
case "some":
|
|
1602
|
+
return `EXISTS { MATCH ${pattern} WHERE ${predicate} }`;
|
|
1603
|
+
case "none":
|
|
1604
|
+
return `NOT EXISTS { MATCH ${pattern} WHERE ${predicate} }`;
|
|
1605
|
+
case "single":
|
|
1606
|
+
return `COUNT { MATCH ${pattern} WHERE ${predicate} } = 1`;
|
|
1607
|
+
case "all":
|
|
1608
|
+
return `EXISTS { MATCH ${pattern} } AND NOT EXISTS { MATCH ${pattern} WHERE NOT (${predicate}) }`;
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
var AGGREGATION_COMPARISON = {
|
|
1612
|
+
EQ: "eq",
|
|
1613
|
+
EQUAL: "eq",
|
|
1614
|
+
GT: "gt",
|
|
1615
|
+
GTE: "gte",
|
|
1616
|
+
LT: "lt",
|
|
1617
|
+
LTE: "lte"
|
|
1618
|
+
};
|
|
1619
|
+
var GENERIC_AGGREGATES = {
|
|
1620
|
+
average: "avg",
|
|
1621
|
+
averageLength: "avg",
|
|
1622
|
+
min: "min",
|
|
1623
|
+
shortest: "min",
|
|
1624
|
+
shortestLength: "min",
|
|
1625
|
+
max: "max",
|
|
1626
|
+
longest: "max",
|
|
1627
|
+
longestLength: "max",
|
|
1628
|
+
sum: "sum"
|
|
1629
|
+
};
|
|
1630
|
+
var LEGACY_AGGREGATES = {
|
|
1631
|
+
AVERAGE: "avg",
|
|
1632
|
+
MIN: "min",
|
|
1633
|
+
SHORTEST: "min",
|
|
1634
|
+
MAX: "max",
|
|
1635
|
+
LONGEST: "max",
|
|
1636
|
+
SUM: "sum"
|
|
1637
|
+
};
|
|
1638
|
+
var COMPARISON_OPERATORS = {
|
|
1639
|
+
eq: "=",
|
|
1640
|
+
gt: ">",
|
|
1641
|
+
gte: ">=",
|
|
1642
|
+
lt: "<",
|
|
1643
|
+
lte: "<="
|
|
1644
|
+
};
|
|
1645
|
+
function comparison(ctx, expr, op, value, attr) {
|
|
1646
|
+
if (value === void 0 || value === null) return void 0;
|
|
1647
|
+
const cmp = COMPARISON_OPERATORS[op];
|
|
1648
|
+
if (!cmp) throw new Error(`Invalid aggregation filter operator ${op}`);
|
|
1649
|
+
const p = ctx.param(value);
|
|
1650
|
+
const isDateTime2 = attr?.kind === "scalar" && attr.type.name === "DateTime";
|
|
1651
|
+
return `${expr} ${cmp} ${isDateTime2 ? `datetime(${p})` : p}`;
|
|
1652
|
+
}
|
|
1653
|
+
var WhereCompiler = class {
|
|
1654
|
+
constructor(model, ctx, onTraverse = () => {
|
|
1655
|
+
}) {
|
|
1656
|
+
this.model = model;
|
|
1657
|
+
this.ctx = ctx;
|
|
1658
|
+
this.onTraverse = onTraverse;
|
|
1659
|
+
}
|
|
1660
|
+
model;
|
|
1661
|
+
ctx;
|
|
1662
|
+
onTraverse;
|
|
1663
|
+
/** Predicate for a `${Node}Where` input on `variable`, or `undefined` when it filters nothing. */
|
|
1664
|
+
node(variable, node, where) {
|
|
1665
|
+
if (!isPlainObject(where)) return void 0;
|
|
1666
|
+
const parts = [];
|
|
1667
|
+
for (const [key, value] of Object.entries(where)) {
|
|
1668
|
+
if (value === void 0) continue;
|
|
1669
|
+
const l = logical(where, key, (w) => this.node(variable, node, w));
|
|
1670
|
+
if (l.handled) {
|
|
1671
|
+
parts.push(l.predicate);
|
|
1672
|
+
continue;
|
|
1673
|
+
}
|
|
1674
|
+
const a = attributeFilter(this.ctx, variable, node.attributes, key, value);
|
|
1675
|
+
if (a.handled) {
|
|
1676
|
+
parts.push(a.predicate);
|
|
1677
|
+
continue;
|
|
1678
|
+
}
|
|
1679
|
+
parts.push(this.relationshipFilter(variable, node, key, value));
|
|
1680
|
+
}
|
|
1681
|
+
return and(parts);
|
|
1682
|
+
}
|
|
1683
|
+
relationshipFilter(variable, node, key, value) {
|
|
1684
|
+
const find = (name) => node.relationships.find((r) => r.name === name);
|
|
1685
|
+
let rel = find(key);
|
|
1686
|
+
if (rel) {
|
|
1687
|
+
if (!isPlainObject(value)) return void 0;
|
|
1688
|
+
return and(
|
|
1689
|
+
Object.entries(value).map(([q2, w]) => this.related(variable, rel, q2, w))
|
|
1690
|
+
);
|
|
1691
|
+
}
|
|
1692
|
+
if (key.endsWith("Connection") && (rel = find(key.slice(0, -"Connection".length)))) {
|
|
1693
|
+
if (!isPlainObject(value)) return void 0;
|
|
1694
|
+
return and(
|
|
1695
|
+
Object.entries(value).map(([q2, w]) => {
|
|
1696
|
+
if (q2 === "aggregate") return this.aggregate(variable, rel, w, false);
|
|
1697
|
+
return this.relatedConnection(variable, rel, q2, w);
|
|
1698
|
+
})
|
|
1699
|
+
);
|
|
1700
|
+
}
|
|
1701
|
+
if (key.endsWith("Aggregate") && (rel = find(key.slice(0, -"Aggregate".length)))) {
|
|
1702
|
+
return this.aggregate(variable, rel, value, true);
|
|
1703
|
+
}
|
|
1704
|
+
const m = /^(.+)_(ALL|NONE|SINGLE|SOME)$/.exec(key);
|
|
1705
|
+
if (m) {
|
|
1706
|
+
const quantifier = QUANTIFIER_KEYS[m[2]];
|
|
1707
|
+
if (rel = find(m[1])) return this.related(variable, rel, quantifier, value);
|
|
1708
|
+
if (m[1].endsWith("Connection") && (rel = find(m[1].slice(0, -"Connection".length)))) {
|
|
1709
|
+
return this.relatedConnection(variable, rel, quantifier, value);
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1712
|
+
throw new Error(`Unknown filter ${node.name}Where.${key}`);
|
|
1713
|
+
}
|
|
1714
|
+
related(variable, rel, quantifier, where) {
|
|
1715
|
+
if (!isPlainObject(where)) return void 0;
|
|
1716
|
+
const m = this.ctx.variable("n");
|
|
1717
|
+
const target = this.model.node(rel.target);
|
|
1718
|
+
this.onTraverse(target);
|
|
1719
|
+
return quantified(
|
|
1720
|
+
relationshipPattern(this.model, variable, rel, m),
|
|
1721
|
+
quantifier,
|
|
1722
|
+
this.node(m, target, where)
|
|
1723
|
+
);
|
|
1724
|
+
}
|
|
1725
|
+
relatedConnection(variable, rel, quantifier, where) {
|
|
1726
|
+
if (!isPlainObject(where)) return void 0;
|
|
1727
|
+
const m = this.ctx.variable("n");
|
|
1728
|
+
const r = this.ctx.variable("r");
|
|
1729
|
+
this.onTraverse(this.model.node(rel.target));
|
|
1730
|
+
return quantified(
|
|
1731
|
+
relationshipPattern(this.model, variable, rel, m, r),
|
|
1732
|
+
quantifier,
|
|
1733
|
+
this.connection(r, m, rel, where)
|
|
1734
|
+
);
|
|
1735
|
+
}
|
|
1736
|
+
/**
|
|
1737
|
+
* Predicate for a `${Source}${Rel}ConnectionAggregateInput` (`deprecated`: `${…}AggregateInput`,
|
|
1738
|
+
* the `actorsAggregate` form): `count`, `node`, `edge`, combined with AND / OR / NOT.
|
|
1739
|
+
*/
|
|
1740
|
+
aggregate(variable, rel, where, deprecated) {
|
|
1741
|
+
if (!isPlainObject(where)) return void 0;
|
|
1742
|
+
const target = this.model.node(rel.target);
|
|
1743
|
+
this.onTraverse(target);
|
|
1744
|
+
const m = this.ctx.variable("n");
|
|
1745
|
+
const r = this.ctx.variable("r");
|
|
1746
|
+
const pattern = relationshipPattern(this.model, variable, rel, m, r);
|
|
1747
|
+
const scope = { pattern, nodeVar: m, relVar: r };
|
|
1748
|
+
const compile = (w) => {
|
|
1749
|
+
const parts = [];
|
|
1750
|
+
for (const [key, value] of Object.entries(w)) {
|
|
1751
|
+
if (value === void 0 || value === null) continue;
|
|
1752
|
+
const l = logical(w, key, compile);
|
|
1753
|
+
if (l.handled) {
|
|
1754
|
+
parts.push(l.predicate);
|
|
1755
|
+
continue;
|
|
1756
|
+
}
|
|
1757
|
+
if (key === "count") {
|
|
1758
|
+
if (!isPlainObject(value)) continue;
|
|
1759
|
+
if (deprecated) {
|
|
1760
|
+
parts.push(this.countFilter(scope, false, value));
|
|
1761
|
+
continue;
|
|
1762
|
+
}
|
|
1763
|
+
for (const [what, filters] of Object.entries(value)) {
|
|
1764
|
+
if (!isPlainObject(filters)) continue;
|
|
1765
|
+
if (what === "nodes") parts.push(this.countFilter(scope, true, filters));
|
|
1766
|
+
else if (what === "edges") parts.push(this.countFilter(scope, false, filters));
|
|
1767
|
+
else throw new Error(`Unknown aggregation count filter ${what}`);
|
|
1768
|
+
}
|
|
1769
|
+
continue;
|
|
1770
|
+
}
|
|
1771
|
+
const legacyCount = /^count_(EQ|GT|GTE|LT|LTE)$/.exec(key);
|
|
1772
|
+
if (legacyCount) {
|
|
1773
|
+
parts.push(
|
|
1774
|
+
this.countFilter(scope, false, {
|
|
1775
|
+
[AGGREGATION_COMPARISON[legacyCount[1]]]: value
|
|
1776
|
+
})
|
|
1777
|
+
);
|
|
1778
|
+
continue;
|
|
1779
|
+
}
|
|
1780
|
+
if (key === "node") {
|
|
1781
|
+
parts.push(this.aggregationWhere(scope, target.attributes, "node", !deprecated, value));
|
|
1782
|
+
continue;
|
|
1783
|
+
}
|
|
1784
|
+
if (key === "edge") {
|
|
1785
|
+
const props = this.model.properties.get(rel.properties ?? "");
|
|
1786
|
+
if (!props) throw new Error(`Unknown aggregation filter ${key}`);
|
|
1787
|
+
parts.push(this.aggregationWhere(scope, props.attributes, "edge", false, value));
|
|
1788
|
+
continue;
|
|
1789
|
+
}
|
|
1790
|
+
throw new Error(`Unknown aggregation filter ${key}`);
|
|
1791
|
+
}
|
|
1792
|
+
return and(parts);
|
|
1793
|
+
};
|
|
1794
|
+
return compile(where);
|
|
1795
|
+
}
|
|
1796
|
+
/** `count` filters: `COUNT { … } >= $p` (one row per relationship, or per distinct node). */
|
|
1797
|
+
countFilter(scope, distinct, filters) {
|
|
1798
|
+
const count = distinct ? `COUNT { MATCH ${scope.pattern} WITH DISTINCT ${scope.nodeVar} RETURN ${scope.nodeVar} }` : `COUNT { MATCH ${scope.pattern} }`;
|
|
1799
|
+
return and(
|
|
1800
|
+
Object.entries(filters).map(([op, v]) => comparison(this.ctx, count, op, v, void 0))
|
|
1801
|
+
);
|
|
1802
|
+
}
|
|
1803
|
+
/** `${…}NodeAggregationWhereInput` / `${Properties}AggregationWhereInput`. */
|
|
1804
|
+
aggregationWhere(scope, attributes, on, distinct, where) {
|
|
1805
|
+
if (!isPlainObject(where)) return void 0;
|
|
1806
|
+
const parts = [];
|
|
1807
|
+
for (const [key, value] of Object.entries(where)) {
|
|
1808
|
+
if (value === void 0 || value === null) continue;
|
|
1809
|
+
const l = logical(
|
|
1810
|
+
where,
|
|
1811
|
+
key,
|
|
1812
|
+
(w) => this.aggregationWhere(scope, attributes, on, distinct, w)
|
|
1813
|
+
);
|
|
1814
|
+
if (l.handled) {
|
|
1815
|
+
parts.push(l.predicate);
|
|
1816
|
+
continue;
|
|
1817
|
+
}
|
|
1818
|
+
const direct = attributes.find((a) => a.name === key);
|
|
1819
|
+
if (direct) {
|
|
1820
|
+
if (!isPlainObject(value)) continue;
|
|
1821
|
+
for (const [aggOp, filters] of Object.entries(value)) {
|
|
1822
|
+
if (!isPlainObject(filters)) continue;
|
|
1823
|
+
const fn = GENERIC_AGGREGATES[aggOp];
|
|
1824
|
+
if (!fn) throw new Error(`Invalid aggregation operator ${aggOp}`);
|
|
1825
|
+
const agg2 = this.aggregated(scope, direct, on, distinct, fn);
|
|
1826
|
+
for (const [op, v] of Object.entries(filters)) {
|
|
1827
|
+
parts.push(comparison(this.ctx, agg2, op, v, direct));
|
|
1828
|
+
}
|
|
1829
|
+
}
|
|
1830
|
+
continue;
|
|
1831
|
+
}
|
|
1832
|
+
const m = /^(.+?)_(AVERAGE|MAX|MIN|SUM|SHORTEST|LONGEST)(?:_LENGTH)?_(EQUAL|GT|GTE|LT|LTE)$/.exec(
|
|
1833
|
+
key
|
|
1834
|
+
);
|
|
1835
|
+
const attr = m && attributes.find((a) => a.name === m[1]);
|
|
1836
|
+
if (!m || !attr) throw new Error(`Unknown aggregation filter ${key}`);
|
|
1837
|
+
const agg = this.aggregated(scope, attr, on, distinct, LEGACY_AGGREGATES[m[2]]);
|
|
1838
|
+
parts.push(comparison(this.ctx, agg, AGGREGATION_COMPARISON[m[3]], value, attr));
|
|
1839
|
+
}
|
|
1840
|
+
return and(parts);
|
|
1841
|
+
}
|
|
1842
|
+
/** `min` / `max` / … of the related values (`COLLECT { MATCH … RETURN n.born }`); strings: `size()`. */
|
|
1843
|
+
aggregated(scope, attr, on, distinct, fn) {
|
|
1844
|
+
const v = on === "node" ? scope.nodeVar : scope.relVar;
|
|
1845
|
+
const prop = `${v}.${q(attr.property)}`;
|
|
1846
|
+
const expr = attr.kind === "scalar" && attr.type.name === "String" ? `size(${prop})` : prop;
|
|
1847
|
+
const dedupe = distinct ? ` WITH DISTINCT ${v}` : "";
|
|
1848
|
+
const list2 = `COLLECT { MATCH ${scope.pattern}${dedupe} WITH ${v} WHERE ${prop} IS NOT NULL RETURN ${expr} }`;
|
|
1849
|
+
return withList(list2, this.ctx.variable("list"), (l) => listAggregate(fn, l));
|
|
1850
|
+
}
|
|
1851
|
+
/** Predicate for a `${Source}${Rel}ConnectionWhere` input (`node` / `edge`, AND / OR / NOT). */
|
|
1852
|
+
connection(relVar, nodeVar, rel, where) {
|
|
1853
|
+
if (!isPlainObject(where)) return void 0;
|
|
1854
|
+
const parts = [];
|
|
1855
|
+
for (const [key, value] of Object.entries(where)) {
|
|
1856
|
+
if (value === void 0) continue;
|
|
1857
|
+
const l = logical(where, key, (w) => this.connection(relVar, nodeVar, rel, w));
|
|
1858
|
+
if (l.handled) {
|
|
1859
|
+
parts.push(l.predicate);
|
|
1860
|
+
continue;
|
|
1861
|
+
}
|
|
1862
|
+
if (key === "node") {
|
|
1863
|
+
parts.push(this.node(nodeVar, this.model.node(rel.target), value));
|
|
1864
|
+
continue;
|
|
1865
|
+
}
|
|
1866
|
+
if (key === "edge") {
|
|
1867
|
+
const props = this.model.properties.get(rel.properties ?? "");
|
|
1868
|
+
if (props) parts.push(this.edge(relVar, props, value));
|
|
1869
|
+
continue;
|
|
1870
|
+
}
|
|
1871
|
+
throw new Error(`Unknown connection filter ${key}`);
|
|
1872
|
+
}
|
|
1873
|
+
return and(parts);
|
|
1874
|
+
}
|
|
1875
|
+
/** Predicate for a `${Properties}Where` input on a relationship variable. */
|
|
1876
|
+
edge(relVar, props, where) {
|
|
1877
|
+
if (!isPlainObject(where)) return void 0;
|
|
1878
|
+
const parts = [];
|
|
1879
|
+
for (const [key, value] of Object.entries(where)) {
|
|
1880
|
+
if (value === void 0) continue;
|
|
1881
|
+
const l = logical(where, key, (w) => this.edge(relVar, props, w));
|
|
1882
|
+
if (l.handled) {
|
|
1883
|
+
parts.push(l.predicate);
|
|
1884
|
+
continue;
|
|
1885
|
+
}
|
|
1886
|
+
const a = attributeFilter(this.ctx, relVar, props.attributes, key, value);
|
|
1887
|
+
if (!a.handled) throw new Error(`Unknown filter ${props.name}Where.${key}`);
|
|
1888
|
+
parts.push(a.predicate);
|
|
1889
|
+
}
|
|
1890
|
+
return and(parts);
|
|
1891
|
+
}
|
|
1892
|
+
};
|
|
1893
|
+
|
|
1894
|
+
// src/v7/cypher/select.ts
|
|
1895
|
+
var CURSOR_PREFIX = "arrayconnection:";
|
|
1896
|
+
function offsetToCursor(offset) {
|
|
1897
|
+
return Buffer.from(`${CURSOR_PREFIX}${offset}`, "utf8").toString("base64");
|
|
1898
|
+
}
|
|
1899
|
+
function cursorToOffset(cursor) {
|
|
1900
|
+
if (typeof cursor !== "string") return void 0;
|
|
1901
|
+
const decoded = Buffer.from(cursor, "base64").toString("utf8");
|
|
1902
|
+
if (!decoded.startsWith(CURSOR_PREFIX)) return void 0;
|
|
1903
|
+
const n = Number(decoded.slice(CURSOR_PREFIX.length));
|
|
1904
|
+
return Number.isInteger(n) && n >= 0 ? n : void 0;
|
|
1905
|
+
}
|
|
1906
|
+
function collectFields(info, sets, out = /* @__PURE__ */ new Map()) {
|
|
1907
|
+
for (const set of sets) {
|
|
1908
|
+
for (const sel of set?.selections ?? []) {
|
|
1909
|
+
const skip = getDirectiveValues(GraphQLSkipDirective, sel, info.variableValues);
|
|
1910
|
+
if (skip?.if === true) continue;
|
|
1911
|
+
const include = getDirectiveValues(GraphQLIncludeDirective, sel, info.variableValues);
|
|
1912
|
+
if (include?.if === false) continue;
|
|
1913
|
+
if (sel.kind === Kind4.FIELD) {
|
|
1914
|
+
const key = sel.alias?.value ?? sel.name.value;
|
|
1915
|
+
const list2 = out.get(key) ?? [];
|
|
1916
|
+
list2.push(sel);
|
|
1917
|
+
out.set(key, list2);
|
|
1918
|
+
} else if (sel.kind === Kind4.INLINE_FRAGMENT) {
|
|
1919
|
+
collectFields(info, [sel.selectionSet], out);
|
|
1920
|
+
} else {
|
|
1921
|
+
const frag = info.fragments[sel.name.value];
|
|
1922
|
+
if (frag) collectFields(info, [frag.selectionSet], out);
|
|
1923
|
+
}
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1926
|
+
return out;
|
|
1927
|
+
}
|
|
1928
|
+
function subSelections(nodes) {
|
|
1929
|
+
return nodes.map((n) => n.selectionSet);
|
|
1930
|
+
}
|
|
1931
|
+
function objectType(info, name) {
|
|
1932
|
+
return info.schema.getType(name);
|
|
1933
|
+
}
|
|
1934
|
+
function fieldArgs(field, node, info) {
|
|
1935
|
+
return getArgumentValues(field, node, info.variableValues);
|
|
1936
|
+
}
|
|
1937
|
+
function mapValue(v, f) {
|
|
1938
|
+
if (v === null || v === void 0) return null;
|
|
1939
|
+
return Array.isArray(v) ? v.map(f) : f(v);
|
|
1940
|
+
}
|
|
1941
|
+
function integerToNumber(x) {
|
|
1942
|
+
return isInt(x) ? x.toNumber() : x;
|
|
1943
|
+
}
|
|
1944
|
+
function attributeDecoder(a) {
|
|
1945
|
+
if (a.kind === "scalar" && a.type.name === "BigInt") {
|
|
1946
|
+
return (v) => mapValue(v, (x) => isInt(x) ? x.toString() : x);
|
|
1947
|
+
}
|
|
1948
|
+
if (a.kind === "scalar" && (a.type.name === "Int" || a.type.name === "Float")) {
|
|
1949
|
+
return (v) => mapValue(v, integerToNumber);
|
|
1950
|
+
}
|
|
1951
|
+
return (v) => v ?? null;
|
|
1952
|
+
}
|
|
1953
|
+
function toNumber(v) {
|
|
1954
|
+
return isInt(v) ? v.toNumber() : Number(v);
|
|
1955
|
+
}
|
|
1956
|
+
function intParam(ctx, value) {
|
|
1957
|
+
if (typeof value !== "number") return void 0;
|
|
1958
|
+
return ctx.param(neo4j2.int(Math.max(0, Math.trunc(value))));
|
|
1959
|
+
}
|
|
1960
|
+
function paging(ctx, offset, limit) {
|
|
1961
|
+
const parts = [];
|
|
1962
|
+
const o = intParam(ctx, offset);
|
|
1963
|
+
if (o) parts.push(`SKIP ${o}`);
|
|
1964
|
+
const l = intParam(ctx, limit);
|
|
1965
|
+
if (l) parts.push(`LIMIT ${l}`);
|
|
1966
|
+
return parts.join(" ");
|
|
1967
|
+
}
|
|
1968
|
+
function withClause(vars, order, page) {
|
|
1969
|
+
if (!order && !page) return "";
|
|
1970
|
+
return ["WITH", vars, order, page].filter(Boolean).join(" ");
|
|
1971
|
+
}
|
|
1972
|
+
var AGGREGATE_FUNCTIONS = {
|
|
1973
|
+
min: "min",
|
|
1974
|
+
max: "max",
|
|
1975
|
+
average: "avg",
|
|
1976
|
+
sum: "sum"
|
|
1977
|
+
};
|
|
1978
|
+
function aggregateValueDecoder(type) {
|
|
1979
|
+
if (type === "Int" || type === "Float") return (v) => mapValue(v, integerToNumber);
|
|
1980
|
+
if (type === "BigInt") return (v) => mapValue(v, (x) => isInt(x) ? x.toString() : x);
|
|
1981
|
+
return (v) => v ?? null;
|
|
1982
|
+
}
|
|
1983
|
+
function mapDecoder(decoders) {
|
|
1984
|
+
return (raw) => {
|
|
1985
|
+
const r = raw ?? {};
|
|
1986
|
+
const out = {};
|
|
1987
|
+
for (const [key, dec] of decoders) out[key] = dec(r[key]);
|
|
1988
|
+
return out;
|
|
1989
|
+
};
|
|
1990
|
+
}
|
|
1991
|
+
var SelectionCompiler = class {
|
|
1992
|
+
constructor(model, info) {
|
|
1993
|
+
this.model = model;
|
|
1994
|
+
this.info = info;
|
|
1995
|
+
this.where = new WhereCompiler(model, this.ctx, (n) => this.assertReadable(n));
|
|
1996
|
+
}
|
|
1997
|
+
model;
|
|
1998
|
+
info;
|
|
1999
|
+
ctx = new CypherContext();
|
|
2000
|
+
where;
|
|
2001
|
+
assertReadable(node) {
|
|
2002
|
+
if (readNeedsAuth(node)) {
|
|
2003
|
+
throw notImplemented(
|
|
2004
|
+
`reading ${node.name}, which has @authentication / @authorization rules`,
|
|
2005
|
+
FOLLOW_UP.authorization
|
|
2006
|
+
);
|
|
2007
|
+
}
|
|
2008
|
+
}
|
|
2009
|
+
sortItems(variable, attributes, sort, owner) {
|
|
2010
|
+
const items = [];
|
|
2011
|
+
if (sort === null || typeof sort !== "object") return items;
|
|
2012
|
+
for (const [field, dir] of Object.entries(sort)) {
|
|
2013
|
+
if (dir !== "ASC" && dir !== "DESC") continue;
|
|
2014
|
+
const a = attributes.find((x) => x.name === field);
|
|
2015
|
+
if (!a) throw new Error(`Unknown sort field ${owner}.${field}`);
|
|
2016
|
+
if (a.cypher)
|
|
2017
|
+
throw notImplemented(`sorting on @cypher field ${owner}.${field}`, FOLLOW_UP.cypher);
|
|
2018
|
+
items.push(`${variable}.${q(a.property)} ${dir}`);
|
|
2019
|
+
}
|
|
2020
|
+
return items;
|
|
2021
|
+
}
|
|
2022
|
+
nodeOrder(variable, node, sort) {
|
|
2023
|
+
const items = (Array.isArray(sort) ? sort : []).flatMap(
|
|
2024
|
+
(s) => this.sortItems(variable, node.attributes, s, node.name)
|
|
2025
|
+
);
|
|
2026
|
+
return items.length ? `ORDER BY ${items.join(", ")}` : "";
|
|
2027
|
+
}
|
|
2028
|
+
connectionOrder(relVar, nodeVar, rel, sort) {
|
|
2029
|
+
const target = this.model.node(rel.target);
|
|
2030
|
+
const props = this.props(rel);
|
|
2031
|
+
const items = [];
|
|
2032
|
+
for (const s of Array.isArray(sort) ? sort : []) {
|
|
2033
|
+
if (s === null || typeof s !== "object") continue;
|
|
2034
|
+
for (const [k, v] of Object.entries(s)) {
|
|
2035
|
+
if (k === "node") items.push(...this.sortItems(nodeVar, target.attributes, v, target.name));
|
|
2036
|
+
else if (k === "edge" && props)
|
|
2037
|
+
items.push(...this.sortItems(relVar, props.attributes, v, props.name));
|
|
2038
|
+
}
|
|
2039
|
+
}
|
|
2040
|
+
return items.length ? `ORDER BY ${items.join(", ")}` : "";
|
|
2041
|
+
}
|
|
2042
|
+
props(rel) {
|
|
2043
|
+
return rel.properties ? this.model.properties.get(rel.properties) : void 0;
|
|
2044
|
+
}
|
|
2045
|
+
/** `{ key: expr, … }` for a selection on a node variable, and its decoder. */
|
|
2046
|
+
projectNode(variable, node, fieldNodes) {
|
|
2047
|
+
this.assertReadable(node);
|
|
2048
|
+
const type = objectType(this.info, node.name);
|
|
2049
|
+
const gqlFields = type.getFields();
|
|
2050
|
+
const entries = [];
|
|
2051
|
+
const decoders = [];
|
|
2052
|
+
for (const [key, nodes] of collectFields(this.info, subSelections(fieldNodes))) {
|
|
2053
|
+
const name = nodes[0].name.value;
|
|
2054
|
+
if (name === "__typename") continue;
|
|
2055
|
+
const attr = node.attributes.find((a) => a.name === name);
|
|
2056
|
+
if (attr) {
|
|
2057
|
+
if (attr.cypher)
|
|
2058
|
+
throw notImplemented(`@cypher field ${node.name}.${name}`, FOLLOW_UP.cypher);
|
|
2059
|
+
entries.push(`${q(key)}: ${variable}.${q(attr.property)}`);
|
|
2060
|
+
decoders.push([key, attributeDecoder(attr)]);
|
|
2061
|
+
continue;
|
|
2062
|
+
}
|
|
2063
|
+
const gqlField = gqlFields[name];
|
|
2064
|
+
if (!gqlField) throw new Error(`Unknown field ${node.name}.${name}`);
|
|
2065
|
+
const args = fieldArgs(gqlField, nodes[0], this.info);
|
|
2066
|
+
const rel = node.relationships.find((r) => r.name === name);
|
|
2067
|
+
if (rel) {
|
|
2068
|
+
const p = this.relationshipList(variable, rel, args, nodes);
|
|
2069
|
+
entries.push(`${q(key)}: ${p.expr}`);
|
|
2070
|
+
decoders.push([key, p.decode]);
|
|
2071
|
+
continue;
|
|
2072
|
+
}
|
|
2073
|
+
const connRel = name.endsWith("Connection") ? node.relationships.find((r) => `${r.name}Connection` === name) : void 0;
|
|
2074
|
+
if (connRel) {
|
|
2075
|
+
const p = this.relationshipConnection(variable, connRel, args, nodes);
|
|
2076
|
+
entries.push(`${q(key)}: ${p.expr}`);
|
|
2077
|
+
decoders.push([key, p.decode]);
|
|
2078
|
+
continue;
|
|
2079
|
+
}
|
|
2080
|
+
throw new Error(`Unknown field ${node.name}.${name}`);
|
|
2081
|
+
}
|
|
2082
|
+
return {
|
|
2083
|
+
expr: `{ ${entries.join(", ")} }`,
|
|
2084
|
+
decode: (raw) => {
|
|
2085
|
+
const r = raw ?? {};
|
|
2086
|
+
const out = {};
|
|
2087
|
+
for (const [key, dec] of decoders) out[key] = dec(r[key]);
|
|
2088
|
+
return out;
|
|
2089
|
+
}
|
|
2090
|
+
};
|
|
2091
|
+
}
|
|
2092
|
+
projectProperties(relVar, props, fieldNodes) {
|
|
2093
|
+
const entries = [];
|
|
2094
|
+
const decoders = [];
|
|
2095
|
+
for (const [key, nodes] of collectFields(this.info, subSelections(fieldNodes))) {
|
|
2096
|
+
const name = nodes[0].name.value;
|
|
2097
|
+
if (name === "__typename") continue;
|
|
2098
|
+
const attr = props.attributes.find((a) => a.name === name);
|
|
2099
|
+
if (!attr) throw new Error(`Unknown field ${props.name}.${name}`);
|
|
2100
|
+
entries.push(`${q(key)}: ${relVar}.${q(attr.property)}`);
|
|
2101
|
+
decoders.push([key, attributeDecoder(attr)]);
|
|
2102
|
+
}
|
|
2103
|
+
return {
|
|
2104
|
+
expr: `{ ${entries.join(", ")} }`,
|
|
2105
|
+
decode: (raw) => {
|
|
2106
|
+
const r = raw ?? {};
|
|
2107
|
+
const out = {};
|
|
2108
|
+
for (const [key, dec] of decoders) out[key] = dec(r[key]);
|
|
2109
|
+
return out;
|
|
2110
|
+
}
|
|
2111
|
+
};
|
|
2112
|
+
}
|
|
2113
|
+
relationshipList(variable, rel, args, fieldNodes) {
|
|
2114
|
+
const target = this.model.node(rel.target);
|
|
2115
|
+
const m = this.ctx.variable("this");
|
|
2116
|
+
const pattern = relationshipPattern(this.model, variable, rel, m);
|
|
2117
|
+
const pred = this.where.node(m, target, args.where);
|
|
2118
|
+
const order = this.nodeOrder(m, target, args.sort);
|
|
2119
|
+
const page = paging(this.ctx, args.offset, args.limit);
|
|
2120
|
+
const inner = this.projectNode(m, target, fieldNodes);
|
|
2121
|
+
const body = [
|
|
2122
|
+
`MATCH ${pattern}`,
|
|
2123
|
+
pred ? `WHERE ${pred}` : "",
|
|
2124
|
+
withClause(m, order, page),
|
|
2125
|
+
`RETURN ${inner.expr}`
|
|
2126
|
+
].filter(Boolean).join(" ");
|
|
2127
|
+
return {
|
|
2128
|
+
expr: `COLLECT { ${body} }`,
|
|
2129
|
+
decode: (raw) => Array.isArray(raw) ? raw.map(inner.decode) : []
|
|
2130
|
+
};
|
|
2131
|
+
}
|
|
2132
|
+
/**
|
|
2133
|
+
* A connection over `match` (a pattern binding `nodeVar` and, for relationships, `relVar`):
|
|
2134
|
+
* `{ total: COUNT { … }, edges: COLLECT { … } }` and the decoder that builds edges, cursors and
|
|
2135
|
+
* `pageInfo` from the selection.
|
|
2136
|
+
*/
|
|
2137
|
+
connection(opts) {
|
|
2138
|
+
const afterOffset = cursorToOffset(opts.args.after);
|
|
2139
|
+
const offset = afterOffset === void 0 ? 0 : afterOffset + 1;
|
|
2140
|
+
const conn = collectFields(this.info, subSelections(opts.fieldNodes));
|
|
2141
|
+
const edgeEntries = [];
|
|
2142
|
+
const edgeDecoders = [];
|
|
2143
|
+
const edgeFieldNodes = [];
|
|
2144
|
+
const aggregates = [];
|
|
2145
|
+
const aggregateEntries = [];
|
|
2146
|
+
let needsTotal = false;
|
|
2147
|
+
let needsEdges = false;
|
|
2148
|
+
const where = opts.predicate ? ` WHERE ${opts.predicate}` : "";
|
|
2149
|
+
for (const [key, nodes] of conn) {
|
|
2150
|
+
const name = nodes[0].name.value;
|
|
2151
|
+
if (name === "aggregate") {
|
|
2152
|
+
const p = this.aggregate(
|
|
2153
|
+
{
|
|
2154
|
+
base: `MATCH ${opts.match}${where}`,
|
|
2155
|
+
nodeVar: opts.nodeVar,
|
|
2156
|
+
relVar: opts.relVar,
|
|
2157
|
+
node: opts.node,
|
|
2158
|
+
props: opts.props,
|
|
2159
|
+
owner: opts.owner
|
|
2160
|
+
},
|
|
2161
|
+
nodes
|
|
2162
|
+
);
|
|
2163
|
+
aggregateEntries.push(`${q(key)}: ${p.expr}`);
|
|
2164
|
+
aggregates.push([key, p.decode]);
|
|
2165
|
+
}
|
|
2166
|
+
if (name === "edges") edgeFieldNodes.push(...nodes);
|
|
2167
|
+
if (name === "edges" || name === "pageInfo") needsEdges = true;
|
|
2168
|
+
if (name === "totalCount" || name === "pageInfo") needsTotal = true;
|
|
2169
|
+
}
|
|
2170
|
+
for (const [key, nodes] of collectFields(this.info, subSelections(edgeFieldNodes))) {
|
|
2171
|
+
const name = nodes[0].name.value;
|
|
2172
|
+
if (name === "cursor") {
|
|
2173
|
+
edgeDecoders.push([key, (_raw, i) => offsetToCursor(offset + i)]);
|
|
2174
|
+
} else if (name === "node") {
|
|
2175
|
+
const p = opts.projectNode(nodes);
|
|
2176
|
+
edgeEntries.push(`${q(key)}: ${p.expr}`);
|
|
2177
|
+
edgeDecoders.push([key, (raw) => p.decode(raw[key])]);
|
|
2178
|
+
} else if (name === "properties" && opts.projectProperties) {
|
|
2179
|
+
const p = opts.projectProperties(nodes);
|
|
2180
|
+
edgeEntries.push(`${q(key)}: ${p.expr}`);
|
|
2181
|
+
edgeDecoders.push([key, (raw) => p.decode(raw[key])]);
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
const withVars = opts.relVar ? `${opts.relVar}, ${opts.nodeVar}` : opts.nodeVar;
|
|
2185
|
+
const page = paging(this.ctx, offset || void 0, opts.args.first);
|
|
2186
|
+
const edgesBody = [
|
|
2187
|
+
`MATCH ${opts.match}${where}`,
|
|
2188
|
+
withClause(withVars, opts.order, page),
|
|
2189
|
+
`RETURN { ${edgeEntries.join(", ")} }`
|
|
2190
|
+
].filter(Boolean).join(" ");
|
|
2191
|
+
const parts = [];
|
|
2192
|
+
if (needsTotal) parts.push(`total: COUNT { MATCH ${opts.match}${where} }`);
|
|
2193
|
+
if (needsEdges) parts.push(`edges: COLLECT { ${edgesBody} }`);
|
|
2194
|
+
if (aggregateEntries.length) parts.push(`aggregate: { ${aggregateEntries.join(", ")} }`);
|
|
2195
|
+
const expr = `{ ${parts.join(", ")} }`;
|
|
2196
|
+
return {
|
|
2197
|
+
expr,
|
|
2198
|
+
decode: (raw) => {
|
|
2199
|
+
const r = raw ?? {};
|
|
2200
|
+
const total = toNumber(r.total ?? 0);
|
|
2201
|
+
const rawEdges = Array.isArray(r.edges) ? r.edges : [];
|
|
2202
|
+
const edges = rawEdges.map((e, i) => {
|
|
2203
|
+
const out2 = {};
|
|
2204
|
+
for (const [key, dec] of edgeDecoders) out2[key] = dec(e ?? {}, i);
|
|
2205
|
+
return out2;
|
|
2206
|
+
});
|
|
2207
|
+
const out = {};
|
|
2208
|
+
for (const [key, nodes] of conn) {
|
|
2209
|
+
const name = nodes[0].name.value;
|
|
2210
|
+
if (name === "totalCount") out[key] = total;
|
|
2211
|
+
else if (name === "edges") out[key] = edges;
|
|
2212
|
+
else if (name === "aggregate") {
|
|
2213
|
+
const agg = r.aggregate ?? {};
|
|
2214
|
+
out[key] = aggregates.find(([k]) => k === key)[1](agg[key]);
|
|
2215
|
+
} else if (name === "pageInfo") {
|
|
2216
|
+
const info = {};
|
|
2217
|
+
for (const [pk, pn] of collectFields(this.info, subSelections(nodes))) {
|
|
2218
|
+
switch (pn[0].name.value) {
|
|
2219
|
+
case "hasNextPage":
|
|
2220
|
+
info[pk] = offset + edges.length < total;
|
|
2221
|
+
break;
|
|
2222
|
+
case "hasPreviousPage":
|
|
2223
|
+
info[pk] = offset > 0;
|
|
2224
|
+
break;
|
|
2225
|
+
case "startCursor":
|
|
2226
|
+
info[pk] = edges.length ? offsetToCursor(offset) : null;
|
|
2227
|
+
break;
|
|
2228
|
+
case "endCursor":
|
|
2229
|
+
info[pk] = edges.length ? offsetToCursor(offset + edges.length - 1) : null;
|
|
2230
|
+
break;
|
|
2231
|
+
}
|
|
2232
|
+
}
|
|
2233
|
+
out[key] = info;
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
2236
|
+
return out;
|
|
2237
|
+
}
|
|
2238
|
+
};
|
|
2239
|
+
}
|
|
2240
|
+
/**
|
|
2241
|
+
* `{ count: …, node: { field: … }, edge: { field: … } }` for a connection `aggregate` selection:
|
|
2242
|
+
* one `COUNT { … }` per count and one `COLLECT { … }` of the values per field (reduced with list
|
|
2243
|
+
* expressions, see `listAggregate`), like v7's one subquery per field.
|
|
2244
|
+
*/
|
|
2245
|
+
aggregate(scope, fieldNodes) {
|
|
2246
|
+
const entries = [];
|
|
2247
|
+
const decoders = [];
|
|
2248
|
+
for (const [key, nodes] of collectFields(this.info, subSelections(fieldNodes))) {
|
|
2249
|
+
const name = nodes[0].name.value;
|
|
2250
|
+
if (name === "__typename") continue;
|
|
2251
|
+
if (name === "count") {
|
|
2252
|
+
const counts = [];
|
|
2253
|
+
const keys = [];
|
|
2254
|
+
for (const [ck, cn] of collectFields(this.info, subSelections(nodes))) {
|
|
2255
|
+
const what = cn[0].name.value;
|
|
2256
|
+
const v = what === "nodes" ? scope.nodeVar : what === "edges" ? scope.relVar : void 0;
|
|
2257
|
+
if (!v) continue;
|
|
2258
|
+
counts.push(`${q(ck)}: COUNT { ${scope.base} WITH DISTINCT ${v} RETURN ${v} }`);
|
|
2259
|
+
keys.push(ck);
|
|
2260
|
+
}
|
|
2261
|
+
entries.push(`${q(key)}: { ${counts.join(", ")} }`);
|
|
2262
|
+
decoders.push([
|
|
2263
|
+
key,
|
|
2264
|
+
(raw) => {
|
|
2265
|
+
const r = raw ?? {};
|
|
2266
|
+
return Object.fromEntries(keys.map((k) => [k, toNumber(r[k] ?? 0)]));
|
|
2267
|
+
}
|
|
2268
|
+
]);
|
|
2269
|
+
continue;
|
|
2270
|
+
}
|
|
2271
|
+
const isEdge = name === "edge";
|
|
2272
|
+
if (name !== "node" && !isEdge)
|
|
2273
|
+
throw new Error(`Unknown field ${scope.owner}.aggregate.${name}`);
|
|
2274
|
+
const variable = isEdge ? scope.relVar : scope.nodeVar;
|
|
2275
|
+
const attributes = isEdge ? scope.props?.attributes : scope.node.attributes;
|
|
2276
|
+
if (!variable || !attributes)
|
|
2277
|
+
throw new Error(`Unknown field ${scope.owner}.aggregate.${name}`);
|
|
2278
|
+
this.assertReadable(scope.node);
|
|
2279
|
+
const fieldEntries = [];
|
|
2280
|
+
const fieldDecoders = [];
|
|
2281
|
+
for (const [fk, fn] of collectFields(this.info, subSelections(nodes))) {
|
|
2282
|
+
const field = fn[0].name.value;
|
|
2283
|
+
if (field === "__typename") continue;
|
|
2284
|
+
const attr = attributes.find((a) => a.name === field);
|
|
2285
|
+
if (!attr) throw new Error(`Unknown field ${scope.owner}.aggregate.${name}.${field}`);
|
|
2286
|
+
const p = this.aggregateAttribute(scope.base, variable, attr, fn);
|
|
2287
|
+
fieldEntries.push(`${q(fk)}: ${p.expr}`);
|
|
2288
|
+
fieldDecoders.push([fk, p.decode]);
|
|
2289
|
+
}
|
|
2290
|
+
entries.push(`${q(key)}: { ${fieldEntries.join(", ")} }`);
|
|
2291
|
+
decoders.push([key, mapDecoder(fieldDecoders)]);
|
|
2292
|
+
}
|
|
2293
|
+
return { expr: `{ ${entries.join(", ")} }`, decode: mapDecoder(decoders) };
|
|
2294
|
+
}
|
|
2295
|
+
/** `min` / `max` / `average` / `sum` / `shortest` / `longest` of one attribute, v7 semantics. */
|
|
2296
|
+
aggregateAttribute(base, variable, attr, fieldNodes) {
|
|
2297
|
+
const prop = `${variable}.${q(attr.property)}`;
|
|
2298
|
+
const type = attr.type.name;
|
|
2299
|
+
const ops = [];
|
|
2300
|
+
for (const [k, n] of collectFields(this.info, subSelections(fieldNodes))) {
|
|
2301
|
+
const op = n[0].name.value;
|
|
2302
|
+
if (op !== "__typename") ops.push([k, op]);
|
|
2303
|
+
}
|
|
2304
|
+
if (ops.length === 0) return { expr: "{}", decode: () => ({}) };
|
|
2305
|
+
const decoders = ops.map(([k]) => [k, aggregateValueDecoder(type)]);
|
|
2306
|
+
const l = this.ctx.variable("list");
|
|
2307
|
+
const values = `${base} WITH DISTINCT ${variable} WHERE ${prop} IS NOT NULL`;
|
|
2308
|
+
if (type === "String") {
|
|
2309
|
+
const list3 = `COLLECT { ${values} WITH ${variable} ORDER BY size(${prop}) DESC RETURN ${prop} }`;
|
|
2310
|
+
const items2 = ops.map(
|
|
2311
|
+
([k, op]) => `${q(k)}: ${op === "longest" ? `head(${l})` : op === "shortest" ? `last(${l})` : "null"}`
|
|
2312
|
+
);
|
|
2313
|
+
return {
|
|
2314
|
+
expr: withList(list3, l, () => `{ ${items2.join(", ")} }`),
|
|
2315
|
+
decode: mapDecoder(decoders)
|
|
2316
|
+
};
|
|
2317
|
+
}
|
|
2318
|
+
const list2 = `COLLECT { ${values} RETURN ${prop} }`;
|
|
2319
|
+
const items = ops.map(([k, op]) => {
|
|
2320
|
+
const fn = AGGREGATE_FUNCTIONS[op];
|
|
2321
|
+
return `${q(k)}: ${fn ? listAggregate(fn, l) : "null"}`;
|
|
2322
|
+
});
|
|
2323
|
+
return {
|
|
2324
|
+
expr: withList(list2, l, () => `{ ${items.join(", ")} }`),
|
|
2325
|
+
decode: mapDecoder(decoders)
|
|
2326
|
+
};
|
|
2327
|
+
}
|
|
2328
|
+
relationshipConnection(variable, rel, args, fieldNodes) {
|
|
2329
|
+
const target = this.model.node(rel.target);
|
|
2330
|
+
this.assertReadable(target);
|
|
2331
|
+
const m = this.ctx.variable("this");
|
|
2332
|
+
const r = this.ctx.variable("edge");
|
|
2333
|
+
const props = this.props(rel);
|
|
2334
|
+
return this.connection({
|
|
2335
|
+
match: relationshipPattern(this.model, variable, rel, m, r),
|
|
2336
|
+
predicate: this.where.connection(r, m, rel, args.where),
|
|
2337
|
+
order: this.connectionOrder(r, m, rel, args.sort),
|
|
2338
|
+
nodeVar: m,
|
|
2339
|
+
relVar: r,
|
|
2340
|
+
projectNode: (nodes) => this.projectNode(m, target, nodes),
|
|
2341
|
+
projectProperties: props ? (nodes) => this.projectProperties(r, props, nodes) : void 0,
|
|
2342
|
+
node: target,
|
|
2343
|
+
props,
|
|
2344
|
+
args,
|
|
2345
|
+
fieldNodes,
|
|
2346
|
+
owner: `${rel.source}.${rel.name}Connection`
|
|
2347
|
+
});
|
|
2348
|
+
}
|
|
2349
|
+
/** `movies(where, sort, limit, offset)`. */
|
|
2350
|
+
rootList(node, args, fieldNodes) {
|
|
2351
|
+
this.assertReadable(node);
|
|
2352
|
+
const v = this.ctx.variable("this");
|
|
2353
|
+
const pred = this.where.node(v, node, args.where);
|
|
2354
|
+
const order = this.nodeOrder(v, node, args.sort);
|
|
2355
|
+
const page = paging(this.ctx, args.offset, args.limit);
|
|
2356
|
+
const proj = this.projectNode(v, node, fieldNodes);
|
|
2357
|
+
const cypher = [
|
|
2358
|
+
`MATCH (${v}${labels(node.labels)})`,
|
|
2359
|
+
pred ? `WHERE ${pred}` : "",
|
|
2360
|
+
withClause(v, order, page),
|
|
2361
|
+
`RETURN ${proj.expr} AS this`
|
|
2362
|
+
].filter(Boolean).join("\n");
|
|
2363
|
+
return { cypher, params: this.ctx.params, decode: (rows) => rows.map(proj.decode) };
|
|
2364
|
+
}
|
|
2365
|
+
/** `moviesConnection(where, sort, first, after)`. */
|
|
2366
|
+
rootConnection(node, args, fieldNodes) {
|
|
2367
|
+
this.assertReadable(node);
|
|
2368
|
+
const v = this.ctx.variable("this");
|
|
2369
|
+
const c = this.connection({
|
|
2370
|
+
match: `(${v}${labels(node.labels)})`,
|
|
2371
|
+
predicate: this.where.node(v, node, args.where),
|
|
2372
|
+
order: this.nodeOrder(v, node, args.sort),
|
|
2373
|
+
nodeVar: v,
|
|
2374
|
+
projectNode: (nodes) => this.projectNode(v, node, nodes),
|
|
2375
|
+
node,
|
|
2376
|
+
args,
|
|
2377
|
+
fieldNodes,
|
|
2378
|
+
owner: `${node.plural}Connection`
|
|
2379
|
+
});
|
|
2380
|
+
return {
|
|
2381
|
+
cypher: `RETURN ${c.expr} AS this`,
|
|
2382
|
+
params: this.ctx.params,
|
|
2383
|
+
decode: (rows) => c.decode(rows[0])
|
|
2384
|
+
};
|
|
2385
|
+
}
|
|
2386
|
+
};
|
|
2387
|
+
|
|
2388
|
+
// src/v7/cypher/mutate.ts
|
|
2389
|
+
import { GraphQLError as GraphQLError3 } from "graphql";
|
|
2390
|
+
import { isInt as isInt2 } from "neo4j-driver";
|
|
2391
|
+
var COUNTER_KEYS = {
|
|
2392
|
+
nodesCreated: "nc",
|
|
2393
|
+
nodesDeleted: "nd",
|
|
2394
|
+
relationshipsCreated: "rc",
|
|
2395
|
+
relationshipsDeleted: "rd"
|
|
2396
|
+
};
|
|
2397
|
+
var ALL_COUNTERS = ["nc", "nd", "rc", "rd"];
|
|
2398
|
+
var ELEMENT_OPERATIONS = ["update", "create", "connect", "delete", "disconnect"];
|
|
2399
|
+
var LEGACY_UPDATE_OPERATORS = {
|
|
2400
|
+
SET: "set",
|
|
2401
|
+
PUSH: "push",
|
|
2402
|
+
POP: "pop",
|
|
2403
|
+
INCREMENT: "add",
|
|
2404
|
+
DECREMENT: "subtract",
|
|
2405
|
+
ADD: "add",
|
|
2406
|
+
SUBTRACT: "subtract",
|
|
2407
|
+
MULTIPLY: "multiply",
|
|
2408
|
+
DIVIDE: "divide"
|
|
2409
|
+
};
|
|
2410
|
+
function isPlainObject2(v) {
|
|
2411
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
2412
|
+
}
|
|
2413
|
+
function asList(v) {
|
|
2414
|
+
if (v === null || v === void 0) return [];
|
|
2415
|
+
return Array.isArray(v) ? v : [v];
|
|
2416
|
+
}
|
|
2417
|
+
var Block = class {
|
|
2418
|
+
clauses = [];
|
|
2419
|
+
terms = { nc: [], nd: [], rc: [], rd: [] };
|
|
2420
|
+
/** Per row: lists of the error messages of failed checks (see `checkExpr`). */
|
|
2421
|
+
errors = [];
|
|
2422
|
+
add(clause) {
|
|
2423
|
+
this.clauses.push(clause);
|
|
2424
|
+
}
|
|
2425
|
+
count(counter, term) {
|
|
2426
|
+
this.terms[counter].push(term);
|
|
2427
|
+
}
|
|
2428
|
+
/** Checks evaluated on each row after the writes: `CASE WHEN … THEN <message> END`. */
|
|
2429
|
+
check(checks) {
|
|
2430
|
+
if (checks.length) this.errors.push(`[x IN [${checks.join(", ")}] WHERE x IS NOT NULL]`);
|
|
2431
|
+
}
|
|
2432
|
+
hasCounts() {
|
|
2433
|
+
return this.errors.length > 0 || ALL_COUNTERS.some((k) => this.terms[k].length > 0);
|
|
2434
|
+
}
|
|
2435
|
+
/** `{ nc: sum(…), …, errors: … }` over the rows of the block (`aggregate`), or of its one row. */
|
|
2436
|
+
aggregate(aggregate = true) {
|
|
2437
|
+
const total = (k) => this.terms[k].join(" + ") || "0";
|
|
2438
|
+
const items = ALL_COUNTERS.map((k) => `${k}: ${aggregate ? `sum(${total(k)})` : total(k)}`);
|
|
2439
|
+
if (this.errors.length) {
|
|
2440
|
+
const errors = this.errors.join(" + ");
|
|
2441
|
+
items.push(
|
|
2442
|
+
`errors: ${aggregate ? `reduce(acc = [], l IN collect(${errors}) | acc + l)` : errors}`
|
|
2443
|
+
);
|
|
2444
|
+
}
|
|
2445
|
+
return `{ ${items.join(", ")} }`;
|
|
2446
|
+
}
|
|
2447
|
+
};
|
|
2448
|
+
function indent(lines) {
|
|
2449
|
+
return lines.join("\n").split("\n").map((l) => ` ${l}`).join("\n");
|
|
2450
|
+
}
|
|
2451
|
+
function edgePattern(from, rel, relVar, to) {
|
|
2452
|
+
const edge = `[${relVar}:${q(rel.type)}]`;
|
|
2453
|
+
return rel.direction === "OUT" ? `(${from})-${edge}->(${to})` : `(${from})<-${edge}-(${to})`;
|
|
2454
|
+
}
|
|
2455
|
+
function generatedValue(a) {
|
|
2456
|
+
if (a.id) return "randomUUID()";
|
|
2457
|
+
return a.type.name === "Date" ? "date()" : "datetime()";
|
|
2458
|
+
}
|
|
2459
|
+
function onCreateGenerated(variable, attributes) {
|
|
2460
|
+
return attributes.filter((a) => !a.cypher && (a.id || a.timestamp?.includes("CREATE"))).map((a) => `${variable}.${q(a.property)} = ${generatedValue(a)}`);
|
|
2461
|
+
}
|
|
2462
|
+
function onUpdateGenerated(variable, attributes) {
|
|
2463
|
+
return attributes.filter((a) => !a.cypher && !a.id && a.timestamp?.includes("UPDATE")).map((a) => `${variable}.${q(a.property)} = ${generatedValue(a)}`);
|
|
2464
|
+
}
|
|
2465
|
+
function decodeCounts(fields, counts) {
|
|
2466
|
+
return Object.fromEntries(
|
|
2467
|
+
fields.filter(([, f]) => f in COUNTER_KEYS).map(([k, f]) => {
|
|
2468
|
+
const v = counts[COUNTER_KEYS[f]] ?? 0;
|
|
2469
|
+
return [k, isInt2(v) ? v.toNumber() : Number(v)];
|
|
2470
|
+
})
|
|
2471
|
+
);
|
|
2472
|
+
}
|
|
2473
|
+
var MutationCompiler = class {
|
|
2474
|
+
constructor(model, info) {
|
|
2475
|
+
this.model = model;
|
|
2476
|
+
this.info = info;
|
|
2477
|
+
this.select = new SelectionCompiler(model, info);
|
|
2478
|
+
this.ctx = this.select.ctx;
|
|
2479
|
+
this.where = new WhereCompiler(model, this.ctx, (n) => this.select.assertReadable(n));
|
|
2480
|
+
}
|
|
2481
|
+
model;
|
|
2482
|
+
info;
|
|
2483
|
+
select;
|
|
2484
|
+
where;
|
|
2485
|
+
ctx;
|
|
2486
|
+
assertWritable(node) {
|
|
2487
|
+
if (node.auth.authorization || node.auth.authentication?.length) {
|
|
2488
|
+
throw notImplemented(
|
|
2489
|
+
`writing ${node.name}, which has @authentication / @authorization rules`,
|
|
2490
|
+
FOLLOW_UP.authorization
|
|
2491
|
+
);
|
|
2492
|
+
}
|
|
2493
|
+
}
|
|
2494
|
+
props(rel) {
|
|
2495
|
+
return rel.properties ? this.model.properties.get(rel.properties) : void 0;
|
|
2496
|
+
}
|
|
2497
|
+
relationship(node, name) {
|
|
2498
|
+
const rel = node.relationships.find((r) => r.name === name);
|
|
2499
|
+
if (!rel) throw new Error(`Unknown relationship ${node.name}.${name}`);
|
|
2500
|
+
return rel;
|
|
2501
|
+
}
|
|
2502
|
+
/** Runs `inner` once per row of `outer` (`CALL (imports) { … }`) and adds its counts. */
|
|
2503
|
+
call(outer, imports, inner) {
|
|
2504
|
+
if (outer.clauses.length) outer.add("WITH *");
|
|
2505
|
+
if (!inner.hasCounts()) {
|
|
2506
|
+
outer.add(`CALL (${imports.join(", ")}) {
|
|
2507
|
+
${indent(inner.clauses)}
|
|
2508
|
+
}`);
|
|
2509
|
+
return;
|
|
2510
|
+
}
|
|
2511
|
+
const c = this.ctx.variable("count");
|
|
2512
|
+
outer.add(
|
|
2513
|
+
`CALL (${imports.join(", ")}) {
|
|
2514
|
+
${indent(inner.clauses)}
|
|
2515
|
+
RETURN ${inner.aggregate()} AS ${c}
|
|
2516
|
+
}`
|
|
2517
|
+
);
|
|
2518
|
+
for (const k of ALL_COUNTERS) if (inner.terms[k].length) outer.count(k, `${c}.${k}`);
|
|
2519
|
+
if (inner.errors.length) outer.errors.push(`${c}.errors`);
|
|
2520
|
+
}
|
|
2521
|
+
/** `SET` items for the attribute keys of a create input. */
|
|
2522
|
+
createAssignments(variable, attributes, input, owner, relationships = []) {
|
|
2523
|
+
const sets = [];
|
|
2524
|
+
if (!isPlainObject2(input)) return sets;
|
|
2525
|
+
for (const [key, value] of Object.entries(input)) {
|
|
2526
|
+
if (value === void 0 || relationships.some((r) => r.name === key)) continue;
|
|
2527
|
+
const a = attributes.find((x) => x.name === key);
|
|
2528
|
+
if (!a) throw new Error(`Unknown field ${owner}CreateInput.${key}`);
|
|
2529
|
+
sets.push(`${variable}.${q(a.property)} = ${valueExpr(this.ctx, a, value, a.type.list)}`);
|
|
2530
|
+
}
|
|
2531
|
+
return sets;
|
|
2532
|
+
}
|
|
2533
|
+
/** `SET` items for the scalar operators of an update input (`{ set }`, `{ add }`, `title_SET`, …). */
|
|
2534
|
+
updateAssignments(variable, attributes, input, owner, checks, relationships = []) {
|
|
2535
|
+
if (!isPlainObject2(input)) return [];
|
|
2536
|
+
const byAttribute = /* @__PURE__ */ new Map();
|
|
2537
|
+
for (const [key, value] of Object.entries(input)) {
|
|
2538
|
+
if (value === void 0 || relationships.some((r) => r.name === key)) continue;
|
|
2539
|
+
let attr = attributes.find((a) => a.name === key);
|
|
2540
|
+
let ops;
|
|
2541
|
+
if (attr) {
|
|
2542
|
+
if (!isPlainObject2(value)) continue;
|
|
2543
|
+
ops = Object.entries(value).filter(([, v]) => v !== void 0).map(([op, v]) => [op, op, v]);
|
|
2544
|
+
} else {
|
|
2545
|
+
const m = /^(.+)_([A-Z]+)$/.exec(key);
|
|
2546
|
+
attr = m ? attributes.find((a) => a.name === m[1]) : void 0;
|
|
2547
|
+
const op = m ? LEGACY_UPDATE_OPERATORS[m[2]] : void 0;
|
|
2548
|
+
if (!attr || !op) throw new Error(`Unknown field ${owner}UpdateInput.${key}`);
|
|
2549
|
+
ops = [[op, m[2].toLowerCase(), value]];
|
|
2550
|
+
}
|
|
2551
|
+
const entry = byAttribute.get(attr) ?? { keys: [], ops: [] };
|
|
2552
|
+
entry.keys.push(key);
|
|
2553
|
+
entry.ops.push(...ops);
|
|
2554
|
+
byAttribute.set(attr, entry);
|
|
2555
|
+
}
|
|
2556
|
+
const sets = [];
|
|
2557
|
+
for (const [attr, { keys, ops }] of byAttribute) {
|
|
2558
|
+
if (keys.length > 1) {
|
|
2559
|
+
throw new GraphQLError3(
|
|
2560
|
+
`Conflicting modification of ${keys.map((k) => `[[${k}]]`).join(", ")} on type ${owner}`
|
|
2561
|
+
);
|
|
2562
|
+
}
|
|
2563
|
+
const prop = `${variable}.${q(attr.property)}`;
|
|
2564
|
+
for (const [op, label, value] of ops) {
|
|
2565
|
+
sets.push(`${prop} = ${this.updateExpr(prop, attr, op, value)}`);
|
|
2566
|
+
const check = this.checkExpr(prop, attr, op, label, value);
|
|
2567
|
+
if (check) checks.push(check);
|
|
2568
|
+
}
|
|
2569
|
+
}
|
|
2570
|
+
return sets;
|
|
2571
|
+
}
|
|
2572
|
+
/**
|
|
2573
|
+
* The v7 checks of an operator, evaluated on the written value (v7 runs them with APOC; here the
|
|
2574
|
+
* statement returns the messages and the transaction is rolled back): arithmetic on a missing
|
|
2575
|
+
* value, Int results beyond 32 bits, `push` / `pop` on a missing list.
|
|
2576
|
+
*/
|
|
2577
|
+
checkExpr(prop, attr, op, label, value) {
|
|
2578
|
+
const type = attr.type.name;
|
|
2579
|
+
if (op === "push" || op === "pop") {
|
|
2580
|
+
return `CASE WHEN ${prop} IS NULL THEN ${this.ctx.param(`Property ${attr.name} cannot be NULL`)} END`;
|
|
2581
|
+
}
|
|
2582
|
+
if (!["add", "subtract", "multiply", "divide"].includes(op)) return void 0;
|
|
2583
|
+
const shown = isInt2(value) ? value.toString() : type === "Float" && typeof value === "number" && Number.isInteger(value) ? `${value}.0` : String(value);
|
|
2584
|
+
const whens = [
|
|
2585
|
+
`WHEN ${prop} IS NULL THEN ${this.ctx.param(`Cannot ${label} ${shown} to Nan`)}`
|
|
2586
|
+
];
|
|
2587
|
+
if (type === "Int") {
|
|
2588
|
+
whens.push(
|
|
2589
|
+
`WHEN ${prop} > 2147483647 THEN ${this.ctx.param(`Overflow: Value returned from operator ${label} is larger than 32 bit`)}`
|
|
2590
|
+
);
|
|
2591
|
+
}
|
|
2592
|
+
return `CASE ${whens.join(" ")} END`;
|
|
2593
|
+
}
|
|
2594
|
+
updateExpr(prop, attr, op, value) {
|
|
2595
|
+
switch (op) {
|
|
2596
|
+
case "set":
|
|
2597
|
+
return valueExpr(this.ctx, attr, value, attr.type.list);
|
|
2598
|
+
case "push":
|
|
2599
|
+
return `${prop} + ${valueExpr(this.ctx, attr, asList(value), true)}`;
|
|
2600
|
+
case "pop":
|
|
2601
|
+
return `${prop}[0..-${this.ctx.param(encodeValue(intAttribute, value))}]`;
|
|
2602
|
+
case "add":
|
|
2603
|
+
return `(${prop} + ${valueExpr(this.ctx, attr, value, false)})`;
|
|
2604
|
+
case "subtract":
|
|
2605
|
+
return `(${prop} - ${valueExpr(this.ctx, attr, value, false)})`;
|
|
2606
|
+
case "multiply":
|
|
2607
|
+
return `(${prop} * ${valueExpr(this.ctx, attr, value, false)})`;
|
|
2608
|
+
case "divide":
|
|
2609
|
+
return `(${prop} / ${valueExpr(this.ctx, attr, value, false)})`;
|
|
2610
|
+
}
|
|
2611
|
+
throw new Error(`Unsupported update operator ${op}`);
|
|
2612
|
+
}
|
|
2613
|
+
// ---------------------------------------------------------------------------------------------
|
|
2614
|
+
// Create
|
|
2615
|
+
// ---------------------------------------------------------------------------------------------
|
|
2616
|
+
/** `CREATE (v:Label) SET …` and the nested writes of a `${Node}CreateInput`. */
|
|
2617
|
+
createNode(block, v, node, input, afterCreate) {
|
|
2618
|
+
this.assertWritable(node);
|
|
2619
|
+
block.add(`CREATE (${v}${labels(node.labels)})`);
|
|
2620
|
+
const sets = [
|
|
2621
|
+
...onCreateGenerated(v, node.attributes),
|
|
2622
|
+
...this.createAssignments(v, node.attributes, input, node.name, node.relationships)
|
|
2623
|
+
];
|
|
2624
|
+
if (sets.length) block.add(`SET ${sets.join(", ")}`);
|
|
2625
|
+
block.count("nc", "1");
|
|
2626
|
+
afterCreate?.();
|
|
2627
|
+
if (!isPlainObject2(input)) return;
|
|
2628
|
+
for (const rel of node.relationships) {
|
|
2629
|
+
const field = input[rel.name];
|
|
2630
|
+
if (!isPlainObject2(field)) continue;
|
|
2631
|
+
for (const el of asList(field.create)) this.nestedCreate(block, v, rel, el);
|
|
2632
|
+
for (const el of asList(field.connect)) this.connect(block, v, rel, el);
|
|
2633
|
+
}
|
|
2634
|
+
}
|
|
2635
|
+
/** `{ node, edge }` of a relationship `create`: a new related node and the edge to it. */
|
|
2636
|
+
nestedCreate(block, from, rel, el) {
|
|
2637
|
+
if (!isPlainObject2(el)) return;
|
|
2638
|
+
const target = this.model.node(rel.target);
|
|
2639
|
+
const inner = new Block();
|
|
2640
|
+
const t = this.ctx.variable("this");
|
|
2641
|
+
const r = this.ctx.variable("edge");
|
|
2642
|
+
this.createNode(inner, t, target, el.node, () => {
|
|
2643
|
+
inner.add(`CREATE ${edgePattern(from, rel, r, t)}`);
|
|
2644
|
+
const props = this.props(rel);
|
|
2645
|
+
if (props) {
|
|
2646
|
+
const sets = [
|
|
2647
|
+
...onCreateGenerated(r, props.attributes),
|
|
2648
|
+
...this.createAssignments(r, props.attributes, el.edge, props.name)
|
|
2649
|
+
];
|
|
2650
|
+
if (sets.length) inner.add(`SET ${sets.join(", ")}`);
|
|
2651
|
+
}
|
|
2652
|
+
inner.count("rc", "1");
|
|
2653
|
+
});
|
|
2654
|
+
this.call(block, [from], inner);
|
|
2655
|
+
}
|
|
2656
|
+
/** `{ where, edge, connect }`: an edge to every node matching `where` (then nested connects). */
|
|
2657
|
+
connect(block, from, rel, el) {
|
|
2658
|
+
if (!isPlainObject2(el)) return;
|
|
2659
|
+
const target = this.model.node(rel.target);
|
|
2660
|
+
this.assertWritable(target);
|
|
2661
|
+
const inner = new Block();
|
|
2662
|
+
const t = this.ctx.variable("this");
|
|
2663
|
+
const where = isPlainObject2(el.where) ? el.where.node : void 0;
|
|
2664
|
+
const pred = this.where.node(t, target, where);
|
|
2665
|
+
inner.add(`MATCH (${t}${labels(target.labels)})${pred ? ` WHERE ${pred}` : ""}`);
|
|
2666
|
+
for (const nested of asList(el.connect)) {
|
|
2667
|
+
if (!isPlainObject2(nested)) continue;
|
|
2668
|
+
for (const [name, els] of Object.entries(nested)) {
|
|
2669
|
+
const rel2 = this.relationship(target, name);
|
|
2670
|
+
for (const e of asList(els)) this.connect(inner, t, rel2, e);
|
|
2671
|
+
}
|
|
2672
|
+
}
|
|
2673
|
+
const r = this.ctx.variable("edge");
|
|
2674
|
+
inner.add(`CREATE ${edgePattern(from, rel, r, t)}`);
|
|
2675
|
+
const props = this.props(rel);
|
|
2676
|
+
if (props) {
|
|
2677
|
+
const sets = this.createAssignments(r, props.attributes, el.edge, props.name);
|
|
2678
|
+
if (sets.length) inner.add(`SET ${sets.join(", ")}`);
|
|
2679
|
+
}
|
|
2680
|
+
inner.count("rc", "1");
|
|
2681
|
+
this.call(block, [from], inner);
|
|
2682
|
+
}
|
|
2683
|
+
// ---------------------------------------------------------------------------------------------
|
|
2684
|
+
// Update
|
|
2685
|
+
// ---------------------------------------------------------------------------------------------
|
|
2686
|
+
/** The relationship operations of a `${Node}UpdateInput` on `v`. */
|
|
2687
|
+
updateRelationships(block, v, node, input) {
|
|
2688
|
+
if (!isPlainObject2(input)) return;
|
|
2689
|
+
for (const [key, value] of Object.entries(input)) {
|
|
2690
|
+
const rel = node.relationships.find((r) => r.name === key);
|
|
2691
|
+
if (!rel || value === null || value === void 0) continue;
|
|
2692
|
+
for (const el of asList(value)) {
|
|
2693
|
+
if (!isPlainObject2(el)) continue;
|
|
2694
|
+
for (const op of ELEMENT_OPERATIONS) {
|
|
2695
|
+
const arg3 = el[op];
|
|
2696
|
+
if (arg3 === null || arg3 === void 0) continue;
|
|
2697
|
+
switch (op) {
|
|
2698
|
+
case "update":
|
|
2699
|
+
this.nestedUpdate(block, v, rel, arg3);
|
|
2700
|
+
break;
|
|
2701
|
+
case "create":
|
|
2702
|
+
for (const e of asList(arg3)) this.nestedCreate(block, v, rel, e);
|
|
2703
|
+
break;
|
|
2704
|
+
case "connect":
|
|
2705
|
+
for (const e of asList(arg3)) this.connect(block, v, rel, e);
|
|
2706
|
+
break;
|
|
2707
|
+
case "delete":
|
|
2708
|
+
for (const e of asList(arg3)) this.nestedDelete(block, v, rel, e);
|
|
2709
|
+
break;
|
|
2710
|
+
case "disconnect":
|
|
2711
|
+
for (const e of asList(arg3)) this.disconnect(block, v, rel, e);
|
|
2712
|
+
break;
|
|
2713
|
+
}
|
|
2714
|
+
}
|
|
2715
|
+
}
|
|
2716
|
+
}
|
|
2717
|
+
}
|
|
2718
|
+
/** `{ where, node, edge }`: updates the related nodes (and edges) matching `where`. */
|
|
2719
|
+
nestedUpdate(block, from, rel, el) {
|
|
2720
|
+
if (!isPlainObject2(el)) return;
|
|
2721
|
+
const target = this.model.node(rel.target);
|
|
2722
|
+
this.assertWritable(target);
|
|
2723
|
+
const props = this.props(rel);
|
|
2724
|
+
const inner = new Block();
|
|
2725
|
+
const t = this.ctx.variable("this");
|
|
2726
|
+
const r = this.ctx.variable("edge");
|
|
2727
|
+
const pred = this.where.connection(r, t, rel, el.where);
|
|
2728
|
+
inner.add(
|
|
2729
|
+
`MATCH ${relationshipPattern(this.model, from, rel, t, r)}${pred ? ` WHERE ${pred}` : ""}`
|
|
2730
|
+
);
|
|
2731
|
+
const checks = [];
|
|
2732
|
+
const sets = [
|
|
2733
|
+
...onUpdateGenerated(t, target.attributes),
|
|
2734
|
+
...props ? onUpdateGenerated(r, props.attributes) : [],
|
|
2735
|
+
...this.updateAssignments(
|
|
2736
|
+
t,
|
|
2737
|
+
target.attributes,
|
|
2738
|
+
el.node,
|
|
2739
|
+
target.name,
|
|
2740
|
+
checks,
|
|
2741
|
+
target.relationships
|
|
2742
|
+
),
|
|
2743
|
+
...props ? this.updateAssignments(r, props.attributes, el.edge, props.name, checks) : []
|
|
2744
|
+
];
|
|
2745
|
+
if (sets.length) inner.add(`SET ${sets.join(", ")}`);
|
|
2746
|
+
inner.check(checks);
|
|
2747
|
+
this.updateRelationships(inner, t, target, el.node);
|
|
2748
|
+
if (!inner.hasCounts() && inner.clauses.length === 1) return;
|
|
2749
|
+
this.call(block, [from], inner);
|
|
2750
|
+
}
|
|
2751
|
+
/** `{ where, disconnect }`: deletes the matching relationships (then nested disconnects). */
|
|
2752
|
+
disconnect(block, from, rel, el) {
|
|
2753
|
+
if (!isPlainObject2(el)) return;
|
|
2754
|
+
const target = this.model.node(rel.target);
|
|
2755
|
+
this.assertWritable(target);
|
|
2756
|
+
const inner = new Block();
|
|
2757
|
+
const t = this.ctx.variable("this");
|
|
2758
|
+
const r = this.ctx.variable("edge");
|
|
2759
|
+
const pred = this.where.connection(r, t, rel, el.where);
|
|
2760
|
+
inner.add(
|
|
2761
|
+
`MATCH ${relationshipPattern(this.model, from, rel, t, r)}${pred ? ` WHERE ${pred}` : ""}`
|
|
2762
|
+
);
|
|
2763
|
+
if (isPlainObject2(el.disconnect)) {
|
|
2764
|
+
for (const [name, els] of Object.entries(el.disconnect)) {
|
|
2765
|
+
const rel2 = this.relationship(target, name);
|
|
2766
|
+
for (const e of asList(els)) this.disconnect(inner, t, rel2, e);
|
|
2767
|
+
}
|
|
2768
|
+
}
|
|
2769
|
+
if (inner.clauses.length > 1) inner.add("WITH *");
|
|
2770
|
+
inner.add(`DELETE ${r}`);
|
|
2771
|
+
inner.count("rd", "1");
|
|
2772
|
+
this.call(block, [from], inner);
|
|
2773
|
+
}
|
|
2774
|
+
// ---------------------------------------------------------------------------------------------
|
|
2775
|
+
// Delete
|
|
2776
|
+
// ---------------------------------------------------------------------------------------------
|
|
2777
|
+
/**
|
|
2778
|
+
* `COLLECT { … }` lists of the nodes a `{ where, delete }` element deletes: the related nodes
|
|
2779
|
+
* matching `where` and, through nested `delete`, nodes related to them. `match` is the chain of
|
|
2780
|
+
* `MATCH … WHERE …` that binds `t`.
|
|
2781
|
+
*/
|
|
2782
|
+
deleteLists(match, t, node, del) {
|
|
2783
|
+
this.assertWritable(node);
|
|
2784
|
+
const lists = [`COLLECT { ${match} RETURN DISTINCT ${t} }`];
|
|
2785
|
+
if (!isPlainObject2(del)) return lists;
|
|
2786
|
+
for (const [name, els] of Object.entries(del)) {
|
|
2787
|
+
const rel = this.relationship(node, name);
|
|
2788
|
+
const target = this.model.node(rel.target);
|
|
2789
|
+
for (const el of asList(els)) {
|
|
2790
|
+
if (!isPlainObject2(el)) continue;
|
|
2791
|
+
const u = this.ctx.variable("this");
|
|
2792
|
+
const r = this.ctx.variable("edge");
|
|
2793
|
+
const pred = this.where.connection(r, u, rel, el.where);
|
|
2794
|
+
const chain = `${match} MATCH ${relationshipPattern(this.model, t, rel, u, r)}${pred ? ` WHERE ${pred}` : ""}`;
|
|
2795
|
+
lists.push(...this.deleteLists(chain, u, target, el.delete));
|
|
2796
|
+
}
|
|
2797
|
+
}
|
|
2798
|
+
return lists;
|
|
2799
|
+
}
|
|
2800
|
+
/**
|
|
2801
|
+
* Deletes the distinct nodes of `list` with their relationships, counting both
|
|
2802
|
+
* (`WITH … AS deleted, COUNT { … } AS …`, then `FOREACH … DETACH DELETE`).
|
|
2803
|
+
*/
|
|
2804
|
+
deleteNodes(block, list2, keep) {
|
|
2805
|
+
const d = this.ctx.variable("deleted");
|
|
2806
|
+
const x = this.ctx.variable("node");
|
|
2807
|
+
const e = this.ctx.variable("rel");
|
|
2808
|
+
const n = this.ctx.variable("relCount");
|
|
2809
|
+
const kept = keep.length ? `${keep.join(", ")}, ` : "";
|
|
2810
|
+
block.add(`WITH ${kept}COLLECT { UNWIND ${list2} AS ${x} RETURN DISTINCT ${x} } AS ${d}`);
|
|
2811
|
+
block.add(
|
|
2812
|
+
`WITH ${kept}${d}, COUNT { UNWIND ${d} AS ${x} MATCH (${x})-[${e}]-() RETURN DISTINCT ${e} } AS ${n}`
|
|
2813
|
+
);
|
|
2814
|
+
block.add(`FOREACH (${x} IN ${d} | DETACH DELETE ${x})`);
|
|
2815
|
+
block.count("nd", `size(${d})`);
|
|
2816
|
+
block.count("rd", n);
|
|
2817
|
+
}
|
|
2818
|
+
/** `{ where, delete }` inside an update: deletes the matching related nodes. */
|
|
2819
|
+
nestedDelete(block, from, rel, el) {
|
|
2820
|
+
if (!isPlainObject2(el)) return;
|
|
2821
|
+
const target = this.model.node(rel.target);
|
|
2822
|
+
const t = this.ctx.variable("this");
|
|
2823
|
+
const r = this.ctx.variable("edge");
|
|
2824
|
+
const pred = this.where.connection(r, t, rel, el.where);
|
|
2825
|
+
const match = `MATCH ${relationshipPattern(this.model, from, rel, t, r)}${pred ? ` WHERE ${pred}` : ""}`;
|
|
2826
|
+
const lists = this.deleteLists(match, t, target, el.delete);
|
|
2827
|
+
const inner = new Block();
|
|
2828
|
+
this.deleteNodes(inner, `(${lists.join(" + ")})`, []);
|
|
2829
|
+
this.call(block, [from], inner);
|
|
2830
|
+
}
|
|
2831
|
+
// ---------------------------------------------------------------------------------------------
|
|
2832
|
+
// Root fields
|
|
2833
|
+
// ---------------------------------------------------------------------------------------------
|
|
2834
|
+
/**
|
|
2835
|
+
* `WITH <nodes> AS nodes, <info>`, the projections of the response's node list (one per response
|
|
2836
|
+
* key) and the decoder of the `{ info, <plural> }` response.
|
|
2837
|
+
*/
|
|
2838
|
+
response(block, nodes, info, node, fieldNodes) {
|
|
2839
|
+
const list2 = this.ctx.variable("nodes");
|
|
2840
|
+
block.add(`WITH ${nodes} AS ${list2}, ${info} AS info`);
|
|
2841
|
+
const entries = [];
|
|
2842
|
+
const decoders = [];
|
|
2843
|
+
for (const [key, nodesOfKey] of collectFields(this.info, subSelections(fieldNodes))) {
|
|
2844
|
+
const name = nodesOfKey[0].name.value;
|
|
2845
|
+
if (name === "info") {
|
|
2846
|
+
const fields = [...collectFields(this.info, subSelections(nodesOfKey))].map(
|
|
2847
|
+
([k, n]) => [k, n[0].name.value]
|
|
2848
|
+
);
|
|
2849
|
+
decoders.push([
|
|
2850
|
+
key,
|
|
2851
|
+
(raw) => {
|
|
2852
|
+
const counts = raw.info ?? {};
|
|
2853
|
+
return decodeCounts(fields, counts);
|
|
2854
|
+
}
|
|
2855
|
+
]);
|
|
2856
|
+
} else if (name === node.plural) {
|
|
2857
|
+
const v = this.ctx.variable("this");
|
|
2858
|
+
const d = this.ctx.variable("data");
|
|
2859
|
+
const proj = this.select.projectNode(v, node, nodesOfKey);
|
|
2860
|
+
block.add(
|
|
2861
|
+
`CALL (${list2}) {
|
|
2862
|
+
UNWIND ${list2} AS ${v}
|
|
2863
|
+
RETURN collect(${proj.expr}) AS ${d}
|
|
2864
|
+
}`
|
|
2865
|
+
);
|
|
2866
|
+
entries.push(`${q(key)}: ${d}`);
|
|
2867
|
+
decoders.push([
|
|
2868
|
+
key,
|
|
2869
|
+
(raw) => {
|
|
2870
|
+
const data2 = (raw.data ?? {})[key];
|
|
2871
|
+
return Array.isArray(data2) ? data2.map(proj.decode) : [];
|
|
2872
|
+
}
|
|
2873
|
+
]);
|
|
2874
|
+
}
|
|
2875
|
+
}
|
|
2876
|
+
const data = entries.length ? `{ ${entries.join(", ")} }` : "{}";
|
|
2877
|
+
block.add(`RETURN { info: info, data: ${data} } AS this`);
|
|
2878
|
+
return {
|
|
2879
|
+
cypher: block.clauses.join("\n"),
|
|
2880
|
+
params: this.ctx.params,
|
|
2881
|
+
decode: (rows) => {
|
|
2882
|
+
const raw = rows[0] ?? {};
|
|
2883
|
+
const errors = (raw.info ?? {}).errors;
|
|
2884
|
+
if (Array.isArray(errors) && errors.length) throw new GraphQLError3(String(errors[0]));
|
|
2885
|
+
return Object.fromEntries(decoders.map(([k, dec]) => [k, dec(raw)]));
|
|
2886
|
+
}
|
|
2887
|
+
};
|
|
2888
|
+
}
|
|
2889
|
+
/** `createMovies(input: [...])`. */
|
|
2890
|
+
rootCreate(node, args, fieldNodes) {
|
|
2891
|
+
this.assertWritable(node);
|
|
2892
|
+
const block = new Block();
|
|
2893
|
+
const groups = [];
|
|
2894
|
+
const inputs = asList(args.input);
|
|
2895
|
+
let i = 0;
|
|
2896
|
+
while (i < inputs.length) {
|
|
2897
|
+
let j = i;
|
|
2898
|
+
while (j < inputs.length && !this.hasRelationshipInput(node, inputs[j])) j++;
|
|
2899
|
+
if (j > i) {
|
|
2900
|
+
groups.push(this.createFlat(block, node, inputs.slice(i, j)));
|
|
2901
|
+
i = j;
|
|
2902
|
+
continue;
|
|
2903
|
+
}
|
|
2904
|
+
const inner = new Block();
|
|
2905
|
+
const v = this.ctx.variable("this");
|
|
2906
|
+
this.createNode(inner, v, node, inputs[i]);
|
|
2907
|
+
const g = this.ctx.variable("created");
|
|
2908
|
+
const c = this.ctx.variable("count");
|
|
2909
|
+
block.add(
|
|
2910
|
+
`CALL () {
|
|
2911
|
+
${indent(inner.clauses)}
|
|
2912
|
+
RETURN collect(${v}) AS ${g}, ${inner.aggregate()} AS ${c}
|
|
2913
|
+
}`
|
|
2914
|
+
);
|
|
2915
|
+
for (const k of ALL_COUNTERS) if (inner.terms[k].length) block.count(k, `${c}.${k}`);
|
|
2916
|
+
if (inner.errors.length) block.errors.push(`${c}.errors`);
|
|
2917
|
+
groups.push(g);
|
|
2918
|
+
i++;
|
|
2919
|
+
}
|
|
2920
|
+
return this.response(
|
|
2921
|
+
block,
|
|
2922
|
+
groups.length ? groups.join(" + ") : "[]",
|
|
2923
|
+
block.aggregate(false),
|
|
2924
|
+
node,
|
|
2925
|
+
fieldNodes
|
|
2926
|
+
);
|
|
2927
|
+
}
|
|
2928
|
+
hasRelationshipInput(node, input) {
|
|
2929
|
+
return isPlainObject2(input) && node.relationships.some((r) => input[r.name] !== void 0 && input[r.name] !== null);
|
|
2930
|
+
}
|
|
2931
|
+
/** `UNWIND $rows AS row CREATE (n:Label) SET n.p = row.p, …` for inputs without relationships. */
|
|
2932
|
+
createFlat(block, node, inputs) {
|
|
2933
|
+
const keys = /* @__PURE__ */ new Set();
|
|
2934
|
+
for (const input of inputs) {
|
|
2935
|
+
if (!isPlainObject2(input)) continue;
|
|
2936
|
+
for (const [k, v2] of Object.entries(input)) if (v2 !== void 0) keys.add(k);
|
|
2937
|
+
}
|
|
2938
|
+
const attrs = [...keys].map((k) => {
|
|
2939
|
+
const a = node.attributes.find((x) => x.name === k);
|
|
2940
|
+
if (!a) throw new Error(`Unknown field ${node.name}CreateInput.${k}`);
|
|
2941
|
+
return a;
|
|
2942
|
+
});
|
|
2943
|
+
const rows = inputs.map((input) => {
|
|
2944
|
+
const r = isPlainObject2(input) ? input : {};
|
|
2945
|
+
return Object.fromEntries(attrs.map((a) => [a.name, encodeValue(a, r[a.name])]));
|
|
2946
|
+
});
|
|
2947
|
+
const row = this.ctx.variable("row");
|
|
2948
|
+
const v = this.ctx.variable("this");
|
|
2949
|
+
const g = this.ctx.variable("created");
|
|
2950
|
+
const sets = [
|
|
2951
|
+
...onCreateGenerated(v, node.attributes),
|
|
2952
|
+
...attrs.map(
|
|
2953
|
+
(a) => `${v}.${q(a.property)} = ${castValue(a, `${row}.${q(a.name)}`, a.type.list)}`
|
|
2954
|
+
)
|
|
2955
|
+
];
|
|
2956
|
+
const lines = [
|
|
2957
|
+
`UNWIND ${this.ctx.param(rows)} AS ${row}`,
|
|
2958
|
+
`CREATE (${v}${labels(node.labels)})`,
|
|
2959
|
+
...sets.length ? [`SET ${sets.join(", ")}`] : [],
|
|
2960
|
+
`RETURN collect(${v}) AS ${g}`
|
|
2961
|
+
];
|
|
2962
|
+
block.add(`CALL () {
|
|
2963
|
+
${indent(lines)}
|
|
2964
|
+
}`);
|
|
2965
|
+
block.count("nc", `size(${g})`);
|
|
2966
|
+
return g;
|
|
2967
|
+
}
|
|
2968
|
+
/** `updateMovies(where, update)`; without `update` it only reads (and refreshes UPDATE timestamps). */
|
|
2969
|
+
rootUpdate(node, args, fieldNodes) {
|
|
2970
|
+
this.assertWritable(node);
|
|
2971
|
+
const block = new Block();
|
|
2972
|
+
const v = this.ctx.variable("this");
|
|
2973
|
+
const pred = this.where.node(v, node, args.where);
|
|
2974
|
+
block.add(`MATCH (${v}${labels(node.labels)})${pred ? `
|
|
2975
|
+
WHERE ${pred}` : ""}`);
|
|
2976
|
+
const checks = [];
|
|
2977
|
+
const sets = [
|
|
2978
|
+
...onUpdateGenerated(v, node.attributes),
|
|
2979
|
+
...this.updateAssignments(
|
|
2980
|
+
v,
|
|
2981
|
+
node.attributes,
|
|
2982
|
+
args.update,
|
|
2983
|
+
node.name,
|
|
2984
|
+
checks,
|
|
2985
|
+
node.relationships
|
|
2986
|
+
)
|
|
2987
|
+
];
|
|
2988
|
+
if (sets.length) block.add(`SET ${sets.join(", ")}`);
|
|
2989
|
+
block.check(checks);
|
|
2990
|
+
this.updateRelationships(block, v, node, args.update);
|
|
2991
|
+
return this.response(block, `collect(${v})`, block.aggregate(), node, fieldNodes);
|
|
2992
|
+
}
|
|
2993
|
+
/** `deleteMovies(where, delete)`: one `DeleteInfo`. */
|
|
2994
|
+
rootDelete(node, args, fieldNodes) {
|
|
2995
|
+
this.assertWritable(node);
|
|
2996
|
+
const block = new Block();
|
|
2997
|
+
const v = this.ctx.variable("this");
|
|
2998
|
+
const pred = this.where.node(v, node, args.where);
|
|
2999
|
+
block.add(`MATCH (${v}${labels(node.labels)})${pred ? `
|
|
3000
|
+
WHERE ${pred}` : ""}`);
|
|
3001
|
+
const roots = this.ctx.variable("roots");
|
|
3002
|
+
const nested = [];
|
|
3003
|
+
if (isPlainObject2(args.delete)) {
|
|
3004
|
+
for (const [name, els] of Object.entries(args.delete)) {
|
|
3005
|
+
const rel = this.relationship(node, name);
|
|
3006
|
+
const target = this.model.node(rel.target);
|
|
3007
|
+
for (const el of asList(els)) {
|
|
3008
|
+
if (!isPlainObject2(el)) continue;
|
|
3009
|
+
const t = this.ctx.variable("this");
|
|
3010
|
+
const r = this.ctx.variable("edge");
|
|
3011
|
+
const p = this.where.connection(r, t, rel, el.where);
|
|
3012
|
+
const match = `MATCH ${relationshipPattern(this.model, v, rel, t, r)}${p ? ` WHERE ${p}` : ""}`;
|
|
3013
|
+
nested.push(...this.deleteLists(match, t, target, el.delete));
|
|
3014
|
+
}
|
|
3015
|
+
}
|
|
3016
|
+
}
|
|
3017
|
+
let list2;
|
|
3018
|
+
if (nested.length) {
|
|
3019
|
+
const related = this.ctx.variable("related");
|
|
3020
|
+
block.add(`WITH collect(${v}) AS ${roots}, collect(${nested.join(" + ")}) AS ${related}`);
|
|
3021
|
+
list2 = `(${roots} + reduce(acc = [], l IN ${related} | acc + l))`;
|
|
3022
|
+
} else {
|
|
3023
|
+
block.add(`WITH collect(${v}) AS ${roots}`);
|
|
3024
|
+
list2 = roots;
|
|
3025
|
+
}
|
|
3026
|
+
this.deleteNodes(block, list2, []);
|
|
3027
|
+
const fields = [...collectFields(this.info, subSelections(fieldNodes))].map(
|
|
3028
|
+
([k, n]) => [k, n[0].name.value]
|
|
3029
|
+
);
|
|
3030
|
+
block.add(`RETURN ${block.aggregate(false)} AS this`);
|
|
3031
|
+
return {
|
|
3032
|
+
cypher: block.clauses.join("\n"),
|
|
3033
|
+
params: this.ctx.params,
|
|
3034
|
+
decode: (rows) => {
|
|
3035
|
+
const counts = rows[0] ?? {};
|
|
3036
|
+
return decodeCounts(fields, counts);
|
|
3037
|
+
}
|
|
3038
|
+
};
|
|
3039
|
+
}
|
|
3040
|
+
};
|
|
3041
|
+
var intAttribute = {
|
|
3042
|
+
name: "pop",
|
|
3043
|
+
property: "pop",
|
|
3044
|
+
type: { name: "Int", list: false, required: true, elementRequired: false },
|
|
3045
|
+
kind: "scalar",
|
|
3046
|
+
id: false
|
|
3047
|
+
};
|
|
3048
|
+
|
|
3049
|
+
// src/v7/execute.ts
|
|
3050
|
+
import neo4j3 from "neo4j-driver";
|
|
3051
|
+
function createExecutors(opts) {
|
|
3052
|
+
const log = (cypher, params) => {
|
|
3053
|
+
if (opts.debug)
|
|
3054
|
+
console.debug("[cyphra/graphql] cypher:", cypher, "param keys:", Object.keys(params));
|
|
3055
|
+
};
|
|
3056
|
+
const rows = async (tx, cypher, params) => (await tx.run(cypher, params)).records.map((r) => r.get("this"));
|
|
3057
|
+
if (opts.client) {
|
|
3058
|
+
const client = opts.client;
|
|
3059
|
+
return {
|
|
3060
|
+
read: async (cypher, params) => {
|
|
3061
|
+
log(cypher, params);
|
|
3062
|
+
return client.withReadTransaction((tx) => rows(tx, cypher, params));
|
|
3063
|
+
},
|
|
3064
|
+
write: async (cypher, params, consume) => {
|
|
3065
|
+
log(cypher, params);
|
|
3066
|
+
return client.withWriteTransaction(async (tx) => consume(await rows(tx, cypher, params)));
|
|
3067
|
+
}
|
|
3068
|
+
};
|
|
3069
|
+
}
|
|
3070
|
+
if (opts.driver) {
|
|
3071
|
+
const driver = opts.driver;
|
|
3072
|
+
const withSession = async (mode, fn) => {
|
|
3073
|
+
const session = driver.session({
|
|
3074
|
+
database: opts.database,
|
|
3075
|
+
defaultAccessMode: neo4j3.session[mode]
|
|
3076
|
+
});
|
|
3077
|
+
try {
|
|
3078
|
+
return await fn(session);
|
|
3079
|
+
} finally {
|
|
3080
|
+
await session.close();
|
|
3081
|
+
}
|
|
3082
|
+
};
|
|
3083
|
+
return {
|
|
3084
|
+
read: async (cypher, params) => {
|
|
3085
|
+
log(cypher, params);
|
|
3086
|
+
return withSession("READ", (s) => s.executeRead((tx) => rows(tx, cypher, params)));
|
|
3087
|
+
},
|
|
3088
|
+
write: async (cypher, params, consume) => {
|
|
3089
|
+
log(cypher, params);
|
|
3090
|
+
return withSession(
|
|
3091
|
+
"WRITE",
|
|
3092
|
+
(s) => s.executeWrite(async (tx) => consume(await rows(tx, cypher, params)))
|
|
3093
|
+
);
|
|
3094
|
+
}
|
|
3095
|
+
};
|
|
3096
|
+
}
|
|
3097
|
+
throw new TypeError("@cyphra/graphql: pass `driver` (neo4j-driver) or `client` (CyphraClient).");
|
|
3098
|
+
}
|
|
3099
|
+
|
|
3100
|
+
// src/v7/sdl.ts
|
|
3101
|
+
import {
|
|
3102
|
+
GraphQLBoolean,
|
|
3103
|
+
GraphQLEnumType,
|
|
3104
|
+
GraphQLFloat,
|
|
3105
|
+
GraphQLID,
|
|
3106
|
+
GraphQLInputObjectType,
|
|
3107
|
+
GraphQLInt,
|
|
3108
|
+
GraphQLList,
|
|
3109
|
+
GraphQLNonNull,
|
|
3110
|
+
GraphQLObjectType,
|
|
3111
|
+
GraphQLSchema,
|
|
3112
|
+
GraphQLString,
|
|
3113
|
+
valueFromAST
|
|
3114
|
+
} from "graphql";
|
|
3115
|
+
|
|
3116
|
+
// src/v7/scalars.ts
|
|
3117
|
+
import { GraphQLError as GraphQLError4, GraphQLScalarType, Kind as Kind5 } from "graphql";
|
|
3118
|
+
import neo4j4, { isDate, isDateTime, isInt as isInt3 } from "neo4j-driver";
|
|
3119
|
+
var GraphQLBigInt = new GraphQLScalarType({
|
|
3120
|
+
name: "BigInt",
|
|
3121
|
+
description: "A BigInt value up to 64 bits in size, which can be a number or a string if used inline, or a string only if used as a variable. Always returned as a string.",
|
|
3122
|
+
serialize(value) {
|
|
3123
|
+
if (isInt3(value)) return value.toString(10);
|
|
3124
|
+
if (typeof value === "string") return value;
|
|
3125
|
+
if (typeof value === "number" || typeof value === "bigint") return value.toString(10);
|
|
3126
|
+
throw new GraphQLError4(`BigInt cannot represent value: ${String(value)}`);
|
|
3127
|
+
},
|
|
3128
|
+
parseValue(value) {
|
|
3129
|
+
if (typeof value !== "string") {
|
|
3130
|
+
throw new GraphQLError4(
|
|
3131
|
+
"BigInt values are not JSON serializable. Please pass as a string in variables, or inline in the GraphQL query."
|
|
3132
|
+
);
|
|
3133
|
+
}
|
|
3134
|
+
try {
|
|
3135
|
+
return neo4j4.int(value, { strictStringValidation: true });
|
|
3136
|
+
} catch {
|
|
3137
|
+
throw new GraphQLError4(
|
|
3138
|
+
"Value must be either a BigInt, or a string representing a BigInt value."
|
|
3139
|
+
);
|
|
3140
|
+
}
|
|
3141
|
+
},
|
|
3142
|
+
parseLiteral(ast) {
|
|
3143
|
+
if (ast.kind === Kind5.INT || ast.kind === Kind5.STRING) {
|
|
3144
|
+
try {
|
|
3145
|
+
return neo4j4.int(ast.value, { strictStringValidation: true });
|
|
3146
|
+
} catch {
|
|
3147
|
+
}
|
|
3148
|
+
}
|
|
3149
|
+
throw new GraphQLError4(
|
|
3150
|
+
"Value must be either a BigInt, or a string representing a BigInt value."
|
|
3151
|
+
);
|
|
3152
|
+
}
|
|
3153
|
+
});
|
|
3154
|
+
var formatDate = (s) => new Date(s).toISOString().split("T")[0];
|
|
3155
|
+
var GraphQLDate = new GraphQLScalarType({
|
|
3156
|
+
name: "Date",
|
|
3157
|
+
description: "A date, represented as a 'yyyy-mm-dd' string",
|
|
3158
|
+
serialize(value) {
|
|
3159
|
+
if (typeof value === "string") return formatDate(value);
|
|
3160
|
+
if (isDate(value)) return formatDate(String(value));
|
|
3161
|
+
throw new GraphQLError4(`Date cannot represent value: ${String(value)}`);
|
|
3162
|
+
},
|
|
3163
|
+
parseValue(value) {
|
|
3164
|
+
if (typeof value === "string") {
|
|
3165
|
+
const d = new Date(value);
|
|
3166
|
+
if (Number.isNaN(d.getTime())) {
|
|
3167
|
+
throw new GraphQLError4(`Date cannot represent non temporal value: ${value}`);
|
|
3168
|
+
}
|
|
3169
|
+
return neo4j4.types.Date.fromStandardDate(d);
|
|
3170
|
+
}
|
|
3171
|
+
if (isDate(value)) return value;
|
|
3172
|
+
throw new GraphQLError4(`Date cannot represent non string value: ${String(value)}`);
|
|
3173
|
+
},
|
|
3174
|
+
parseLiteral(ast) {
|
|
3175
|
+
if (ast.kind !== Kind5.STRING) throw new GraphQLError4("Date cannot represent non string value.");
|
|
3176
|
+
return neo4j4.types.Date.fromStandardDate(new Date(ast.value));
|
|
3177
|
+
}
|
|
3178
|
+
});
|
|
3179
|
+
var GraphQLDateTime = new GraphQLScalarType({
|
|
3180
|
+
name: "DateTime",
|
|
3181
|
+
description: "A date and time, represented as an ISO-8601 string",
|
|
3182
|
+
serialize(value) {
|
|
3183
|
+
if (typeof value === "string") return new Date(value).toISOString();
|
|
3184
|
+
if (isDateTime(value)) return new Date(String(value)).toISOString();
|
|
3185
|
+
if (value instanceof Date) return value.toISOString();
|
|
3186
|
+
throw new GraphQLError4(`DateTime cannot represent value: ${String(value)}`);
|
|
3187
|
+
},
|
|
3188
|
+
parseValue(value) {
|
|
3189
|
+
if (typeof value === "string") {
|
|
3190
|
+
if (Number.isNaN(new Date(value).getTime())) {
|
|
3191
|
+
throw new GraphQLError4(`DateTime cannot represent non temporal value: ${value}`);
|
|
3192
|
+
}
|
|
3193
|
+
return value;
|
|
3194
|
+
}
|
|
3195
|
+
throw new GraphQLError4(`DateTime cannot represent non string value: ${String(value)}`);
|
|
3196
|
+
},
|
|
3197
|
+
parseLiteral(ast) {
|
|
3198
|
+
if (ast.kind !== Kind5.STRING)
|
|
3199
|
+
throw new GraphQLError4("DateTime cannot represent non string value.");
|
|
3200
|
+
return ast.value;
|
|
3201
|
+
}
|
|
3202
|
+
});
|
|
3203
|
+
|
|
3204
|
+
// src/v7/sdl.ts
|
|
3205
|
+
var SCALARS2 = {
|
|
3206
|
+
ID: GraphQLID,
|
|
3207
|
+
String: GraphQLString,
|
|
3208
|
+
Int: GraphQLInt,
|
|
3209
|
+
Float: GraphQLFloat,
|
|
3210
|
+
Boolean: GraphQLBoolean,
|
|
3211
|
+
BigInt: GraphQLBigInt,
|
|
3212
|
+
Date: GraphQLDate,
|
|
3213
|
+
DateTime: GraphQLDateTime
|
|
3214
|
+
};
|
|
3215
|
+
var NUMERIC_OR_TEMPORAL = /* @__PURE__ */ new Set(["Int", "Float", "BigInt", "Date", "DateTime"]);
|
|
3216
|
+
var AGGREGABLE = /* @__PURE__ */ new Set(["String", "Int", "Float", "BigInt", "DateTime"]);
|
|
3217
|
+
var nn = (t) => new GraphQLNonNull(t);
|
|
3218
|
+
var list = (t) => new GraphQLList(t);
|
|
3219
|
+
var QUANTIFIERS = ["all", "none", "single", "some"];
|
|
3220
|
+
var QUANTIFIER_WORD = {
|
|
3221
|
+
all: "all",
|
|
3222
|
+
none: "none",
|
|
3223
|
+
single: "one",
|
|
3224
|
+
some: "some"
|
|
3225
|
+
};
|
|
3226
|
+
function isAggregable(a) {
|
|
3227
|
+
return !a.type.list && !a.cypher && a.kind === "scalar" && AGGREGABLE.has(a.type.name);
|
|
3228
|
+
}
|
|
3229
|
+
var TypeRegistry = class {
|
|
3230
|
+
constructor(model) {
|
|
3231
|
+
this.model = model;
|
|
3232
|
+
}
|
|
3233
|
+
model;
|
|
3234
|
+
types = /* @__PURE__ */ new Map();
|
|
3235
|
+
get(name, create) {
|
|
3236
|
+
let t = this.types.get(name);
|
|
3237
|
+
if (!t) {
|
|
3238
|
+
t = create();
|
|
3239
|
+
this.types.set(name, t);
|
|
3240
|
+
}
|
|
3241
|
+
return t;
|
|
3242
|
+
}
|
|
3243
|
+
input(name, fields, description) {
|
|
3244
|
+
return this.get(name, () => new GraphQLInputObjectType({ name, description, fields }));
|
|
3245
|
+
}
|
|
3246
|
+
object(name, fields, description) {
|
|
3247
|
+
return this.get(name, () => new GraphQLObjectType({ name, description, fields }));
|
|
3248
|
+
}
|
|
3249
|
+
// -------------------------------------------------------------------------
|
|
3250
|
+
// Shared types
|
|
3251
|
+
// -------------------------------------------------------------------------
|
|
3252
|
+
namedType(name) {
|
|
3253
|
+
const scalar = SCALARS2[name];
|
|
3254
|
+
if (scalar) return scalar;
|
|
3255
|
+
const e = this.model.enums.get(name);
|
|
3256
|
+
if (!e) throw new Error(`Unknown type ${name}`);
|
|
3257
|
+
return this.get(
|
|
3258
|
+
name,
|
|
3259
|
+
() => new GraphQLEnumType({
|
|
3260
|
+
name,
|
|
3261
|
+
description: e.description,
|
|
3262
|
+
values: Object.fromEntries(
|
|
3263
|
+
e.values.map((v) => [
|
|
3264
|
+
v.name,
|
|
3265
|
+
{ value: v.name, description: v.description, deprecationReason: v.deprecated }
|
|
3266
|
+
])
|
|
3267
|
+
)
|
|
3268
|
+
})
|
|
3269
|
+
);
|
|
3270
|
+
}
|
|
3271
|
+
/** The declared output type of an attribute, e.g. `[String!]!`. */
|
|
3272
|
+
attributeType(t) {
|
|
3273
|
+
const named = this.namedType(t.name);
|
|
3274
|
+
if (t.list) {
|
|
3275
|
+
const inner = list(t.elementRequired ? nn(named) : named);
|
|
3276
|
+
return t.required ? nn(inner) : inner;
|
|
3277
|
+
}
|
|
3278
|
+
return t.required ? nn(named) : named;
|
|
3279
|
+
}
|
|
3280
|
+
sortDirection() {
|
|
3281
|
+
return this.get(
|
|
3282
|
+
"SortDirection",
|
|
3283
|
+
() => new GraphQLEnumType({
|
|
3284
|
+
name: "SortDirection",
|
|
3285
|
+
description: "An enum for sorting in either ascending or descending order.",
|
|
3286
|
+
values: {
|
|
3287
|
+
ASC: { value: "ASC", description: "Sort by field values in ascending order." },
|
|
3288
|
+
DESC: { value: "DESC", description: "Sort by field values in descending order." }
|
|
3289
|
+
}
|
|
3290
|
+
})
|
|
3291
|
+
);
|
|
3292
|
+
}
|
|
3293
|
+
pageInfo() {
|
|
3294
|
+
return this.object(
|
|
3295
|
+
"PageInfo",
|
|
3296
|
+
() => ({
|
|
3297
|
+
hasNextPage: { type: nn(GraphQLBoolean) },
|
|
3298
|
+
hasPreviousPage: { type: nn(GraphQLBoolean) },
|
|
3299
|
+
startCursor: { type: GraphQLString },
|
|
3300
|
+
endCursor: { type: GraphQLString }
|
|
3301
|
+
}),
|
|
3302
|
+
"Pagination information (Relay)"
|
|
3303
|
+
);
|
|
3304
|
+
}
|
|
3305
|
+
createInfo() {
|
|
3306
|
+
return this.object(
|
|
3307
|
+
"CreateInfo",
|
|
3308
|
+
() => ({
|
|
3309
|
+
nodesCreated: { type: nn(GraphQLInt) },
|
|
3310
|
+
relationshipsCreated: { type: nn(GraphQLInt) }
|
|
3311
|
+
}),
|
|
3312
|
+
"Information about the number of nodes and relationships created during a create mutation"
|
|
3313
|
+
);
|
|
3314
|
+
}
|
|
3315
|
+
deleteInfo() {
|
|
3316
|
+
return this.object(
|
|
3317
|
+
"DeleteInfo",
|
|
3318
|
+
() => ({
|
|
3319
|
+
nodesDeleted: { type: nn(GraphQLInt) },
|
|
3320
|
+
relationshipsDeleted: { type: nn(GraphQLInt) }
|
|
3321
|
+
}),
|
|
3322
|
+
"Information about the number of nodes and relationships deleted during a delete mutation"
|
|
3323
|
+
);
|
|
3324
|
+
}
|
|
3325
|
+
updateInfo() {
|
|
3326
|
+
return this.object(
|
|
3327
|
+
"UpdateInfo",
|
|
3328
|
+
() => ({
|
|
3329
|
+
nodesCreated: { type: nn(GraphQLInt) },
|
|
3330
|
+
nodesDeleted: { type: nn(GraphQLInt) },
|
|
3331
|
+
relationshipsCreated: { type: nn(GraphQLInt) },
|
|
3332
|
+
relationshipsDeleted: { type: nn(GraphQLInt) }
|
|
3333
|
+
}),
|
|
3334
|
+
"Information about the number of nodes and relationships created and deleted during an update mutation"
|
|
3335
|
+
);
|
|
3336
|
+
}
|
|
3337
|
+
count() {
|
|
3338
|
+
return this.object("Count", () => ({ nodes: { type: nn(GraphQLInt) } }));
|
|
3339
|
+
}
|
|
3340
|
+
countConnection() {
|
|
3341
|
+
return this.object("CountConnection", () => ({
|
|
3342
|
+
edges: { type: nn(GraphQLInt) },
|
|
3343
|
+
nodes: { type: nn(GraphQLInt) }
|
|
3344
|
+
}));
|
|
3345
|
+
}
|
|
3346
|
+
/** `IntScalarFilters`, `StringListFilters`, `OrderStatusEnumScalarFilters`, … */
|
|
3347
|
+
scalarFilters(a) {
|
|
3348
|
+
const t = a.type.name;
|
|
3349
|
+
const named = this.namedType(t);
|
|
3350
|
+
if (a.kind === "enum") {
|
|
3351
|
+
if (a.type.list) {
|
|
3352
|
+
return this.input(
|
|
3353
|
+
`${t}ListEnumScalarFilters`,
|
|
3354
|
+
() => ({ eq: { type: list(nn(named)) }, includes: { type: named } }),
|
|
3355
|
+
`${t} filters`
|
|
3356
|
+
);
|
|
3357
|
+
}
|
|
3358
|
+
return this.input(
|
|
3359
|
+
`${t}EnumScalarFilters`,
|
|
3360
|
+
() => ({ eq: { type: named }, in: { type: list(nn(named)) } }),
|
|
3361
|
+
`${t} filters`
|
|
3362
|
+
);
|
|
3363
|
+
}
|
|
3364
|
+
if (a.type.list) {
|
|
3365
|
+
if (t === "Boolean") {
|
|
3366
|
+
return this.input(
|
|
3367
|
+
"BooleanListFilters",
|
|
3368
|
+
() => ({ eq: { type: list(nn(named)) } }),
|
|
3369
|
+
"Boolean list filters"
|
|
3370
|
+
);
|
|
3371
|
+
}
|
|
3372
|
+
return this.input(
|
|
3373
|
+
`${t}ListFilters`,
|
|
3374
|
+
() => ({ eq: { type: list(nn(named)) }, includes: { type: named } }),
|
|
3375
|
+
`${t} list filters`
|
|
3376
|
+
);
|
|
3377
|
+
}
|
|
3378
|
+
if (t === "Boolean") {
|
|
3379
|
+
return this.input("BooleanScalarFilters", () => ({ eq: { type: named } }), "Boolean filters");
|
|
3380
|
+
}
|
|
3381
|
+
if (t === "String" || t === "ID") {
|
|
3382
|
+
return this.input(
|
|
3383
|
+
`${t}ScalarFilters`,
|
|
3384
|
+
() => ({
|
|
3385
|
+
contains: { type: named },
|
|
3386
|
+
endsWith: { type: named },
|
|
3387
|
+
eq: { type: named },
|
|
3388
|
+
in: { type: list(nn(named)) },
|
|
3389
|
+
startsWith: { type: named }
|
|
3390
|
+
}),
|
|
3391
|
+
`${t} filters`
|
|
3392
|
+
);
|
|
3393
|
+
}
|
|
3394
|
+
return this.input(
|
|
3395
|
+
`${t}ScalarFilters`,
|
|
3396
|
+
() => ({
|
|
3397
|
+
eq: { type: named },
|
|
3398
|
+
gt: { type: named },
|
|
3399
|
+
gte: { type: named },
|
|
3400
|
+
in: { type: list(nn(named)) },
|
|
3401
|
+
lt: { type: named },
|
|
3402
|
+
lte: { type: named }
|
|
3403
|
+
}),
|
|
3404
|
+
`${t} filters`
|
|
3405
|
+
);
|
|
3406
|
+
}
|
|
3407
|
+
intFilters() {
|
|
3408
|
+
return this.scalarFilters({ type: scalarRef("Int"), kind: "scalar" });
|
|
3409
|
+
}
|
|
3410
|
+
floatFilters() {
|
|
3411
|
+
return this.scalarFilters({ type: scalarRef("Float"), kind: "scalar" });
|
|
3412
|
+
}
|
|
3413
|
+
/** `IntScalarMutations`, `ListStringMutations`, `OrderStatusEnumScalarMutations`, … */
|
|
3414
|
+
scalarMutations(a) {
|
|
3415
|
+
const t = a.type.name;
|
|
3416
|
+
const named = this.namedType(t);
|
|
3417
|
+
if (a.type.list) {
|
|
3418
|
+
return this.input(
|
|
3419
|
+
a.kind === "enum" ? `List${t}EnumScalarMutations` : `List${t}Mutations`,
|
|
3420
|
+
() => ({
|
|
3421
|
+
pop: { type: GraphQLInt },
|
|
3422
|
+
push: { type: list(nn(named)) },
|
|
3423
|
+
set: { type: list(nn(named)) }
|
|
3424
|
+
}),
|
|
3425
|
+
`Mutations for a list for ${t}`
|
|
3426
|
+
);
|
|
3427
|
+
}
|
|
3428
|
+
if (a.kind === "enum") {
|
|
3429
|
+
return this.input(
|
|
3430
|
+
`${t}EnumScalarMutations`,
|
|
3431
|
+
() => ({ set: { type: named } }),
|
|
3432
|
+
`${t} mutations`
|
|
3433
|
+
);
|
|
3434
|
+
}
|
|
3435
|
+
switch (t) {
|
|
3436
|
+
case "Int":
|
|
3437
|
+
case "BigInt":
|
|
3438
|
+
return this.input(
|
|
3439
|
+
`${t}ScalarMutations`,
|
|
3440
|
+
() => ({ add: { type: named }, set: { type: named }, subtract: { type: named } }),
|
|
3441
|
+
`${t} mutations`
|
|
3442
|
+
);
|
|
3443
|
+
case "Float":
|
|
3444
|
+
return this.input(
|
|
3445
|
+
"FloatScalarMutations",
|
|
3446
|
+
() => ({
|
|
3447
|
+
add: { type: named },
|
|
3448
|
+
divide: { type: named },
|
|
3449
|
+
multiply: { type: named },
|
|
3450
|
+
set: { type: named },
|
|
3451
|
+
subtract: { type: named }
|
|
3452
|
+
}),
|
|
3453
|
+
"Float mutations"
|
|
3454
|
+
);
|
|
3455
|
+
default:
|
|
3456
|
+
return this.input(
|
|
3457
|
+
`${t}ScalarMutations`,
|
|
3458
|
+
() => ({ set: { type: named } }),
|
|
3459
|
+
`${t} mutations`
|
|
3460
|
+
);
|
|
3461
|
+
}
|
|
3462
|
+
}
|
|
3463
|
+
/** `IntAggregateSelection`, `StringAggregateSelection`, … */
|
|
3464
|
+
aggregateSelection(t) {
|
|
3465
|
+
const named = this.namedType(t);
|
|
3466
|
+
switch (t) {
|
|
3467
|
+
case "String":
|
|
3468
|
+
return this.object("StringAggregateSelection", () => ({
|
|
3469
|
+
longest: { type: GraphQLString },
|
|
3470
|
+
shortest: { type: GraphQLString }
|
|
3471
|
+
}));
|
|
3472
|
+
case "Int":
|
|
3473
|
+
return this.object("IntAggregateSelection", () => ({
|
|
3474
|
+
average: { type: GraphQLFloat },
|
|
3475
|
+
max: { type: GraphQLInt },
|
|
3476
|
+
min: { type: GraphQLInt },
|
|
3477
|
+
sum: { type: GraphQLInt }
|
|
3478
|
+
}));
|
|
3479
|
+
case "Float":
|
|
3480
|
+
case "BigInt":
|
|
3481
|
+
return this.object(`${t}AggregateSelection`, () => ({
|
|
3482
|
+
average: { type: named },
|
|
3483
|
+
max: { type: named },
|
|
3484
|
+
min: { type: named },
|
|
3485
|
+
sum: { type: named }
|
|
3486
|
+
}));
|
|
3487
|
+
default:
|
|
3488
|
+
return this.object(`${t}AggregateSelection`, () => ({
|
|
3489
|
+
max: { type: named },
|
|
3490
|
+
min: { type: named }
|
|
3491
|
+
}));
|
|
3492
|
+
}
|
|
3493
|
+
}
|
|
3494
|
+
/** `IntScalarAggregationFilters`, … */
|
|
3495
|
+
aggregationFilters(t) {
|
|
3496
|
+
switch (t) {
|
|
3497
|
+
case "String":
|
|
3498
|
+
return this.input(
|
|
3499
|
+
"StringScalarAggregationFilters",
|
|
3500
|
+
() => ({
|
|
3501
|
+
averageLength: { type: this.floatFilters() },
|
|
3502
|
+
longestLength: { type: this.intFilters() },
|
|
3503
|
+
shortestLength: { type: this.intFilters() }
|
|
3504
|
+
}),
|
|
3505
|
+
"Filters for an aggregation of a string field"
|
|
3506
|
+
);
|
|
3507
|
+
case "Int":
|
|
3508
|
+
return this.input(
|
|
3509
|
+
"IntScalarAggregationFilters",
|
|
3510
|
+
() => ({
|
|
3511
|
+
average: { type: this.floatFilters() },
|
|
3512
|
+
max: { type: this.intFilters() },
|
|
3513
|
+
min: { type: this.intFilters() },
|
|
3514
|
+
sum: { type: this.intFilters() }
|
|
3515
|
+
}),
|
|
3516
|
+
"Filters for an aggregation of an int field"
|
|
3517
|
+
);
|
|
3518
|
+
case "Float":
|
|
3519
|
+
return this.input(
|
|
3520
|
+
"FloatScalarAggregationFilters",
|
|
3521
|
+
() => ({
|
|
3522
|
+
average: { type: this.floatFilters() },
|
|
3523
|
+
max: { type: this.floatFilters() },
|
|
3524
|
+
min: { type: this.floatFilters() },
|
|
3525
|
+
sum: { type: this.floatFilters() }
|
|
3526
|
+
}),
|
|
3527
|
+
"Filters for an aggregation of a float field"
|
|
3528
|
+
);
|
|
3529
|
+
case "BigInt": {
|
|
3530
|
+
const f = () => this.scalarFilters({ type: scalarRef("BigInt"), kind: "scalar" });
|
|
3531
|
+
return this.input(
|
|
3532
|
+
"BigIntScalarAggregationFilters",
|
|
3533
|
+
() => ({
|
|
3534
|
+
average: { type: f() },
|
|
3535
|
+
max: { type: f() },
|
|
3536
|
+
min: { type: f() },
|
|
3537
|
+
sum: { type: f() }
|
|
3538
|
+
}),
|
|
3539
|
+
"Filters for an aggregation of an BigInt field"
|
|
3540
|
+
);
|
|
3541
|
+
}
|
|
3542
|
+
default: {
|
|
3543
|
+
const f = () => this.scalarFilters({ type: scalarRef(t), kind: "scalar" });
|
|
3544
|
+
return this.input(
|
|
3545
|
+
`${t}ScalarAggregationFilters`,
|
|
3546
|
+
() => ({ max: { type: f() }, min: { type: f() } }),
|
|
3547
|
+
`Filters for an aggregation of an ${t} input field`
|
|
3548
|
+
);
|
|
3549
|
+
}
|
|
3550
|
+
}
|
|
3551
|
+
}
|
|
3552
|
+
connectionAggregationCountFilter() {
|
|
3553
|
+
return this.input("ConnectionAggregationCountFilterInput", () => ({
|
|
3554
|
+
edges: { type: this.intFilters() },
|
|
3555
|
+
nodes: { type: this.intFilters() }
|
|
3556
|
+
}));
|
|
3557
|
+
}
|
|
3558
|
+
// -------------------------------------------------------------------------
|
|
3559
|
+
// Attribute-level field maps (shared by nodes and relationship properties)
|
|
3560
|
+
// -------------------------------------------------------------------------
|
|
3561
|
+
/** `where` fields of attributes, with the deprecated `field_OPERATOR` variants. */
|
|
3562
|
+
attributeWhereFields(attributes) {
|
|
3563
|
+
const out = {};
|
|
3564
|
+
for (const a of attributes) {
|
|
3565
|
+
if (a.cypher && a.type.list) continue;
|
|
3566
|
+
out[a.name] = { type: this.scalarFilters(a), deprecationReason: a.deprecated };
|
|
3567
|
+
const named = this.namedType(a.type.name);
|
|
3568
|
+
const dep = (op) => a.deprecated ?? `Please use the relevant generic filter ${a.name}: { ${op}: ... }`;
|
|
3569
|
+
out[`${a.name}_EQ`] = {
|
|
3570
|
+
type: a.type.list ? list(a.type.elementRequired ? nn(named) : named) : named,
|
|
3571
|
+
deprecationReason: dep("eq")
|
|
3572
|
+
};
|
|
3573
|
+
if (a.kind === "scalar" && a.type.name === "Boolean") continue;
|
|
3574
|
+
if (a.type.list) {
|
|
3575
|
+
out[`${a.name}_INCLUDES`] = { type: named, deprecationReason: dep("includes") };
|
|
3576
|
+
continue;
|
|
3577
|
+
}
|
|
3578
|
+
out[`${a.name}_IN`] = {
|
|
3579
|
+
type: list(a.type.required ? nn(named) : named),
|
|
3580
|
+
deprecationReason: dep("in")
|
|
3581
|
+
};
|
|
3582
|
+
if (a.kind === "scalar" && NUMERIC_OR_TEMPORAL.has(a.type.name)) {
|
|
3583
|
+
for (const op of ["LT", "LTE", "GT", "GTE"]) {
|
|
3584
|
+
out[`${a.name}_${op}`] = { type: named, deprecationReason: dep(op.toLowerCase()) };
|
|
3585
|
+
}
|
|
3586
|
+
continue;
|
|
3587
|
+
}
|
|
3588
|
+
if (a.kind === "scalar" && (a.type.name === "String" || a.type.name === "ID")) {
|
|
3589
|
+
out[`${a.name}_CONTAINS`] = { type: named, deprecationReason: dep("contains") };
|
|
3590
|
+
out[`${a.name}_STARTS_WITH`] = { type: named, deprecationReason: dep("startsWith") };
|
|
3591
|
+
out[`${a.name}_ENDS_WITH`] = { type: named, deprecationReason: dep("endsWith") };
|
|
3592
|
+
}
|
|
3593
|
+
}
|
|
3594
|
+
return out;
|
|
3595
|
+
}
|
|
3596
|
+
/** Aggregation `where` fields (`name: StringScalarAggregationFilters`, `name_AVERAGE_LENGTH_GT`…). */
|
|
3597
|
+
aggregationWhereFields(self, attributes) {
|
|
3598
|
+
const out = {
|
|
3599
|
+
AND: { type: list(nn(self())) },
|
|
3600
|
+
NOT: { type: self() },
|
|
3601
|
+
OR: { type: list(nn(self())) }
|
|
3602
|
+
};
|
|
3603
|
+
for (const a of attributes) {
|
|
3604
|
+
if (!isAggregable(a)) continue;
|
|
3605
|
+
const t = a.type.name;
|
|
3606
|
+
out[a.name] = { type: this.aggregationFilters(t) };
|
|
3607
|
+
const named = this.namedType(t);
|
|
3608
|
+
const ops = t === "String" ? [
|
|
3609
|
+
["AVERAGE_LENGTH", "averageLength", GraphQLFloat],
|
|
3610
|
+
["LONGEST_LENGTH", "longestLength", GraphQLInt],
|
|
3611
|
+
["SHORTEST_LENGTH", "shortestLength", GraphQLInt]
|
|
3612
|
+
] : t === "Int" ? [
|
|
3613
|
+
["AVERAGE", "average", GraphQLFloat],
|
|
3614
|
+
["MAX", "max", GraphQLInt],
|
|
3615
|
+
["MIN", "min", GraphQLInt],
|
|
3616
|
+
["SUM", "sum", GraphQLInt]
|
|
3617
|
+
] : t === "Float" || t === "BigInt" ? [
|
|
3618
|
+
["AVERAGE", "average", named],
|
|
3619
|
+
["MAX", "max", named],
|
|
3620
|
+
["MIN", "min", named],
|
|
3621
|
+
["SUM", "sum", named]
|
|
3622
|
+
] : [
|
|
3623
|
+
["MAX", "max", named],
|
|
3624
|
+
["MIN", "min", named]
|
|
3625
|
+
];
|
|
3626
|
+
for (const [legacy, generic, type] of ops) {
|
|
3627
|
+
for (const [cmp, op] of [
|
|
3628
|
+
["EQUAL", "eq"],
|
|
3629
|
+
["GT", "gt"],
|
|
3630
|
+
["GTE", "gte"],
|
|
3631
|
+
["LT", "lt"],
|
|
3632
|
+
["LTE", "lte"]
|
|
3633
|
+
]) {
|
|
3634
|
+
out[`${a.name}_${legacy}_${cmp}`] = {
|
|
3635
|
+
type,
|
|
3636
|
+
deprecationReason: `Please use the relevant generic filter '${a.name}: { ${generic}: { ${op}: ... } } }' instead.`
|
|
3637
|
+
};
|
|
3638
|
+
}
|
|
3639
|
+
}
|
|
3640
|
+
}
|
|
3641
|
+
return out;
|
|
3642
|
+
}
|
|
3643
|
+
/** Create input fields of attributes (`@id`, `@cypher` and `@timestamp(CREATE)` excluded). */
|
|
3644
|
+
attributeCreateFields(attributes) {
|
|
3645
|
+
const out = {};
|
|
3646
|
+
for (const a of attributes) {
|
|
3647
|
+
if (a.id || a.cypher || a.timestamp?.includes("CREATE")) continue;
|
|
3648
|
+
const type = this.attributeType(a.type);
|
|
3649
|
+
const field = { type, deprecationReason: a.deprecated };
|
|
3650
|
+
if (a.defaultAst) field.defaultValue = valueFromAST(a.defaultAst, type);
|
|
3651
|
+
out[a.name] = field;
|
|
3652
|
+
}
|
|
3653
|
+
return out;
|
|
3654
|
+
}
|
|
3655
|
+
/** Update input fields of attributes, with the deprecated `field_SET` / `_INCREMENT` / … */
|
|
3656
|
+
attributeUpdateFields(attributes) {
|
|
3657
|
+
const out = {};
|
|
3658
|
+
for (const a of attributes) {
|
|
3659
|
+
if (a.id || a.cypher || a.timestamp?.includes("UPDATE")) continue;
|
|
3660
|
+
const named = this.namedType(a.type.name);
|
|
3661
|
+
out[a.name] = { type: this.scalarMutations(a), deprecationReason: a.deprecated };
|
|
3662
|
+
const generic = (op) => a.deprecated ?? `Please use the generic mutation '${a.name}: { ${op}: ... } }' instead.`;
|
|
3663
|
+
const relevant = (op) => a.deprecated ?? `Please use the relevant generic mutation '${a.name}: { ${op}: ... } }' instead.`;
|
|
3664
|
+
if (a.type.list) {
|
|
3665
|
+
out[`${a.name}_POP`] = { type: GraphQLInt, deprecationReason: generic("pop") };
|
|
3666
|
+
out[`${a.name}_PUSH`] = { type: list(nn(named)), deprecationReason: generic("push") };
|
|
3667
|
+
out[`${a.name}_SET`] = { type: list(nn(named)), deprecationReason: generic("set") };
|
|
3668
|
+
continue;
|
|
3669
|
+
}
|
|
3670
|
+
out[`${a.name}_SET`] = { type: named, deprecationReason: generic("set") };
|
|
3671
|
+
if (a.kind !== "scalar") continue;
|
|
3672
|
+
if (a.type.name === "Int" || a.type.name === "BigInt") {
|
|
3673
|
+
out[`${a.name}_INCREMENT`] = { type: named, deprecationReason: relevant("increment") };
|
|
3674
|
+
out[`${a.name}_DECREMENT`] = { type: named, deprecationReason: relevant("decrement") };
|
|
3675
|
+
} else if (a.type.name === "Float") {
|
|
3676
|
+
for (const op of ["add", "subtract", "multiply", "divide"]) {
|
|
3677
|
+
out[`${a.name}_${op.toUpperCase()}`] = { type: named, deprecationReason: relevant(op) };
|
|
3678
|
+
}
|
|
3679
|
+
}
|
|
3680
|
+
}
|
|
3681
|
+
return out;
|
|
3682
|
+
}
|
|
3683
|
+
// -------------------------------------------------------------------------
|
|
3684
|
+
// Relationship properties
|
|
3685
|
+
// -------------------------------------------------------------------------
|
|
3686
|
+
propertiesObject(p) {
|
|
3687
|
+
const users = this.model.nodes.flatMap(
|
|
3688
|
+
(n) => n.relationships.filter((r) => r.properties === p.name).map((r) => `* ${n.name}.${r.name}`)
|
|
3689
|
+
);
|
|
3690
|
+
return this.object(
|
|
3691
|
+
p.name,
|
|
3692
|
+
() => attributeOutputFields(this, p.attributes),
|
|
3693
|
+
`The edge properties for the following fields:
|
|
3694
|
+
${users.join("\n")}`
|
|
3695
|
+
);
|
|
3696
|
+
}
|
|
3697
|
+
propertiesWhere(p) {
|
|
3698
|
+
const self = () => this.propertiesWhere(p);
|
|
3699
|
+
return this.input(`${p.name}Where`, () => ({
|
|
3700
|
+
AND: { type: list(nn(self())) },
|
|
3701
|
+
NOT: { type: self() },
|
|
3702
|
+
OR: { type: list(nn(self())) },
|
|
3703
|
+
...this.attributeWhereFields(p.attributes)
|
|
3704
|
+
}));
|
|
3705
|
+
}
|
|
3706
|
+
propertiesSort(p) {
|
|
3707
|
+
return this.input(
|
|
3708
|
+
`${p.name}Sort`,
|
|
3709
|
+
() => Object.fromEntries(p.attributes.map((a) => [a.name, { type: this.sortDirection() }]))
|
|
3710
|
+
);
|
|
3711
|
+
}
|
|
3712
|
+
propertiesCreate(p) {
|
|
3713
|
+
return this.input(`${p.name}CreateInput`, () => this.attributeCreateFields(p.attributes));
|
|
3714
|
+
}
|
|
3715
|
+
/** `ActedInCreateInput!` when some property is required on create. */
|
|
3716
|
+
propertiesCreateRef(p) {
|
|
3717
|
+
const t = this.propertiesCreate(p);
|
|
3718
|
+
const required = p.attributes.some(
|
|
3719
|
+
(a) => !a.id && !a.cypher && !a.timestamp?.includes("CREATE") && a.type.required && a.defaultAst === void 0
|
|
3720
|
+
);
|
|
3721
|
+
return required ? nn(t) : t;
|
|
3722
|
+
}
|
|
3723
|
+
propertiesUpdate(p) {
|
|
3724
|
+
return this.input(`${p.name}UpdateInput`, () => this.attributeUpdateFields(p.attributes));
|
|
3725
|
+
}
|
|
3726
|
+
propertiesAggregationWhere(p) {
|
|
3727
|
+
const self = () => this.propertiesAggregationWhere(p);
|
|
3728
|
+
return this.input(
|
|
3729
|
+
`${p.name}AggregationWhereInput`,
|
|
3730
|
+
() => this.aggregationWhereFields(self, p.attributes)
|
|
3731
|
+
);
|
|
3732
|
+
}
|
|
3733
|
+
// -------------------------------------------------------------------------
|
|
3734
|
+
// Nodes
|
|
3735
|
+
// -------------------------------------------------------------------------
|
|
3736
|
+
node(n) {
|
|
3737
|
+
return this.object(
|
|
3738
|
+
n.name,
|
|
3739
|
+
() => {
|
|
3740
|
+
const fields = attributeOutputFields(this, n.attributes);
|
|
3741
|
+
for (const r of n.relationships) {
|
|
3742
|
+
const target = this.model.node(r.target);
|
|
3743
|
+
fields[r.name] = {
|
|
3744
|
+
type: relationshipType(this, r),
|
|
3745
|
+
description: r.description,
|
|
3746
|
+
deprecationReason: r.deprecated,
|
|
3747
|
+
args: {
|
|
3748
|
+
limit: { type: GraphQLInt },
|
|
3749
|
+
offset: { type: GraphQLInt },
|
|
3750
|
+
sort: { type: list(nn(this.nodeSort(target))) },
|
|
3751
|
+
where: { type: this.nodeWhere(target) }
|
|
3752
|
+
}
|
|
3753
|
+
};
|
|
3754
|
+
fields[`${r.name}Connection`] = {
|
|
3755
|
+
type: nn(this.relConnection(r)),
|
|
3756
|
+
deprecationReason: r.deprecated,
|
|
3757
|
+
args: {
|
|
3758
|
+
after: { type: GraphQLString },
|
|
3759
|
+
first: { type: GraphQLInt },
|
|
3760
|
+
sort: { type: list(nn(this.relConnectionSort(r))) },
|
|
3761
|
+
where: { type: this.relConnectionWhere(r) }
|
|
3762
|
+
}
|
|
3763
|
+
};
|
|
3764
|
+
}
|
|
3765
|
+
return fields;
|
|
3766
|
+
},
|
|
3767
|
+
n.description
|
|
3768
|
+
);
|
|
3769
|
+
}
|
|
3770
|
+
nodeSort(n) {
|
|
3771
|
+
return this.input(
|
|
3772
|
+
`${n.name}Sort`,
|
|
3773
|
+
() => Object.fromEntries(
|
|
3774
|
+
n.attributes.filter((a) => !a.type.list).map((a) => [a.name, { type: this.sortDirection() }])
|
|
3775
|
+
),
|
|
3776
|
+
`Fields to sort ${n.pascalPlural} by. The order in which sorts are applied is not guaranteed when specifying many fields in one ${n.name}Sort object.`
|
|
3777
|
+
);
|
|
3778
|
+
}
|
|
3779
|
+
nodeWhere(n) {
|
|
3780
|
+
return this.input(`${n.name}Where`, () => {
|
|
3781
|
+
const self = this.nodeWhere(n);
|
|
3782
|
+
const out = {
|
|
3783
|
+
AND: { type: list(nn(self)) },
|
|
3784
|
+
NOT: { type: self },
|
|
3785
|
+
OR: { type: list(nn(self)) },
|
|
3786
|
+
...this.attributeWhereFields(n.attributes)
|
|
3787
|
+
};
|
|
3788
|
+
const sourcePlural = pluralize(n.name);
|
|
3789
|
+
for (const r of n.relationships) {
|
|
3790
|
+
const target = this.model.node(r.target);
|
|
3791
|
+
const targetWhere = this.nodeWhere(target);
|
|
3792
|
+
const connWhere = this.relConnectionWhere(r);
|
|
3793
|
+
const connPlural = pluralize(relConnectionName(r));
|
|
3794
|
+
out[r.name] = { type: this.relationshipFilters(target) };
|
|
3795
|
+
out[`${r.name}Aggregate`] = {
|
|
3796
|
+
type: this.relAggregateInput(r),
|
|
3797
|
+
deprecationReason: `Aggregate filters are moved inside the ${r.name}Connection filter, please use { ${r.name}Connection: { aggregate: {...} } } instead`
|
|
3798
|
+
};
|
|
3799
|
+
out[`${r.name}Connection`] = { type: this.relConnectionFilters(r) };
|
|
3800
|
+
for (const q2 of QUANTIFIERS) {
|
|
3801
|
+
out[`${r.name}Connection_${q2.toUpperCase()}`] = {
|
|
3802
|
+
type: connWhere,
|
|
3803
|
+
description: `Return ${sourcePlural} where ${QUANTIFIER_WORD[q2]} of the related ${connPlural} match this filter`,
|
|
3804
|
+
deprecationReason: `Please use the relevant generic filter '${r.name}Connection: { ${q2}: { node: ... } } }' instead.`
|
|
3805
|
+
};
|
|
3806
|
+
const spacing = q2 === "single" || q2 === "some" ? " " : " ";
|
|
3807
|
+
out[`${r.name}_${q2.toUpperCase()}`] = {
|
|
3808
|
+
type: targetWhere,
|
|
3809
|
+
description: `Return ${sourcePlural} where ${QUANTIFIER_WORD[q2]} of the related ${pluralize(target.name)} match this filter`,
|
|
3810
|
+
deprecationReason: `Please use the relevant generic filter '${r.name}: {${spacing}${q2}: ... }' instead.`
|
|
3811
|
+
};
|
|
3812
|
+
}
|
|
3813
|
+
}
|
|
3814
|
+
return out;
|
|
3815
|
+
});
|
|
3816
|
+
}
|
|
3817
|
+
relationshipFilters(target) {
|
|
3818
|
+
return this.input(`${target.name}RelationshipFilters`, () => {
|
|
3819
|
+
const where = this.nodeWhere(target);
|
|
3820
|
+
return Object.fromEntries(
|
|
3821
|
+
QUANTIFIERS.map((q2) => [
|
|
3822
|
+
q2,
|
|
3823
|
+
{
|
|
3824
|
+
type: where,
|
|
3825
|
+
description: `Filter type where ${QUANTIFIER_WORD[q2]} of the related ${pluralize(target.name)} match this filter`
|
|
3826
|
+
}
|
|
3827
|
+
])
|
|
3828
|
+
);
|
|
3829
|
+
});
|
|
3830
|
+
}
|
|
3831
|
+
nodeAggregate(n) {
|
|
3832
|
+
return this.object(`${n.name}Aggregate`, () => {
|
|
3833
|
+
const fields = { count: { type: nn(this.count()) } };
|
|
3834
|
+
if (n.attributes.some(isAggregable)) fields.node = { type: nn(this.nodeAggregateNode(n)) };
|
|
3835
|
+
return fields;
|
|
3836
|
+
});
|
|
3837
|
+
}
|
|
3838
|
+
nodeAggregateNode(n) {
|
|
3839
|
+
return this.object(
|
|
3840
|
+
`${n.name}AggregateNode`,
|
|
3841
|
+
() => aggregateSelectionFields(this, n.attributes)
|
|
3842
|
+
);
|
|
3843
|
+
}
|
|
3844
|
+
nodeEdge(n) {
|
|
3845
|
+
return this.object(`${n.name}Edge`, () => ({
|
|
3846
|
+
cursor: { type: nn(GraphQLString) },
|
|
3847
|
+
node: { type: nn(this.node(n)) }
|
|
3848
|
+
}));
|
|
3849
|
+
}
|
|
3850
|
+
rootConnection(n) {
|
|
3851
|
+
return this.object(`${n.pascalPlural}Connection`, () => ({
|
|
3852
|
+
aggregate: { type: nn(this.nodeAggregate(n)) },
|
|
3853
|
+
edges: { type: nn(list(nn(this.nodeEdge(n)))) },
|
|
3854
|
+
pageInfo: { type: nn(this.pageInfo()) },
|
|
3855
|
+
totalCount: { type: nn(GraphQLInt) }
|
|
3856
|
+
}));
|
|
3857
|
+
}
|
|
3858
|
+
nodeCreate(n) {
|
|
3859
|
+
return this.input(`${n.name}CreateInput`, () => {
|
|
3860
|
+
const out = this.attributeCreateFields(n.attributes);
|
|
3861
|
+
for (const r of n.relationships) out[r.name] = { type: this.relFieldInput(r) };
|
|
3862
|
+
return out;
|
|
3863
|
+
});
|
|
3864
|
+
}
|
|
3865
|
+
nodeUpdate(n) {
|
|
3866
|
+
return this.input(`${n.name}UpdateInput`, () => {
|
|
3867
|
+
const out = this.attributeUpdateFields(n.attributes);
|
|
3868
|
+
for (const r of n.relationships)
|
|
3869
|
+
out[r.name] = { type: list(nn(this.relUpdateFieldInput(r))) };
|
|
3870
|
+
return out;
|
|
3871
|
+
});
|
|
3872
|
+
}
|
|
3873
|
+
nodeConnectWhere(n) {
|
|
3874
|
+
return this.input(`${n.name}ConnectWhere`, () => ({ node: { type: nn(this.nodeWhere(n)) } }));
|
|
3875
|
+
}
|
|
3876
|
+
nodeConnect(n) {
|
|
3877
|
+
if (!n.relationships.length) return void 0;
|
|
3878
|
+
return this.input(
|
|
3879
|
+
`${n.name}ConnectInput`,
|
|
3880
|
+
() => Object.fromEntries(
|
|
3881
|
+
n.relationships.map((r) => [r.name, { type: list(nn(this.relConnectFieldInput(r))) }])
|
|
3882
|
+
)
|
|
3883
|
+
);
|
|
3884
|
+
}
|
|
3885
|
+
nodeDisconnect(n) {
|
|
3886
|
+
if (!n.relationships.length) return void 0;
|
|
3887
|
+
return this.input(
|
|
3888
|
+
`${n.name}DisconnectInput`,
|
|
3889
|
+
() => Object.fromEntries(
|
|
3890
|
+
n.relationships.map((r) => [r.name, { type: list(nn(this.relDisconnectFieldInput(r))) }])
|
|
3891
|
+
)
|
|
3892
|
+
);
|
|
3893
|
+
}
|
|
3894
|
+
nodeDelete(n) {
|
|
3895
|
+
if (!n.relationships.length) return void 0;
|
|
3896
|
+
return this.input(
|
|
3897
|
+
`${n.name}DeleteInput`,
|
|
3898
|
+
() => Object.fromEntries(
|
|
3899
|
+
n.relationships.map((r) => [r.name, { type: list(nn(this.relDeleteFieldInput(r))) }])
|
|
3900
|
+
)
|
|
3901
|
+
);
|
|
3902
|
+
}
|
|
3903
|
+
mutationResponse(n, kind) {
|
|
3904
|
+
return this.object(`${kind}${n.pascalPlural}MutationResponse`, () => ({
|
|
3905
|
+
info: { type: nn(kind === "Create" ? this.createInfo() : this.updateInfo()) },
|
|
3906
|
+
[n.plural]: { type: nn(list(nn(this.node(n)))) }
|
|
3907
|
+
}));
|
|
3908
|
+
}
|
|
3909
|
+
// -------------------------------------------------------------------------
|
|
3910
|
+
// Relationships (`${Source}${Field}…` types)
|
|
3911
|
+
// -------------------------------------------------------------------------
|
|
3912
|
+
props(r) {
|
|
3913
|
+
return r.properties ? this.model.properties.get(r.properties) : void 0;
|
|
3914
|
+
}
|
|
3915
|
+
relConnection(r) {
|
|
3916
|
+
return this.object(relConnectionName(r), () => ({
|
|
3917
|
+
aggregate: { type: nn(this.relAggregateSelection(r)) },
|
|
3918
|
+
edges: { type: nn(list(nn(this.relRelationship(r)))) },
|
|
3919
|
+
pageInfo: { type: nn(this.pageInfo()) },
|
|
3920
|
+
totalCount: { type: nn(GraphQLInt) }
|
|
3921
|
+
}));
|
|
3922
|
+
}
|
|
3923
|
+
relRelationship(r) {
|
|
3924
|
+
return this.object(`${prefix(r)}Relationship`, () => {
|
|
3925
|
+
const fields = {
|
|
3926
|
+
cursor: { type: nn(GraphQLString) },
|
|
3927
|
+
node: { type: nn(this.node(this.model.node(r.target))) }
|
|
3928
|
+
};
|
|
3929
|
+
const p = this.props(r);
|
|
3930
|
+
if (p) fields.properties = { type: nn(this.propertiesObject(p)) };
|
|
3931
|
+
return fields;
|
|
3932
|
+
});
|
|
3933
|
+
}
|
|
3934
|
+
relAggregateSelection(r) {
|
|
3935
|
+
const base = `${r.source}${r.target}${upperFirst(r.name)}`;
|
|
3936
|
+
return this.object(`${base}AggregateSelection`, () => {
|
|
3937
|
+
const fields = {
|
|
3938
|
+
count: { type: nn(this.countConnection()) }
|
|
3939
|
+
};
|
|
3940
|
+
const p = this.props(r);
|
|
3941
|
+
if (p && p.attributes.some(isAggregable)) {
|
|
3942
|
+
fields.edge = {
|
|
3943
|
+
type: this.object(
|
|
3944
|
+
`${base}EdgeAggregateSelection`,
|
|
3945
|
+
() => aggregateSelectionFields(this, p.attributes)
|
|
3946
|
+
)
|
|
3947
|
+
};
|
|
3948
|
+
}
|
|
3949
|
+
const target = this.model.node(r.target);
|
|
3950
|
+
if (target.attributes.some(isAggregable)) {
|
|
3951
|
+
fields.node = {
|
|
3952
|
+
type: this.object(
|
|
3953
|
+
`${base}NodeAggregateSelection`,
|
|
3954
|
+
() => aggregateSelectionFields(this, target.attributes)
|
|
3955
|
+
)
|
|
3956
|
+
};
|
|
3957
|
+
}
|
|
3958
|
+
return fields;
|
|
3959
|
+
});
|
|
3960
|
+
}
|
|
3961
|
+
relConnectionSort(r) {
|
|
3962
|
+
return this.input(`${relConnectionName(r)}Sort`, () => {
|
|
3963
|
+
const out = {};
|
|
3964
|
+
const p = this.props(r);
|
|
3965
|
+
if (p) out.edge = { type: this.propertiesSort(p) };
|
|
3966
|
+
out.node = { type: this.nodeSort(this.model.node(r.target)) };
|
|
3967
|
+
return out;
|
|
3968
|
+
});
|
|
3969
|
+
}
|
|
3970
|
+
relConnectionWhere(r) {
|
|
3971
|
+
return this.input(`${relConnectionName(r)}Where`, () => {
|
|
3972
|
+
const self = this.relConnectionWhere(r);
|
|
3973
|
+
const out = {
|
|
3974
|
+
AND: { type: list(nn(self)) },
|
|
3975
|
+
NOT: { type: self },
|
|
3976
|
+
OR: { type: list(nn(self)) }
|
|
3977
|
+
};
|
|
3978
|
+
const p = this.props(r);
|
|
3979
|
+
if (p) out.edge = { type: this.propertiesWhere(p) };
|
|
3980
|
+
out.node = { type: this.nodeWhere(this.model.node(r.target)) };
|
|
3981
|
+
return out;
|
|
3982
|
+
});
|
|
3983
|
+
}
|
|
3984
|
+
relConnectionFilters(r) {
|
|
3985
|
+
return this.input(`${prefix(r)}ConnectionFilters`, () => {
|
|
3986
|
+
const where = this.relConnectionWhere(r);
|
|
3987
|
+
const sourcePlural = pluralize(r.source);
|
|
3988
|
+
const connPlural = pluralize(relConnectionName(r));
|
|
3989
|
+
const out = {
|
|
3990
|
+
aggregate: {
|
|
3991
|
+
type: this.relConnectionAggregateInput(r),
|
|
3992
|
+
description: `Filter ${sourcePlural} by aggregating results on related ${connPlural}`
|
|
3993
|
+
}
|
|
3994
|
+
};
|
|
3995
|
+
for (const q2 of QUANTIFIERS) {
|
|
3996
|
+
out[q2] = {
|
|
3997
|
+
type: where,
|
|
3998
|
+
description: `Return ${sourcePlural} where ${QUANTIFIER_WORD[q2]} of the related ${connPlural} match this filter`
|
|
3999
|
+
};
|
|
4000
|
+
}
|
|
4001
|
+
return out;
|
|
4002
|
+
});
|
|
4003
|
+
}
|
|
4004
|
+
relNodeAggregationWhere(r) {
|
|
4005
|
+
const self = () => this.relNodeAggregationWhere(r);
|
|
4006
|
+
return this.input(
|
|
4007
|
+
`${prefix(r)}NodeAggregationWhereInput`,
|
|
4008
|
+
() => this.aggregationWhereFields(self, this.model.node(r.target).attributes)
|
|
4009
|
+
);
|
|
4010
|
+
}
|
|
4011
|
+
aggregateInputEdgeNode(r) {
|
|
4012
|
+
const out = {};
|
|
4013
|
+
const p = this.props(r);
|
|
4014
|
+
if (p && p.attributes.some(isAggregable))
|
|
4015
|
+
out.edge = { type: this.propertiesAggregationWhere(p) };
|
|
4016
|
+
if (this.model.node(r.target).attributes.some(isAggregable)) {
|
|
4017
|
+
out.node = { type: this.relNodeAggregationWhere(r) };
|
|
4018
|
+
}
|
|
4019
|
+
return out;
|
|
4020
|
+
}
|
|
4021
|
+
relAggregateInput(r) {
|
|
4022
|
+
return this.input(`${prefix(r)}AggregateInput`, () => {
|
|
4023
|
+
const self = this.relAggregateInput(r);
|
|
4024
|
+
const out = {
|
|
4025
|
+
AND: { type: list(nn(self)) },
|
|
4026
|
+
NOT: { type: self },
|
|
4027
|
+
OR: { type: list(nn(self)) },
|
|
4028
|
+
count: { type: this.intFilters() }
|
|
4029
|
+
};
|
|
4030
|
+
for (const op of ["eq", "gt", "gte", "lt", "lte"]) {
|
|
4031
|
+
out[`count_${op.toUpperCase()}`] = {
|
|
4032
|
+
type: GraphQLInt,
|
|
4033
|
+
deprecationReason: `Please use the relevant generic filter '{ count: { ${op}: ... } } }' instead.`
|
|
4034
|
+
};
|
|
4035
|
+
}
|
|
4036
|
+
return { ...out, ...this.aggregateInputEdgeNode(r) };
|
|
4037
|
+
});
|
|
4038
|
+
}
|
|
4039
|
+
relConnectionAggregateInput(r) {
|
|
4040
|
+
return this.input(`${prefix(r)}ConnectionAggregateInput`, () => {
|
|
4041
|
+
const self = this.relConnectionAggregateInput(r);
|
|
4042
|
+
return {
|
|
4043
|
+
AND: { type: list(nn(self)) },
|
|
4044
|
+
NOT: { type: self },
|
|
4045
|
+
OR: { type: list(nn(self)) },
|
|
4046
|
+
count: { type: this.connectionAggregationCountFilter() },
|
|
4047
|
+
...this.aggregateInputEdgeNode(r)
|
|
4048
|
+
};
|
|
4049
|
+
});
|
|
4050
|
+
}
|
|
4051
|
+
relFieldInput(r) {
|
|
4052
|
+
return this.input(`${prefix(r)}FieldInput`, () => ({
|
|
4053
|
+
connect: { type: list(nn(this.relConnectFieldInput(r))) },
|
|
4054
|
+
create: { type: list(nn(this.relCreateFieldInput(r))) }
|
|
4055
|
+
}));
|
|
4056
|
+
}
|
|
4057
|
+
relConnectFieldInput(r) {
|
|
4058
|
+
return this.input(`${prefix(r)}ConnectFieldInput`, () => {
|
|
4059
|
+
const target = this.model.node(r.target);
|
|
4060
|
+
const out = {};
|
|
4061
|
+
const connect = this.nodeConnect(target);
|
|
4062
|
+
if (connect) out.connect = { type: list(nn(connect)) };
|
|
4063
|
+
const p = this.props(r);
|
|
4064
|
+
if (p) out.edge = { type: this.propertiesCreateRef(p) };
|
|
4065
|
+
out.where = { type: this.nodeConnectWhere(target) };
|
|
4066
|
+
return out;
|
|
4067
|
+
});
|
|
4068
|
+
}
|
|
4069
|
+
relCreateFieldInput(r) {
|
|
4070
|
+
return this.input(`${prefix(r)}CreateFieldInput`, () => {
|
|
4071
|
+
const out = {};
|
|
4072
|
+
const p = this.props(r);
|
|
4073
|
+
if (p) out.edge = { type: this.propertiesCreateRef(p) };
|
|
4074
|
+
out.node = { type: nn(this.nodeCreate(this.model.node(r.target))) };
|
|
4075
|
+
return out;
|
|
4076
|
+
});
|
|
4077
|
+
}
|
|
4078
|
+
relDeleteFieldInput(r) {
|
|
4079
|
+
return this.input(`${prefix(r)}DeleteFieldInput`, () => {
|
|
4080
|
+
const out = {};
|
|
4081
|
+
const del = this.nodeDelete(this.model.node(r.target));
|
|
4082
|
+
if (del) out.delete = { type: del };
|
|
4083
|
+
out.where = { type: this.relConnectionWhere(r) };
|
|
4084
|
+
return out;
|
|
4085
|
+
});
|
|
4086
|
+
}
|
|
4087
|
+
relDisconnectFieldInput(r) {
|
|
4088
|
+
return this.input(`${prefix(r)}DisconnectFieldInput`, () => {
|
|
4089
|
+
const out = {};
|
|
4090
|
+
const dis = this.nodeDisconnect(this.model.node(r.target));
|
|
4091
|
+
if (dis) out.disconnect = { type: dis };
|
|
4092
|
+
out.where = { type: this.relConnectionWhere(r) };
|
|
4093
|
+
return out;
|
|
4094
|
+
});
|
|
4095
|
+
}
|
|
4096
|
+
relUpdateConnectionInput(r) {
|
|
4097
|
+
return this.input(`${prefix(r)}UpdateConnectionInput`, () => {
|
|
4098
|
+
const out = {};
|
|
4099
|
+
const p = this.props(r);
|
|
4100
|
+
if (p) out.edge = { type: this.propertiesUpdate(p) };
|
|
4101
|
+
out.node = { type: this.nodeUpdate(this.model.node(r.target)) };
|
|
4102
|
+
out.where = { type: this.relConnectionWhere(r) };
|
|
4103
|
+
return out;
|
|
4104
|
+
});
|
|
4105
|
+
}
|
|
4106
|
+
relUpdateFieldInput(r) {
|
|
4107
|
+
return this.input(`${prefix(r)}UpdateFieldInput`, () => ({
|
|
4108
|
+
connect: { type: list(nn(this.relConnectFieldInput(r))) },
|
|
4109
|
+
create: { type: list(nn(this.relCreateFieldInput(r))) },
|
|
4110
|
+
delete: { type: list(nn(this.relDeleteFieldInput(r))) },
|
|
4111
|
+
disconnect: { type: list(nn(this.relDisconnectFieldInput(r))) },
|
|
4112
|
+
update: { type: this.relUpdateConnectionInput(r) }
|
|
4113
|
+
}));
|
|
4114
|
+
}
|
|
4115
|
+
};
|
|
4116
|
+
function scalarRef(name) {
|
|
4117
|
+
return { name, list: false, required: false, elementRequired: false };
|
|
4118
|
+
}
|
|
4119
|
+
function prefix(r) {
|
|
4120
|
+
return `${r.source}${upperFirst(r.name)}`;
|
|
4121
|
+
}
|
|
4122
|
+
function relConnectionName(r) {
|
|
4123
|
+
return `${prefix(r)}Connection`;
|
|
4124
|
+
}
|
|
4125
|
+
function relationshipType(reg, r) {
|
|
4126
|
+
const target = reg.node(reg.model.node(r.target));
|
|
4127
|
+
if (r.list) {
|
|
4128
|
+
const inner = list(r.elementRequired ? nn(target) : target);
|
|
4129
|
+
return r.required ? nn(inner) : inner;
|
|
4130
|
+
}
|
|
4131
|
+
return r.required ? nn(target) : target;
|
|
4132
|
+
}
|
|
4133
|
+
function attributeOutputFields(reg, attributes) {
|
|
4134
|
+
const out = {};
|
|
4135
|
+
for (const a of attributes) {
|
|
4136
|
+
const field = {
|
|
4137
|
+
type: reg.attributeType(a.type),
|
|
4138
|
+
description: a.description,
|
|
4139
|
+
deprecationReason: a.deprecated
|
|
4140
|
+
};
|
|
4141
|
+
out[a.name] = field;
|
|
4142
|
+
}
|
|
4143
|
+
return out;
|
|
4144
|
+
}
|
|
4145
|
+
function aggregateSelectionFields(reg, attributes) {
|
|
4146
|
+
return Object.fromEntries(
|
|
4147
|
+
attributes.filter(isAggregable).map((a) => [a.name, { type: nn(reg.aggregateSelection(a.type.name)) }])
|
|
4148
|
+
);
|
|
4149
|
+
}
|
|
4150
|
+
function buildV7Schema(model) {
|
|
4151
|
+
const reg = new TypeRegistry(model);
|
|
4152
|
+
for (const n of model.nodes) {
|
|
4153
|
+
for (const r of n.relationships) {
|
|
4154
|
+
if (!r.list) {
|
|
4155
|
+
throw new Error(
|
|
4156
|
+
`${n.name}.${r.name}: non-list relationships are not supported by @cyphra/graphql yet.`
|
|
4157
|
+
);
|
|
4158
|
+
}
|
|
4159
|
+
}
|
|
4160
|
+
}
|
|
4161
|
+
const query = new GraphQLObjectType({
|
|
4162
|
+
name: "Query",
|
|
4163
|
+
fields: () => {
|
|
4164
|
+
const fields = {};
|
|
4165
|
+
for (const n of model.nodes) {
|
|
4166
|
+
const listArgs = {
|
|
4167
|
+
limit: { type: GraphQLInt },
|
|
4168
|
+
offset: { type: GraphQLInt },
|
|
4169
|
+
sort: { type: list(nn(reg.nodeSort(n))) },
|
|
4170
|
+
where: { type: reg.nodeWhere(n) }
|
|
4171
|
+
};
|
|
4172
|
+
fields[n.plural] = { type: nn(list(nn(reg.node(n)))), args: listArgs };
|
|
4173
|
+
fields[`${n.plural}Connection`] = {
|
|
4174
|
+
type: nn(reg.rootConnection(n)),
|
|
4175
|
+
args: {
|
|
4176
|
+
after: { type: GraphQLString },
|
|
4177
|
+
first: { type: GraphQLInt },
|
|
4178
|
+
sort: { type: list(nn(reg.nodeSort(n))) },
|
|
4179
|
+
where: { type: reg.nodeWhere(n) }
|
|
4180
|
+
}
|
|
4181
|
+
};
|
|
4182
|
+
}
|
|
4183
|
+
return fields;
|
|
4184
|
+
}
|
|
4185
|
+
});
|
|
4186
|
+
const mutation = new GraphQLObjectType({
|
|
4187
|
+
name: "Mutation",
|
|
4188
|
+
fields: () => {
|
|
4189
|
+
const fields = {};
|
|
4190
|
+
for (const n of model.nodes) {
|
|
4191
|
+
fields[`create${n.pascalPlural}`] = {
|
|
4192
|
+
type: nn(reg.mutationResponse(n, "Create")),
|
|
4193
|
+
args: { input: { type: nn(list(nn(reg.nodeCreate(n)))) } }
|
|
4194
|
+
};
|
|
4195
|
+
const del = reg.nodeDelete(n);
|
|
4196
|
+
fields[`delete${n.pascalPlural}`] = {
|
|
4197
|
+
type: nn(reg.deleteInfo()),
|
|
4198
|
+
args: {
|
|
4199
|
+
...del ? { delete: { type: del } } : {},
|
|
4200
|
+
where: { type: reg.nodeWhere(n) }
|
|
4201
|
+
}
|
|
4202
|
+
};
|
|
4203
|
+
fields[`update${n.pascalPlural}`] = {
|
|
4204
|
+
type: nn(reg.mutationResponse(n, "Update")),
|
|
4205
|
+
args: {
|
|
4206
|
+
update: { type: reg.nodeUpdate(n) },
|
|
4207
|
+
where: { type: reg.nodeWhere(n) }
|
|
4208
|
+
}
|
|
4209
|
+
};
|
|
4210
|
+
}
|
|
4211
|
+
return fields;
|
|
4212
|
+
}
|
|
4213
|
+
});
|
|
4214
|
+
return new GraphQLSchema({ query, mutation });
|
|
4215
|
+
}
|
|
4216
|
+
|
|
4217
|
+
// src/v7/index.ts
|
|
4218
|
+
var byResponseKey = (source, _args, _ctx, info) => source && typeof source === "object" ? source[info.path.key] : void 0;
|
|
4219
|
+
function rootReadResolver(model, execute, nodeName, kind) {
|
|
4220
|
+
return async (_source, args, _ctx, info) => {
|
|
4221
|
+
const node = model.node(nodeName);
|
|
4222
|
+
const compiler = new SelectionCompiler(model, info);
|
|
4223
|
+
const compiled = kind === "list" ? compiler.rootList(node, args, info.fieldNodes) : compiler.rootConnection(node, args, info.fieldNodes);
|
|
4224
|
+
return compiled.decode(await execute(compiled.cypher, compiled.params));
|
|
4225
|
+
};
|
|
4226
|
+
}
|
|
4227
|
+
function rootMutationResolver(model, execute, nodeName, kind) {
|
|
4228
|
+
return async (_source, args, _ctx, info) => {
|
|
4229
|
+
const node = model.node(nodeName);
|
|
4230
|
+
const compiler = new MutationCompiler(model, info);
|
|
4231
|
+
const a = args;
|
|
4232
|
+
const compiled = kind === "create" ? compiler.rootCreate(node, a, info.fieldNodes) : kind === "update" ? compiler.rootUpdate(node, a, info.fieldNodes) : compiler.rootDelete(node, a, info.fieldNodes);
|
|
4233
|
+
return execute(compiled.cypher, compiled.params, compiled.decode);
|
|
4234
|
+
};
|
|
4235
|
+
}
|
|
4236
|
+
function attachResolvers(schema, model, executors) {
|
|
4237
|
+
const execute = executors.read;
|
|
4238
|
+
for (const type of Object.values(schema.getTypeMap())) {
|
|
4239
|
+
if (!isObjectType(type) || type.name.startsWith("__")) continue;
|
|
4240
|
+
if (type === schema.getQueryType() || type === schema.getMutationType()) continue;
|
|
4241
|
+
for (const field of Object.values(type.getFields())) field.resolve = byResponseKey;
|
|
4242
|
+
}
|
|
4243
|
+
const query = schema.getQueryType().getFields();
|
|
4244
|
+
for (const node of model.nodes) {
|
|
4245
|
+
query[node.plural].resolve = rootReadResolver(model, execute, node.name, "list");
|
|
4246
|
+
query[`${node.plural}Connection`].resolve = rootReadResolver(
|
|
4247
|
+
model,
|
|
4248
|
+
execute,
|
|
4249
|
+
node.name,
|
|
4250
|
+
"connection"
|
|
4251
|
+
);
|
|
4252
|
+
}
|
|
4253
|
+
const mutation = schema.getMutationType().getFields();
|
|
4254
|
+
for (const node of model.nodes) {
|
|
4255
|
+
for (const kind of ["create", "update", "delete"]) {
|
|
4256
|
+
mutation[`${kind}${node.pascalPlural}`].resolve = rootMutationResolver(
|
|
4257
|
+
model,
|
|
4258
|
+
executors.write,
|
|
4259
|
+
node.name,
|
|
4260
|
+
kind
|
|
4261
|
+
);
|
|
4262
|
+
}
|
|
4263
|
+
}
|
|
4264
|
+
}
|
|
4265
|
+
function makeSchema(options) {
|
|
4266
|
+
const model = readTypeDefs(options.typeDefs);
|
|
4267
|
+
const schema = buildV7Schema(model);
|
|
4268
|
+
attachResolvers(schema, model, createExecutors(options));
|
|
4269
|
+
return schema;
|
|
4270
|
+
}
|
|
4271
|
+
function contextFor(opts = {}) {
|
|
4272
|
+
return opts.jwt ? { jwt: opts.jwt } : {};
|
|
4273
|
+
}
|
|
4274
|
+
function cyphraSchema(typeDefs) {
|
|
4275
|
+
const { document, issues } = convertGraphQLTypeDefs([
|
|
4276
|
+
{ name: "typeDefs.graphql", body: typeDefs }
|
|
4277
|
+
]);
|
|
4278
|
+
return { document, model: resolveSchema2(document), issues };
|
|
4279
|
+
}
|
|
4280
|
+
|
|
4281
|
+
// src/index.ts
|
|
4282
|
+
var compat = { v7: v7_exports };
|
|
4283
|
+
export {
|
|
4284
|
+
GraphQLImportError,
|
|
4285
|
+
UnsupportedTypeDefsError,
|
|
4286
|
+
compat,
|
|
4287
|
+
convertGraphQLTypeDefs,
|
|
4288
|
+
formatImportReport,
|
|
4289
|
+
mergeImportedSchema,
|
|
4290
|
+
printImportedSchema
|
|
4291
|
+
};
|
|
4292
|
+
//# sourceMappingURL=index.js.map
|