@coasys/ad4m 0.13.0-test-6 → 0.13.0-test-7
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/lib/index.cjs +111 -36
- package/lib/index.js +111 -36
- package/lib/src/model/Ad4mModel.d.ts +15 -0
- package/lib/src/model/Ad4mModel.js +94 -28
- package/lib/src/model/Ad4mModel.test.js +1434 -688
- package/lib/src/model/ModelQueryBuilder.js +17 -8
- package/lib/src/model/Subject.js +6 -6
- package/lib/src/model/hydration-batch.d.ts +34 -0
- package/lib/src/model/hydration-batch.js +147 -0
- package/lib/src/model/hydration-batching.test.d.ts +7 -0
- package/lib/src/model/hydration-batching.test.js +456 -0
- package/lib/src/model/model-manifest.d.ts +41 -0
- package/lib/src/model/model-manifest.js +11 -0
- package/lib/src/model/query-cache.test.d.ts +1 -0
- package/lib/src/model/query-cache.test.js +43 -0
- package/lib/src/model/query-sparql-batch.d.ts +17 -0
- package/lib/src/model/query-sparql-batch.js +260 -0
- package/lib/src/model/query-sparql.test.d.ts +1 -0
- package/lib/src/model/query-sparql.test.js +312 -0
- package/lib/src/model/relation-filtering.test.js +15 -15
- package/lib/src/model/subscription-delta.test.d.ts +24 -0
- package/lib/src/model/subscription-delta.test.js +180 -0
- package/lib/src/model/subscription-pool.d.ts +39 -0
- package/lib/src/model/subscription-pool.js +165 -0
- package/lib/src/perspectives/PerspectiveClient.test.d.ts +1 -0
- package/lib/src/perspectives/PerspectiveClient.test.js +224 -0
- package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
- package/lib/src/perspectives/PerspectiveResolver.js +0 -11
- package/lib/src/runtime/RuntimeResolver.d.ts +28 -1
- package/lib/src/runtime/RuntimeResolver.js +197 -4
- package/lib/src/schema.gql +27 -1
- package/lib/src/shacl/SHACLShape.test.js +82 -0
- package/package.json +8 -11
- package/src/model/Ad4mModel.ts +97 -26
- package/src/model/ModelQueryBuilder.ts +17 -7
- package/lib/src/model/query-surreal.d.ts +0 -44
- package/lib/src/model/query-surreal.js +0 -249
- package/lib/src/model/surreal-utils.d.ts +0 -42
- package/lib/src/model/surreal-utils.js +0 -128
|
@@ -333,4 +333,86 @@ describe('SHACLShape', () => {
|
|
|
333
333
|
expect(prop.remover).toEqual(original.properties[0].remover);
|
|
334
334
|
});
|
|
335
335
|
});
|
|
336
|
+
describe('sh:in round-trip', () => {
|
|
337
|
+
it('preserves sh:in enum values through toLinks() → fromLinks()', () => {
|
|
338
|
+
const original = new SHACLShape('test://Model');
|
|
339
|
+
original.addProperty({
|
|
340
|
+
name: 'status',
|
|
341
|
+
path: 'test://status',
|
|
342
|
+
datatype: 'xsd:string',
|
|
343
|
+
in: [
|
|
344
|
+
{ value: 'active', label: 'Active' },
|
|
345
|
+
{ value: 'inactive', label: 'Inactive' },
|
|
346
|
+
{ value: 'archived' },
|
|
347
|
+
],
|
|
348
|
+
});
|
|
349
|
+
const links = original.toLinks();
|
|
350
|
+
// Verify sh:in link was created
|
|
351
|
+
const inLink = links.find(l => l.predicate === 'sh://in');
|
|
352
|
+
expect(inLink).toBeDefined();
|
|
353
|
+
expect(inLink.target).toContain('literal:string:');
|
|
354
|
+
// Reconstruct and verify
|
|
355
|
+
const reconstructed = SHACLShape.fromLinks(links, 'test://ModelShape');
|
|
356
|
+
expect(reconstructed.properties[0].in).toBeDefined();
|
|
357
|
+
expect(reconstructed.properties[0].in).toEqual([
|
|
358
|
+
{ value: 'active', label: 'Active' },
|
|
359
|
+
{ value: 'inactive', label: 'Inactive' },
|
|
360
|
+
{ value: 'archived' },
|
|
361
|
+
]);
|
|
362
|
+
});
|
|
363
|
+
it('handles sh:in with special characters in values', () => {
|
|
364
|
+
const original = new SHACLShape('test://Model');
|
|
365
|
+
original.addProperty({
|
|
366
|
+
name: 'category',
|
|
367
|
+
path: 'test://category',
|
|
368
|
+
in: [
|
|
369
|
+
{ value: 'food & drink', label: 'Food & Drink' },
|
|
370
|
+
{ value: 'arts/crafts' },
|
|
371
|
+
],
|
|
372
|
+
});
|
|
373
|
+
const links = original.toLinks();
|
|
374
|
+
const reconstructed = SHACLShape.fromLinks(links, 'test://ModelShape');
|
|
375
|
+
expect(reconstructed.properties[0].in).toEqual(original.properties[0].in);
|
|
376
|
+
});
|
|
377
|
+
it('handles sh:in with empty array (no link created)', () => {
|
|
378
|
+
const original = new SHACLShape('test://Model');
|
|
379
|
+
original.addProperty({
|
|
380
|
+
name: 'field',
|
|
381
|
+
path: 'test://field',
|
|
382
|
+
in: [],
|
|
383
|
+
});
|
|
384
|
+
const links = original.toLinks();
|
|
385
|
+
const inLink = links.find(l => l.predicate === 'sh://in');
|
|
386
|
+
expect(inLink).toBeUndefined();
|
|
387
|
+
});
|
|
388
|
+
it('handles sh:in with literal://string: prefix variant', () => {
|
|
389
|
+
// fromLinks should handle both `literal:string:` and `literal://string:` prefixes
|
|
390
|
+
const links = [
|
|
391
|
+
{ source: 'test://ModelShape', predicate: 'sh://targetClass', target: 'test://Model' },
|
|
392
|
+
{ source: 'test://ModelShape', predicate: 'sh://property', target: 'test://Model.status' },
|
|
393
|
+
{ source: 'test://Model.status', predicate: 'sh://path', target: 'test://status' },
|
|
394
|
+
{ source: 'test://Model.status', predicate: 'sh://in', target: 'literal://string:[{"value":"a"},{"value":"b"}]' },
|
|
395
|
+
];
|
|
396
|
+
const reconstructed = SHACLShape.fromLinks(links, 'test://ModelShape');
|
|
397
|
+
expect(reconstructed.properties[0].in).toEqual([
|
|
398
|
+
{ value: 'a' },
|
|
399
|
+
{ value: 'b' },
|
|
400
|
+
]);
|
|
401
|
+
});
|
|
402
|
+
it('preserves sh:in through toJSON() → fromJSON()', () => {
|
|
403
|
+
const original = new SHACLShape('test://Model');
|
|
404
|
+
original.addProperty({
|
|
405
|
+
name: 'priority',
|
|
406
|
+
path: 'test://priority',
|
|
407
|
+
in: [
|
|
408
|
+
{ value: 'high', label: 'High' },
|
|
409
|
+
{ value: 'medium', label: 'Medium' },
|
|
410
|
+
{ value: 'low', label: 'Low' },
|
|
411
|
+
],
|
|
412
|
+
});
|
|
413
|
+
const json = original.toJSON();
|
|
414
|
+
const reconstructed = SHACLShape.fromJSON(json);
|
|
415
|
+
expect(reconstructed.properties[0].in).toEqual(original.properties[0].in);
|
|
416
|
+
});
|
|
417
|
+
});
|
|
336
418
|
});
|
package/package.json
CHANGED
|
@@ -5,12 +5,6 @@
|
|
|
5
5
|
"module": "lib/index.js",
|
|
6
6
|
"types": "lib/src/index.d.ts",
|
|
7
7
|
"type": "module",
|
|
8
|
-
"scripts": {
|
|
9
|
-
"build": "patch-package && tsc && pnpm run bundle",
|
|
10
|
-
"bundle": "rollup -c rollup.config.js",
|
|
11
|
-
"test": "jest --forceExit",
|
|
12
|
-
"generate:api-types": "cd ../rust-executor && TS_RS_EXPORT_DIR=../core/src/generated/api/ cargo test --lib 2>/dev/null && echo \"API types generated to core/src/generated/api/\""
|
|
13
|
-
},
|
|
14
8
|
"repository": {
|
|
15
9
|
"type": "git",
|
|
16
10
|
"url": "git+https://github.com/coasys/ad4m.git"
|
|
@@ -54,8 +48,11 @@
|
|
|
54
48
|
"ws": "8.13.0"
|
|
55
49
|
},
|
|
56
50
|
"patchedDependencies": {},
|
|
57
|
-
"
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
51
|
+
"version": "0.13.0-test-7",
|
|
52
|
+
"scripts": {
|
|
53
|
+
"build": "patch-package && tsc && pnpm run bundle",
|
|
54
|
+
"bundle": "rollup -c rollup.config.js",
|
|
55
|
+
"test": "jest --forceExit",
|
|
56
|
+
"generate:api-types": "cd ../rust-executor && TS_RS_EXPORT_DIR=../core/src/generated/api/ cargo test --lib 2>/dev/null && echo \"API types generated to core/src/generated/api/\""
|
|
57
|
+
}
|
|
58
|
+
}
|
package/src/model/Ad4mModel.ts
CHANGED
|
@@ -24,6 +24,46 @@ import type {
|
|
|
24
24
|
} from "./types";
|
|
25
25
|
|
|
26
26
|
|
|
27
|
+
// ---------------------------------------------------------------------------
|
|
28
|
+
// Default decoder for file-storage (non-literal resolveLanguage) properties
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* When the Rust executor resolves a non-literal expression it may return a
|
|
33
|
+
* `FileData`-shaped object (`{ data_base64, file_type, ... }`) rather than a
|
|
34
|
+
* raw URI string. If the model class has no custom `transform` registered
|
|
35
|
+
* (e.g. it was synthesised from a SHACL shape at runtime) we still want to
|
|
36
|
+
* decode the content rather than passing raw `FileData` to callers.
|
|
37
|
+
*
|
|
38
|
+
* Decoding rules (mirrors the JS `decodeFileAsJson` / `decodeFileAsString` helpers):
|
|
39
|
+
* - `application/json` (default when `file_type` is absent) → JSON.parse
|
|
40
|
+
* - anything else → raw decoded string
|
|
41
|
+
*
|
|
42
|
+
* If `resolved` is not a `FileData` object the value is returned unchanged so
|
|
43
|
+
* that callers can use this as a safe unconditional fallback.
|
|
44
|
+
*/
|
|
45
|
+
function defaultFileDecode(resolved: unknown): unknown {
|
|
46
|
+
if (
|
|
47
|
+
resolved !== null &&
|
|
48
|
+
typeof resolved === 'object' &&
|
|
49
|
+
'data_base64' in (resolved as object)
|
|
50
|
+
) {
|
|
51
|
+
const fd = resolved as { data_base64: string; file_type?: string };
|
|
52
|
+
let raw: string;
|
|
53
|
+
try {
|
|
54
|
+
raw = atob(fd.data_base64);
|
|
55
|
+
} catch {
|
|
56
|
+
return resolved; // malformed base64 — keep as-is
|
|
57
|
+
}
|
|
58
|
+
const isJson = !fd.file_type || fd.file_type === 'application/json';
|
|
59
|
+
if (isJson) {
|
|
60
|
+
try { return JSON.parse(raw); } catch { return raw; }
|
|
61
|
+
}
|
|
62
|
+
return raw;
|
|
63
|
+
}
|
|
64
|
+
return resolved;
|
|
65
|
+
}
|
|
66
|
+
|
|
27
67
|
// ---------------------------------------------------------------------------
|
|
28
68
|
// Helpers for Rust-side include resolution
|
|
29
69
|
// ---------------------------------------------------------------------------
|
|
@@ -926,6 +966,60 @@ export class Ad4mModel {
|
|
|
926
966
|
return arr.map((json: any) => jsonToModelInstance(this, perspective, json, include, properties));
|
|
927
967
|
}
|
|
928
968
|
|
|
969
|
+
/**
|
|
970
|
+
* Resolve non-literal (file-language) properties on an array of already-constructed
|
|
971
|
+
* model instances. Handles two cases:
|
|
972
|
+
*
|
|
973
|
+
* 1. The Rust executor returned a raw URI string → fetch via `getExpression` then apply transform.
|
|
974
|
+
* 2. The Rust executor already resolved the expression and returned a `FileData` object
|
|
975
|
+
* (happens when the perspective backend eagerly fetches file content) → apply transform
|
|
976
|
+
* (or `defaultFileDecode` if no transform is registered on the class, e.g. for SHACL-
|
|
977
|
+
* synthesised model classes).
|
|
978
|
+
*
|
|
979
|
+
* Extracted as a public static so `ModelQueryBuilder.subscribe()` can reuse it without
|
|
980
|
+
* duplicating logic or introducing a circular dependency.
|
|
981
|
+
* @internal
|
|
982
|
+
*/
|
|
983
|
+
static async resolveNonLiteralProps<T extends Ad4mModel>(
|
|
984
|
+
this: typeof Ad4mModel & (new (...args: any[]) => T),
|
|
985
|
+
perspective: PerspectiveProxy,
|
|
986
|
+
instances: T[],
|
|
987
|
+
): Promise<void> {
|
|
988
|
+
const propsMeta = getPropertiesMetadata(this as any);
|
|
989
|
+
const resolveProps = Object.entries(propsMeta).filter(
|
|
990
|
+
([, opts]: [string, any]) =>
|
|
991
|
+
opts.resolveLanguage != null &&
|
|
992
|
+
opts.resolveLanguage !== 'literal',
|
|
993
|
+
);
|
|
994
|
+
if (resolveProps.length === 0) return;
|
|
995
|
+
|
|
996
|
+
await Promise.all(
|
|
997
|
+
instances.map(async (inst: any) => {
|
|
998
|
+
for (const [propName, opts] of resolveProps) {
|
|
999
|
+
const val = inst[propName];
|
|
1000
|
+
const transform = (opts as any).transform;
|
|
1001
|
+
const applyTransform = (resolved: unknown) =>
|
|
1002
|
+
typeof transform === 'function' ? transform(resolved) : defaultFileDecode(resolved);
|
|
1003
|
+
|
|
1004
|
+
if (typeof val === 'string' && val && !val.startsWith('literal:')) {
|
|
1005
|
+
// Case 1: raw URI — fetch from language runtime
|
|
1006
|
+
try {
|
|
1007
|
+
const expression = await perspective.getExpression(val);
|
|
1008
|
+
if (expression) {
|
|
1009
|
+
let resolved: any;
|
|
1010
|
+
try { resolved = JSON.parse(expression.data); } catch { resolved = expression.data; }
|
|
1011
|
+
inst[propName] = applyTransform(resolved);
|
|
1012
|
+
}
|
|
1013
|
+
} catch (_) { /* resolution failed — keep raw value */ }
|
|
1014
|
+
} else if (val !== null && val !== undefined && typeof val === 'object') {
|
|
1015
|
+
// Case 2: already resolved by Rust — apply transform / default decode
|
|
1016
|
+
inst[propName] = applyTransform(val);
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
}),
|
|
1020
|
+
);
|
|
1021
|
+
}
|
|
1022
|
+
|
|
929
1023
|
// instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
|
|
930
1024
|
|
|
931
1025
|
/**
|
|
@@ -1085,32 +1179,9 @@ export class Ad4mModel {
|
|
|
1085
1179
|
|
|
1086
1180
|
// Resolve non-literal expressions (e.g. file languages where the stored
|
|
1087
1181
|
// value is a content-addressed hash that must be fetched from the language
|
|
1088
|
-
// runtime). The Rust endpoint
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
([, opts]: [string, any]) =>
|
|
1092
|
-
opts.resolveLanguage != null &&
|
|
1093
|
-
opts.resolveLanguage !== 'literal',
|
|
1094
|
-
);
|
|
1095
|
-
if (resolveProps.length > 0) {
|
|
1096
|
-
await Promise.all(
|
|
1097
|
-
instances.map(async (inst: any) => {
|
|
1098
|
-
for (const [propName, opts] of resolveProps) {
|
|
1099
|
-
const val = inst[propName];
|
|
1100
|
-
if (typeof val !== 'string' || !val || val.startsWith('literal:')) continue;
|
|
1101
|
-
try {
|
|
1102
|
-
const expression = await perspective.getExpression(val);
|
|
1103
|
-
if (expression) {
|
|
1104
|
-
let resolved: any;
|
|
1105
|
-
try { resolved = JSON.parse(expression.data); } catch { resolved = expression.data; }
|
|
1106
|
-
const transform = (opts as any).transform;
|
|
1107
|
-
inst[propName] = typeof transform === 'function' ? transform(resolved) : resolved;
|
|
1108
|
-
}
|
|
1109
|
-
} catch (_) { /* resolution failed — keep raw value */ }
|
|
1110
|
-
}
|
|
1111
|
-
}),
|
|
1112
|
-
);
|
|
1113
|
-
}
|
|
1182
|
+
// runtime). The Rust endpoint may return either a raw target URI (string)
|
|
1183
|
+
// or an already-resolved FileData object — both cases are handled here.
|
|
1184
|
+
await (this as any).resolveNonLiteralProps(perspective, instances);
|
|
1114
1185
|
|
|
1115
1186
|
// Take snapshots for dirty tracking
|
|
1116
1187
|
const snapshotRelations = queryInput.include;
|
|
@@ -391,8 +391,15 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
391
391
|
return (ctor as any).parseModelResult(this.perspective, raw, this.queryParams.include, this.queryParams.properties);
|
|
392
392
|
};
|
|
393
393
|
|
|
394
|
-
//
|
|
395
|
-
|
|
394
|
+
// Resolve non-literal (file-language) properties — handles both raw URI strings
|
|
395
|
+
// and already-resolved FileData objects returned by the Rust executor.
|
|
396
|
+
const resolveAndReturn = async (instances: T[]): Promise<T[]> => {
|
|
397
|
+
await (ctor as any).resolveNonLiteralProps(this.perspective, instances);
|
|
398
|
+
return instances;
|
|
399
|
+
};
|
|
400
|
+
|
|
401
|
+
// Parse initial results (with non-literal resolution)
|
|
402
|
+
const initialResults = await resolveAndReturn(parseResults(initialModelResult));
|
|
396
403
|
|
|
397
404
|
// Track last emitted result fingerprint to suppress duplicate callbacks
|
|
398
405
|
let lastResultFingerprint: string | null = null;
|
|
@@ -410,11 +417,14 @@ export class ModelQueryBuilder<T extends Ad4mModel> {
|
|
|
410
417
|
subscriptionId,
|
|
411
418
|
(rawResult: any) => {
|
|
412
419
|
try {
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
420
|
+
resolveAndReturn(parseResults(rawResult)).then((results) => {
|
|
421
|
+
const fp = buildFingerprint(results);
|
|
422
|
+
if (fp === lastResultFingerprint) return;
|
|
423
|
+
lastResultFingerprint = fp;
|
|
424
|
+
callback(results);
|
|
425
|
+
}).catch((e) => {
|
|
426
|
+
console.error('Model subscription update resolve error:', e);
|
|
427
|
+
});
|
|
418
428
|
} catch (e) {
|
|
419
429
|
console.error('Model subscription update parse error:', e);
|
|
420
430
|
}
|
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* SurrealQL query building utilities for Ad4mModel.
|
|
3
|
-
*
|
|
4
|
-
* Contains the graph-traversal WHERE clause builder, legacy
|
|
5
|
-
* subquery-based clause builders, SELECT-field builders, and
|
|
6
|
-
* the main `buildSurrealQLQuery()` function that produces a
|
|
7
|
-
* complete SurrealQL query string from a `Query` object.
|
|
8
|
-
*
|
|
9
|
-
* All functions are stateless — model metadata and relation metadata
|
|
10
|
-
* are passed in as parameters instead of accessed via `this`.
|
|
11
|
-
*
|
|
12
|
-
* @module
|
|
13
|
-
*/
|
|
14
|
-
import type { RelationMetadataEntry } from "./decorators";
|
|
15
|
-
import type { Where, Query, ModelMetadata } from "./types";
|
|
16
|
-
/**
|
|
17
|
-
* Builds WHERE clause filters using SurrealDB graph traversal syntax.
|
|
18
|
-
*
|
|
19
|
-
* Translates where conditions into `->link[WHERE ...]` / `<-link[WHERE ...]`
|
|
20
|
-
* filters that SurrealDB can optimize via graph indexes.
|
|
21
|
-
*
|
|
22
|
-
* @param metadata - Model metadata from `getModelMetadata()`
|
|
23
|
-
* @param allRelationsMetadata - Full relation metadata (needed for belongs-to
|
|
24
|
-
* direction detection)
|
|
25
|
-
* @param where - User-supplied where conditions
|
|
26
|
-
* @returns Combined AND-joined condition string, or empty string
|
|
27
|
-
*/
|
|
28
|
-
export declare function buildGraphTraversalWhereClause(metadata: ModelMetadata, allRelationsMetadata: Record<string, RelationMetadataEntry>, where?: Where): string;
|
|
29
|
-
/**
|
|
30
|
-
* Builds a complete SurrealQL query from a Query object and model metadata.
|
|
31
|
-
*
|
|
32
|
-
* This is the core implementation behind `Ad4mModel.queryToSurrealQL()`.
|
|
33
|
-
* It produces a graph-traversal query that:
|
|
34
|
-
* 1. Filters nodes by required predicates (conformance check)
|
|
35
|
-
* 2. Applies user WHERE conditions
|
|
36
|
-
* 3. Fetches all outgoing links for hydration
|
|
37
|
-
*
|
|
38
|
-
* @param metadata - Model metadata from `getModelMetadata()`
|
|
39
|
-
* @param allRelationsMetadata - Full relation registry (for belongs-to detection)
|
|
40
|
-
* @param query - Query parameters
|
|
41
|
-
* @param modelClass - The model class (for `resolveParentPredicate`)
|
|
42
|
-
* @returns Complete SurrealQL query string
|
|
43
|
-
*/
|
|
44
|
-
export declare function buildSurrealQLQuery(metadata: ModelMetadata, allRelationsMetadata: Record<string, RelationMetadataEntry>, query: Query, modelClass: any): string;
|
|
@@ -1,249 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* SurrealQL query building utilities for Ad4mModel.
|
|
3
|
-
*
|
|
4
|
-
* Contains the graph-traversal WHERE clause builder, legacy
|
|
5
|
-
* subquery-based clause builders, SELECT-field builders, and
|
|
6
|
-
* the main `buildSurrealQLQuery()` function that produces a
|
|
7
|
-
* complete SurrealQL query string from a `Query` object.
|
|
8
|
-
*
|
|
9
|
-
* All functions are stateless — model metadata and relation metadata
|
|
10
|
-
* are passed in as parameters instead of accessed via `this`.
|
|
11
|
-
*
|
|
12
|
-
* @module
|
|
13
|
-
*/
|
|
14
|
-
import { escapeSurrealString } from "../utils";
|
|
15
|
-
import { formatSurrealValue } from "./surreal-utils";
|
|
16
|
-
import { resolveParentPredicate } from "./query-common";
|
|
17
|
-
// ─── Graph Traversal WHERE Clause ────────────────────────────────────────────
|
|
18
|
-
/**
|
|
19
|
-
* Builds WHERE clause filters using SurrealDB graph traversal syntax.
|
|
20
|
-
*
|
|
21
|
-
* Translates where conditions into `->link[WHERE ...]` / `<-link[WHERE ...]`
|
|
22
|
-
* filters that SurrealDB can optimize via graph indexes.
|
|
23
|
-
*
|
|
24
|
-
* @param metadata - Model metadata from `getModelMetadata()`
|
|
25
|
-
* @param allRelationsMetadata - Full relation metadata (needed for belongs-to
|
|
26
|
-
* direction detection)
|
|
27
|
-
* @param where - User-supplied where conditions
|
|
28
|
-
* @returns Combined AND-joined condition string, or empty string
|
|
29
|
-
*/
|
|
30
|
-
export function buildGraphTraversalWhereClause(metadata, allRelationsMetadata, where) {
|
|
31
|
-
if (!where)
|
|
32
|
-
return '';
|
|
33
|
-
const conditions = [];
|
|
34
|
-
for (const [propertyName, condition] of Object.entries(where)) {
|
|
35
|
-
const isSpecial = ['id', 'author', 'timestamp'].includes(propertyName);
|
|
36
|
-
if (isSpecial) {
|
|
37
|
-
if (propertyName === 'author' || propertyName === 'timestamp') {
|
|
38
|
-
continue; // Filtered post-query in JS
|
|
39
|
-
}
|
|
40
|
-
const columnName = 'uri';
|
|
41
|
-
if (Array.isArray(condition)) {
|
|
42
|
-
const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
|
|
43
|
-
conditions.push(`${columnName} IN [${formattedValues}]`);
|
|
44
|
-
}
|
|
45
|
-
else if (typeof condition === 'object' && condition !== null) {
|
|
46
|
-
const ops = condition;
|
|
47
|
-
if (ops.not !== undefined) {
|
|
48
|
-
if (Array.isArray(ops.not)) {
|
|
49
|
-
const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
|
|
50
|
-
conditions.push(`${columnName} NOT IN [${formattedValues}]`);
|
|
51
|
-
}
|
|
52
|
-
else {
|
|
53
|
-
conditions.push(`${columnName} != ${formatSurrealValue(ops.not)}`);
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
|
|
57
|
-
conditions.push(`${columnName} >= ${formatSurrealValue(ops.between[0])} AND ${columnName} <= ${formatSurrealValue(ops.between[1])}`);
|
|
58
|
-
}
|
|
59
|
-
if (ops.gt !== undefined) {
|
|
60
|
-
conditions.push(`${columnName} > ${formatSurrealValue(ops.gt)}`);
|
|
61
|
-
}
|
|
62
|
-
if (ops.gte !== undefined) {
|
|
63
|
-
conditions.push(`${columnName} >= ${formatSurrealValue(ops.gte)}`);
|
|
64
|
-
}
|
|
65
|
-
if (ops.lt !== undefined) {
|
|
66
|
-
conditions.push(`${columnName} < ${formatSurrealValue(ops.lt)}`);
|
|
67
|
-
}
|
|
68
|
-
if (ops.lte !== undefined) {
|
|
69
|
-
conditions.push(`${columnName} <= ${formatSurrealValue(ops.lte)}`);
|
|
70
|
-
}
|
|
71
|
-
if (ops.contains !== undefined) {
|
|
72
|
-
conditions.push(`${columnName} CONTAINS ${formatSurrealValue(ops.contains)}`);
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
else {
|
|
76
|
-
conditions.push(`${columnName} = ${formatSurrealValue(condition)}`);
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
else {
|
|
80
|
-
// Regular properties — check relation metadata first for direction
|
|
81
|
-
const relMeta = allRelationsMetadata[propertyName];
|
|
82
|
-
const isBelongs = relMeta?.kind === 'belongsToOne' || relMeta?.kind === 'belongsToMany';
|
|
83
|
-
if (relMeta) {
|
|
84
|
-
const predicate = escapeSurrealString(relMeta.predicate);
|
|
85
|
-
if (Array.isArray(condition)) {
|
|
86
|
-
const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
|
|
87
|
-
if (isBelongs) {
|
|
88
|
-
conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) > 0`);
|
|
89
|
-
}
|
|
90
|
-
else {
|
|
91
|
-
conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) > 0`);
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
else if (typeof condition === 'object' && condition !== null) {
|
|
95
|
-
const ops = condition;
|
|
96
|
-
if (ops.not !== undefined) {
|
|
97
|
-
if (Array.isArray(ops.not)) {
|
|
98
|
-
const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
|
|
99
|
-
if (isBelongs) {
|
|
100
|
-
conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) = 0`);
|
|
101
|
-
}
|
|
102
|
-
else {
|
|
103
|
-
conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) = 0`);
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
else {
|
|
107
|
-
if (isBelongs) {
|
|
108
|
-
conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${formatSurrealValue(ops.not)}]) = 0`);
|
|
109
|
-
}
|
|
110
|
-
else {
|
|
111
|
-
conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${formatSurrealValue(ops.not)}]) = 0`);
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
else {
|
|
117
|
-
if (isBelongs) {
|
|
118
|
-
conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${formatSurrealValue(condition)}]) > 0`);
|
|
119
|
-
}
|
|
120
|
-
else {
|
|
121
|
-
conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${formatSurrealValue(condition)}]) > 0`);
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
continue;
|
|
125
|
-
}
|
|
126
|
-
const propMeta = metadata.properties[propertyName];
|
|
127
|
-
if (!propMeta)
|
|
128
|
-
continue;
|
|
129
|
-
const predicate = escapeSurrealString(propMeta.predicate);
|
|
130
|
-
const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(out.uri)' : 'out.uri';
|
|
131
|
-
if (Array.isArray(condition)) {
|
|
132
|
-
const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
|
|
133
|
-
conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
|
|
134
|
-
}
|
|
135
|
-
else if (typeof condition === 'object' && condition !== null) {
|
|
136
|
-
const ops = condition;
|
|
137
|
-
if (ops.not !== undefined) {
|
|
138
|
-
if (Array.isArray(ops.not)) {
|
|
139
|
-
const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
|
|
140
|
-
conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
|
|
141
|
-
}
|
|
142
|
-
else {
|
|
143
|
-
conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`);
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
147
|
-
ops.lt !== undefined || ops.lte !== undefined ||
|
|
148
|
-
ops.between !== undefined || ops.contains !== undefined;
|
|
149
|
-
if (hasComparisonOps) {
|
|
150
|
-
conditions.push(`count(->link[WHERE predicate = '${predicate}']) > 0`);
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
else {
|
|
154
|
-
conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`);
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
return conditions.join(' AND ');
|
|
159
|
-
}
|
|
160
|
-
// ─── Main Query Builder ─────────────────────────────────────────────────────
|
|
161
|
-
/**
|
|
162
|
-
* Builds a complete SurrealQL query from a Query object and model metadata.
|
|
163
|
-
*
|
|
164
|
-
* This is the core implementation behind `Ad4mModel.queryToSurrealQL()`.
|
|
165
|
-
* It produces a graph-traversal query that:
|
|
166
|
-
* 1. Filters nodes by required predicates (conformance check)
|
|
167
|
-
* 2. Applies user WHERE conditions
|
|
168
|
-
* 3. Fetches all outgoing links for hydration
|
|
169
|
-
*
|
|
170
|
-
* @param metadata - Model metadata from `getModelMetadata()`
|
|
171
|
-
* @param allRelationsMetadata - Full relation registry (for belongs-to detection)
|
|
172
|
-
* @param query - Query parameters
|
|
173
|
-
* @param modelClass - The model class (for `resolveParentPredicate`)
|
|
174
|
-
* @returns Complete SurrealQL query string
|
|
175
|
-
*/
|
|
176
|
-
export function buildSurrealQLQuery(metadata, allRelationsMetadata, query, modelClass) {
|
|
177
|
-
const { where } = query;
|
|
178
|
-
// Build graph traversal filters for required predicates
|
|
179
|
-
const graphTraversalFilters = [];
|
|
180
|
-
// Parent filter
|
|
181
|
-
if (query.parent) {
|
|
182
|
-
const parentPredicate = resolveParentPredicate(query.parent, modelClass);
|
|
183
|
-
graphTraversalFilters.push(`count(<-link[WHERE in.uri = ${formatSurrealValue(query.parent.id)} AND predicate = '${escapeSurrealString(parentPredicate)}']) > 0`);
|
|
184
|
-
}
|
|
185
|
-
// Required property filters
|
|
186
|
-
for (const [, propMeta] of Object.entries(metadata.properties)) {
|
|
187
|
-
if (propMeta.required) {
|
|
188
|
-
if (propMeta.getter)
|
|
189
|
-
continue;
|
|
190
|
-
if (propMeta.flag && propMeta.initial) {
|
|
191
|
-
graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
|
|
192
|
-
}
|
|
193
|
-
else {
|
|
194
|
-
graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
// Fallback: initial-value filters
|
|
199
|
-
if (graphTraversalFilters.length === 0) {
|
|
200
|
-
for (const [, propMeta] of Object.entries(metadata.properties)) {
|
|
201
|
-
if (propMeta.initial) {
|
|
202
|
-
if (propMeta.flag) {
|
|
203
|
-
graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
|
|
204
|
-
}
|
|
205
|
-
else {
|
|
206
|
-
graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
|
|
207
|
-
}
|
|
208
|
-
break;
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
// Fallback: open-world structural matching
|
|
213
|
-
if (graphTraversalFilters.length === 0) {
|
|
214
|
-
const structuralPredicates = [];
|
|
215
|
-
for (const [, propMeta] of Object.entries(metadata.properties)) {
|
|
216
|
-
if (propMeta.predicate) {
|
|
217
|
-
structuralPredicates.push(`predicate = '${escapeSurrealString(propMeta.predicate)}'`);
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
if (metadata.relations) {
|
|
221
|
-
for (const [, relMeta] of Object.entries(metadata.relations)) {
|
|
222
|
-
if (relMeta.predicate) {
|
|
223
|
-
structuralPredicates.push(`predicate = '${escapeSurrealString(relMeta.predicate)}'`);
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
if (structuralPredicates.length > 0) {
|
|
228
|
-
graphTraversalFilters.push(`count(->link[WHERE (${structuralPredicates.join(' OR ')})]) > 0`);
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
// User WHERE clause
|
|
232
|
-
const userWhereClause = buildGraphTraversalWhereClause(metadata, allRelationsMetadata, where);
|
|
233
|
-
const whereConditions = [];
|
|
234
|
-
whereConditions.push(...graphTraversalFilters);
|
|
235
|
-
if (userWhereClause) {
|
|
236
|
-
whereConditions.push(userWhereClause);
|
|
237
|
-
}
|
|
238
|
-
whereConditions.push(`count(->link) > 0`);
|
|
239
|
-
const fullQuery = `
|
|
240
|
-
SELECT
|
|
241
|
-
id AS source,
|
|
242
|
-
uri AS source_uri,
|
|
243
|
-
->link AS links
|
|
244
|
-
FROM node
|
|
245
|
-
WHERE ${whereConditions.join(' AND ')}
|
|
246
|
-
FETCH links
|
|
247
|
-
`.trim();
|
|
248
|
-
return fullQuery;
|
|
249
|
-
}
|
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Shared SurrealQL compilation utilities.
|
|
3
|
-
*
|
|
4
|
-
* These functions are used by both the runtime query builder (`Ad4mModel`) and
|
|
5
|
-
* the compile-time SHACL generator (`decorators.ts`).
|
|
6
|
-
*/
|
|
7
|
-
import type { WhereCondition, Where, ModelMetadata } from "./types";
|
|
8
|
-
/**
|
|
9
|
-
* Format a JavaScript value for embedding in a SurrealQL expression.
|
|
10
|
-
*
|
|
11
|
-
* - Strings are single-quoted with backslash / quote / newline escaping
|
|
12
|
-
* - Numbers and booleans are passed through as-is
|
|
13
|
-
* - Arrays are recursed
|
|
14
|
-
*/
|
|
15
|
-
export declare function formatSurrealValue(value: any): string;
|
|
16
|
-
/**
|
|
17
|
-
* Compile a single Where condition for a property into a SurrealQL
|
|
18
|
-
* graph-traversal sub-expression.
|
|
19
|
-
*
|
|
20
|
-
* Operates on the **target node** — generates `count(->link[WHERE ...]) > 0`
|
|
21
|
-
* style checks that can be used inside a `[WHERE ...]` filter on nodes.
|
|
22
|
-
*
|
|
23
|
-
* @param predicate - The predicate URI for the property
|
|
24
|
-
* @param condition - The Where condition value
|
|
25
|
-
* @param opts - Optional settings (e.g. `resolveLanguage`)
|
|
26
|
-
* @returns A single SurrealQL condition string
|
|
27
|
-
*/
|
|
28
|
-
export declare function buildWhereCondition(predicate: string, condition: WhereCondition, opts?: {
|
|
29
|
-
resolveLanguage?: string;
|
|
30
|
-
}): string;
|
|
31
|
-
/**
|
|
32
|
-
* Compile a full `Where` clause to an array of SurrealQL condition strings.
|
|
33
|
-
*
|
|
34
|
-
* When `metadata` is provided, property names are resolved to predicates
|
|
35
|
-
* using the model's property metadata. When `metadata` is `null`, property
|
|
36
|
-
* names are treated as raw predicate URIs.
|
|
37
|
-
*
|
|
38
|
-
* Only handles **regular properties** — special fields (`id`, `author`,
|
|
39
|
-
* `timestamp`) and relation fields are skipped (they are only relevant at
|
|
40
|
-
* runtime query time, not for compile-time getter generation).
|
|
41
|
-
*/
|
|
42
|
-
export declare function compileWhereClause(where: Where, metadata: ModelMetadata | null): string[];
|