@coasys/ad4m 0.12.1-dev → 0.13.0-test-2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/index.cjs +1469 -781
- package/lib/index.js +1453 -779
- package/lib/src/Literal.js +6 -5
- package/lib/src/agent/AgentClient.d.ts +8 -1
- package/lib/src/agent/AgentClient.js +73 -2
- package/lib/src/expression/ExpressionRef.js +2 -2
- package/lib/src/language/Language.d.ts +41 -3
- package/lib/src/model/Ad4mModel.d.ts +28 -28
- package/lib/src/model/Ad4mModel.js +129 -101
- package/lib/src/model/Ad4mModel.test.js +1543 -535
- package/lib/src/model/ModelQueryBuilder.d.ts +48 -34
- package/lib/src/model/ModelQueryBuilder.js +163 -78
- package/lib/src/model/Subject.js +6 -6
- package/lib/src/model/decorators.d.ts +14 -8
- package/lib/src/model/decorators.js +41 -14
- package/lib/src/model/hydration-batch.d.ts +34 -0
- package/lib/src/model/hydration-batch.js +147 -0
- package/lib/src/model/hydration.d.ts +3 -3
- package/lib/src/model/hydration.js +106 -36
- package/lib/src/model/index.d.ts +4 -1
- package/lib/src/model/index.js +4 -1
- package/lib/src/model/json-schema.js +2 -2
- package/lib/src/model/query-cache.d.ts +30 -0
- package/lib/src/model/query-cache.js +66 -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-common.d.ts +1 -1
- package/lib/src/model/query-common.js +1 -1
- 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.d.ts +47 -0
- package/lib/src/model/query-sparql.js +336 -0
- package/lib/src/model/query-utils.d.ts +45 -0
- package/lib/src/model/query-utils.js +140 -0
- package/lib/src/model/relation-filtering.test.js +15 -15
- package/lib/src/model/sdna.js +1 -1
- package/lib/src/model/shacl-gen.js +42 -18
- package/lib/src/model/subscription-pool.d.ts +39 -0
- package/lib/src/model/subscription-pool.js +119 -0
- package/lib/src/model/types.d.ts +3 -3
- package/lib/src/model/types.js +1 -1
- package/lib/src/perspectives/PerspectiveClient.d.ts +1 -17
- package/lib/src/perspectives/PerspectiveClient.js +5 -57
- package/lib/src/perspectives/PerspectiveProxy.d.ts +51 -30
- package/lib/src/perspectives/PerspectiveProxy.js +224 -177
- package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
- package/lib/src/perspectives/PerspectiveResolver.js +0 -11
- package/lib/src/perspectives/WakerSubscriptionManager.d.ts +3 -3
- package/lib/src/perspectives/WakerSubscriptionManager.js +7 -8
- package/lib/src/runtime/RuntimeClient.d.ts +2 -0
- package/lib/src/runtime/RuntimeClient.js +17 -0
- package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
- package/lib/src/runtime/RuntimeResolver.js +84 -0
- package/lib/src/schema.gql +14 -1
- package/lib/src/shacl/SHACLFlow.d.ts +1 -1
- package/lib/src/shacl/SHACLFlow.js +9 -9
- package/lib/src/shacl/SHACLShape.d.ts +1 -1
- package/lib/src/shacl/SHACLShape.js +38 -38
- package/lib/src/typeDefs.js +14 -1
- package/lib/src/utils.d.ts +6 -6
- package/lib/src/utils.js +6 -6
- package/package.json +1 -1
- package/src/Literal.test.ts +10 -5
- package/src/Literal.ts +6 -5
- package/src/agent/AgentClient.ts +81 -1
- package/src/expression/ExpressionRef.ts +2 -2
- package/src/language/Language.ts +48 -3
- package/src/model/Ad4mModel.test.ts +1515 -565
- package/src/model/Ad4mModel.ts +142 -102
- package/src/model/ModelQueryBuilder.ts +185 -86
- package/src/model/Subject.ts +6 -6
- package/src/model/decorators.ts +51 -22
- package/src/model/hydration-batch.ts +205 -0
- package/src/model/hydration.ts +102 -39
- package/src/model/index.ts +4 -1
- package/src/model/json-schema.ts +2 -2
- package/src/model/query-cache.test.ts +54 -0
- package/src/model/query-cache.ts +79 -0
- package/src/model/query-common.ts +1 -1
- package/src/model/query-sparql-batch.ts +301 -0
- package/src/model/query-sparql.ts +363 -0
- package/src/model/{surreal-utils.ts → query-utils.ts} +40 -27
- package/src/model/relation-filtering.test.ts +15 -15
- package/src/model/sdna.ts +1 -1
- package/src/model/shacl-gen.ts +42 -17
- package/src/model/subscription-pool.ts +163 -0
- package/src/model/types.ts +3 -3
- package/src/perspectives/PerspectiveClient.ts +5 -61
- package/src/perspectives/PerspectiveProxy.ts +226 -181
- package/src/perspectives/PerspectiveResolver.ts +0 -8
- package/src/perspectives/WakerSubscriptionManager.ts +8 -9
- package/src/runtime/RuntimeClient.ts +19 -0
- package/src/runtime/RuntimeResolver.ts +58 -0
- package/src/shacl/SHACLFlow.ts +9 -9
- package/src/shacl/SHACLShape.ts +39 -39
- package/src/utils.ts +6 -6
- package/src/model/query-surreal.ts +0 -280
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Query Result TTL Cache
|
|
3
|
+
*
|
|
4
|
+
* Short-lived cache (200ms TTL) for SPARQL query results.
|
|
5
|
+
* Prevents redundant queries during rapid render cycles where
|
|
6
|
+
* multiple components issue the same query within milliseconds.
|
|
7
|
+
*
|
|
8
|
+
* Key: `perspectiveUUID + queryText`
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* Get a cached query result if it exists and hasn't expired.
|
|
12
|
+
*/
|
|
13
|
+
export declare function getCachedResult(perspectiveUUID: string, queryText: string): any | undefined;
|
|
14
|
+
/**
|
|
15
|
+
* Store a query result in the cache with TTL.
|
|
16
|
+
*/
|
|
17
|
+
export declare function setCachedResult(perspectiveUUID: string, queryText: string, result: any, ttlMs?: number): void;
|
|
18
|
+
/**
|
|
19
|
+
* Invalidate all cache entries for a given perspective.
|
|
20
|
+
* Called after write operations to ensure stale data isn't served.
|
|
21
|
+
*/
|
|
22
|
+
export declare function invalidatePerspectiveCache(perspectiveUUID: string): void;
|
|
23
|
+
/**
|
|
24
|
+
* Clear all cache entries (useful for testing).
|
|
25
|
+
*/
|
|
26
|
+
export declare function clearQueryCache(): void;
|
|
27
|
+
/**
|
|
28
|
+
* Get the current size of the cache (useful for testing).
|
|
29
|
+
*/
|
|
30
|
+
export declare function queryCacheSize(): number;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Query Result TTL Cache
|
|
3
|
+
*
|
|
4
|
+
* Short-lived cache (200ms TTL) for SPARQL query results.
|
|
5
|
+
* Prevents redundant queries during rapid render cycles where
|
|
6
|
+
* multiple components issue the same query within milliseconds.
|
|
7
|
+
*
|
|
8
|
+
* Key: `perspectiveUUID + queryText`
|
|
9
|
+
*/
|
|
10
|
+
const cache = new Map();
|
|
11
|
+
const DEFAULT_TTL_MS = 200;
|
|
12
|
+
function makeKey(perspectiveUUID, queryText) {
|
|
13
|
+
return `${perspectiveUUID}:${queryText}`;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Get a cached query result if it exists and hasn't expired.
|
|
17
|
+
*/
|
|
18
|
+
export function getCachedResult(perspectiveUUID, queryText) {
|
|
19
|
+
const key = makeKey(perspectiveUUID, queryText);
|
|
20
|
+
const entry = cache.get(key);
|
|
21
|
+
if (!entry)
|
|
22
|
+
return undefined;
|
|
23
|
+
if (Date.now() > entry.expiry) {
|
|
24
|
+
cache.delete(key);
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
return entry.result;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Store a query result in the cache with TTL.
|
|
31
|
+
*/
|
|
32
|
+
export function setCachedResult(perspectiveUUID, queryText, result, ttlMs = DEFAULT_TTL_MS) {
|
|
33
|
+
// Lazy eviction of expired entries
|
|
34
|
+
const now = Date.now();
|
|
35
|
+
for (const [key, entry] of cache) {
|
|
36
|
+
if (now > entry.expiry) {
|
|
37
|
+
cache.delete(key);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
const cacheKey = makeKey(perspectiveUUID, queryText);
|
|
41
|
+
cache.set(cacheKey, { result, expiry: now + ttlMs });
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Invalidate all cache entries for a given perspective.
|
|
45
|
+
* Called after write operations to ensure stale data isn't served.
|
|
46
|
+
*/
|
|
47
|
+
export function invalidatePerspectiveCache(perspectiveUUID) {
|
|
48
|
+
const prefix = perspectiveUUID + ':';
|
|
49
|
+
for (const [key] of cache) {
|
|
50
|
+
if (key.startsWith(prefix)) {
|
|
51
|
+
cache.delete(key);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Clear all cache entries (useful for testing).
|
|
57
|
+
*/
|
|
58
|
+
export function clearQueryCache() {
|
|
59
|
+
cache.clear();
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Get the current size of the cache (useful for testing).
|
|
63
|
+
*/
|
|
64
|
+
export function queryCacheSize() {
|
|
65
|
+
return cache.size;
|
|
66
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { getCachedResult, setCachedResult, invalidatePerspectiveCache, clearQueryCache, queryCacheSize } from './query-cache';
|
|
2
|
+
describe('query-cache', () => {
|
|
3
|
+
beforeEach(() => {
|
|
4
|
+
clearQueryCache();
|
|
5
|
+
});
|
|
6
|
+
describe('lazy eviction', () => {
|
|
7
|
+
it('should remove expired entries when setting a new one', () => {
|
|
8
|
+
// Insert with a very short TTL
|
|
9
|
+
setCachedResult('p1', 'SELECT ?x', 'result1', 1);
|
|
10
|
+
expect(queryCacheSize()).toBe(1);
|
|
11
|
+
// Wait for expiry
|
|
12
|
+
const start = Date.now();
|
|
13
|
+
while (Date.now() - start < 5) { /* busy wait 5ms */ }
|
|
14
|
+
// Expired entry should still be in the map (not yet evicted)
|
|
15
|
+
// but getCachedResult should return undefined
|
|
16
|
+
expect(getCachedResult('p1', 'SELECT ?x')).toBeUndefined();
|
|
17
|
+
// Setting a new entry should evict the expired one
|
|
18
|
+
setCachedResult('p2', 'SELECT ?y', 'result2', 10000);
|
|
19
|
+
// Only the new entry should remain
|
|
20
|
+
expect(queryCacheSize()).toBe(1);
|
|
21
|
+
expect(getCachedResult('p2', 'SELECT ?y')).toBe('result2');
|
|
22
|
+
});
|
|
23
|
+
});
|
|
24
|
+
describe('invalidatePerspectiveCache', () => {
|
|
25
|
+
it('should remove all entries for a specific perspective', () => {
|
|
26
|
+
setCachedResult('p1', 'query1', 'r1', 10000);
|
|
27
|
+
setCachedResult('p1', 'query2', 'r2', 10000);
|
|
28
|
+
setCachedResult('p2', 'query1', 'r3', 10000);
|
|
29
|
+
expect(queryCacheSize()).toBe(3);
|
|
30
|
+
invalidatePerspectiveCache('p1');
|
|
31
|
+
expect(queryCacheSize()).toBe(1);
|
|
32
|
+
expect(getCachedResult('p1', 'query1')).toBeUndefined();
|
|
33
|
+
expect(getCachedResult('p1', 'query2')).toBeUndefined();
|
|
34
|
+
expect(getCachedResult('p2', 'query1')).toBe('r3');
|
|
35
|
+
});
|
|
36
|
+
it('should not affect other perspectives', () => {
|
|
37
|
+
setCachedResult('p1', 'q', 'r1', 10000);
|
|
38
|
+
setCachedResult('p2', 'q', 'r2', 10000);
|
|
39
|
+
invalidatePerspectiveCache('p3');
|
|
40
|
+
expect(queryCacheSize()).toBe(2);
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
});
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Batch SPARQL query builder for Ad4mModel eager-loading (includes).
|
|
3
|
+
*
|
|
4
|
+
* Uses direct triple + named graph storage model.
|
|
5
|
+
* Each AD4M link is stored as: <source> <predicate> <target> in a named graph
|
|
6
|
+
* with metadata in the default graph keyed by graph IRI.
|
|
7
|
+
*
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
import type { Query, ModelMetadata } from "./types";
|
|
11
|
+
/**
|
|
12
|
+
* Build a single SPARQL query that fetches root instances plus all
|
|
13
|
+
* included relations in one query using UNION branches.
|
|
14
|
+
*
|
|
15
|
+
* Uses direct triple patterns in named graphs with metadata in default graph.
|
|
16
|
+
*/
|
|
17
|
+
export declare function buildBatchSPARQLQuery(rootMetadata: ModelMetadata, query: Query, rootModelClass: any): string;
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Batch SPARQL query builder for Ad4mModel eager-loading (includes).
|
|
3
|
+
*
|
|
4
|
+
* Uses direct triple + named graph storage model.
|
|
5
|
+
* Each AD4M link is stored as: <source> <predicate> <target> in a named graph
|
|
6
|
+
* with metadata in the default graph keyed by graph IRI.
|
|
7
|
+
*
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
import { resolveParentPredicate } from "./query-common";
|
|
11
|
+
import { getRelationsMetadata } from "./decorators";
|
|
12
|
+
import { Literal } from "../Literal";
|
|
13
|
+
// ──────────────────────────────────────────────────────────
|
|
14
|
+
// Helpers
|
|
15
|
+
// ──────────────────────────────────────────────────────────
|
|
16
|
+
function iri(value) {
|
|
17
|
+
return `<${value}>`;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Check if a string value looks like a URI (has a scheme).
|
|
21
|
+
*/
|
|
22
|
+
function looksLikeUri(value) {
|
|
23
|
+
return /^[a-zA-Z][a-zA-Z0-9+\-._]*:/.test(value);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Convert a JS value to its literal: IRI form.
|
|
27
|
+
*/
|
|
28
|
+
function valueToLiteralIri(value) {
|
|
29
|
+
if (typeof value === 'string') {
|
|
30
|
+
if (looksLikeUri(value))
|
|
31
|
+
return value;
|
|
32
|
+
return Literal.from(value).toUrl();
|
|
33
|
+
}
|
|
34
|
+
if (typeof value === 'number')
|
|
35
|
+
return Literal.from(value).toUrl();
|
|
36
|
+
if (typeof value === 'boolean')
|
|
37
|
+
return Literal.from(value).toUrl();
|
|
38
|
+
return Literal.from(String(value)).toUrl();
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Determine if a property stores values as literal: IRIs.
|
|
42
|
+
*/
|
|
43
|
+
function isLiteralStoredProperty(propMeta) {
|
|
44
|
+
if (propMeta.flag)
|
|
45
|
+
return false;
|
|
46
|
+
if (propMeta.resolveLanguage && propMeta.resolveLanguage !== "literal")
|
|
47
|
+
return false;
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
function buildConformanceJoins(metadata, sourceVar, prefix) {
|
|
51
|
+
const joins = [];
|
|
52
|
+
const filters = [];
|
|
53
|
+
let hasConformance = false;
|
|
54
|
+
for (const [, propMeta] of Object.entries(metadata.properties)) {
|
|
55
|
+
if (propMeta.required) {
|
|
56
|
+
if (propMeta.getter)
|
|
57
|
+
continue;
|
|
58
|
+
hasConformance = true;
|
|
59
|
+
if (propMeta.flag && propMeta.initial) {
|
|
60
|
+
joins.push(`
|
|
61
|
+
${sourceVar} ${iri(propMeta.predicate)} ${iri(propMeta.initial)} .`);
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
joins.push(`
|
|
65
|
+
${sourceVar} ${iri(propMeta.predicate)} ?${prefix}_cfTarget_${propMeta.name} .`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
if (!hasConformance) {
|
|
70
|
+
for (const [, propMeta] of Object.entries(metadata.properties)) {
|
|
71
|
+
if (propMeta.initial) {
|
|
72
|
+
if (propMeta.flag) {
|
|
73
|
+
joins.push(`
|
|
74
|
+
${sourceVar} ${iri(propMeta.predicate)} ${iri(propMeta.initial)} .`);
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
joins.push(`
|
|
78
|
+
${sourceVar} ${iri(propMeta.predicate)} ?${prefix}_cfInitAny_${propMeta.name} .`);
|
|
79
|
+
}
|
|
80
|
+
break;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return { joins, filters };
|
|
85
|
+
}
|
|
86
|
+
function flattenIncludeTree(parentDepth, parentClass, includeMap, nextDepth) {
|
|
87
|
+
const branches = [];
|
|
88
|
+
const relMeta = getRelationsMetadata(parentClass);
|
|
89
|
+
for (const [relName, includeValue] of Object.entries(includeMap)) {
|
|
90
|
+
const meta = relMeta[relName];
|
|
91
|
+
if (!meta || !meta.target)
|
|
92
|
+
continue;
|
|
93
|
+
const TargetClass = meta.target();
|
|
94
|
+
const targetMetadata = TargetClass.getModelMetadata
|
|
95
|
+
? TargetClass.getModelMetadata()
|
|
96
|
+
: { className: "Unknown", properties: {}, relations: {} };
|
|
97
|
+
const depth = nextDepth.value++;
|
|
98
|
+
const direction = meta.kind === 'belongsToOne' || meta.kind === 'belongsToMany'
|
|
99
|
+
? 'reverse' : 'forward';
|
|
100
|
+
const nestedInclude = typeof includeValue === 'object' && includeValue !== null
|
|
101
|
+
? includeValue.include
|
|
102
|
+
: undefined;
|
|
103
|
+
branches.push({
|
|
104
|
+
depth,
|
|
105
|
+
relationName: relName,
|
|
106
|
+
parentDepth,
|
|
107
|
+
parentPredicate: meta.predicate,
|
|
108
|
+
targetClass: TargetClass,
|
|
109
|
+
targetMetadata,
|
|
110
|
+
includeMap: nestedInclude,
|
|
111
|
+
direction,
|
|
112
|
+
});
|
|
113
|
+
if (nestedInclude) {
|
|
114
|
+
branches.push(...flattenIncludeTree(depth, TargetClass, nestedInclude, nextDepth));
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return branches;
|
|
118
|
+
}
|
|
119
|
+
// ──────────────────────────────────────────────────────────
|
|
120
|
+
// Main entry point
|
|
121
|
+
// ──────────────────────────────────────────────────────────
|
|
122
|
+
/**
|
|
123
|
+
* Build a single SPARQL query that fetches root instances plus all
|
|
124
|
+
* included relations in one query using UNION branches.
|
|
125
|
+
*
|
|
126
|
+
* Uses direct triple patterns in named graphs with metadata in default graph.
|
|
127
|
+
*/
|
|
128
|
+
export function buildBatchSPARQLQuery(rootMetadata, query, rootModelClass) {
|
|
129
|
+
const includeMap = query.include;
|
|
130
|
+
if (!includeMap || Object.keys(includeMap).length === 0) {
|
|
131
|
+
throw new Error("buildBatchSPARQLQuery requires query.include to be non-empty");
|
|
132
|
+
}
|
|
133
|
+
const nextDepth = { value: 1 };
|
|
134
|
+
const branches = flattenIncludeTree(0, rootModelClass, includeMap, nextDepth);
|
|
135
|
+
// Root conformance
|
|
136
|
+
const rootConformance = buildConformanceJoins(rootMetadata, "?source", "root");
|
|
137
|
+
const rootJoins = [...rootConformance.joins];
|
|
138
|
+
const rootFilters = [...rootConformance.filters];
|
|
139
|
+
if (query.parent) {
|
|
140
|
+
const parentPredicate = resolveParentPredicate(query.parent, rootModelClass);
|
|
141
|
+
rootJoins.push(`
|
|
142
|
+
${iri(query.parent.id)} ${iri(parentPredicate)} ?source .`);
|
|
143
|
+
}
|
|
144
|
+
if (query.where) {
|
|
145
|
+
for (const [propertyName, condition] of Object.entries(query.where)) {
|
|
146
|
+
if (propertyName === "base" || propertyName === "id") {
|
|
147
|
+
if (Array.isArray(condition)) {
|
|
148
|
+
const formatted = condition.map(v => iri(v)).join(", ");
|
|
149
|
+
rootFilters.push(`?source IN (${formatted})`);
|
|
150
|
+
}
|
|
151
|
+
else if (typeof condition === "string") {
|
|
152
|
+
rootFilters.push(`?source = ${iri(condition)}`);
|
|
153
|
+
}
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
if (propertyName === "author" || propertyName === "timestamp")
|
|
157
|
+
continue;
|
|
158
|
+
const propMeta = rootMetadata.properties[propertyName];
|
|
159
|
+
if (!propMeta)
|
|
160
|
+
continue;
|
|
161
|
+
const useParseLiteral = isLiteralStoredProperty(propMeta);
|
|
162
|
+
if (typeof condition === "string" || typeof condition === "number" || typeof condition === "boolean") {
|
|
163
|
+
if (useParseLiteral) {
|
|
164
|
+
// For literal-stored properties, just add a join for conformance — filtering is done in JS
|
|
165
|
+
rootJoins.push(`
|
|
166
|
+
?source ${iri(propMeta.predicate)} ?root_wTarget_eq_${propertyName} .`);
|
|
167
|
+
}
|
|
168
|
+
else {
|
|
169
|
+
rootJoins.push(`
|
|
170
|
+
?source ${iri(propMeta.predicate)} ${iri(String(condition))} .`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
else if (Array.isArray(condition)) {
|
|
174
|
+
if (useParseLiteral) {
|
|
175
|
+
// For literal-stored properties, just add a join for conformance — filtering is done in JS
|
|
176
|
+
rootJoins.push(`
|
|
177
|
+
?source ${iri(propMeta.predicate)} ?root_wTarget_${propertyName} .`);
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
const formatted = condition.map(v => iri(v)).join(", ");
|
|
181
|
+
rootJoins.push(`
|
|
182
|
+
?source ${iri(propMeta.predicate)} ?root_wTarget_${propertyName} .`);
|
|
183
|
+
rootFilters.push(`?root_wTarget_${propertyName} IN (${formatted})`);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
const rootJoinClause = rootJoins.join("\n");
|
|
189
|
+
const rootFilterClause = rootFilters.length > 0
|
|
190
|
+
? `FILTER(\n ${rootFilters.join(" &&\n ")}\n )`
|
|
191
|
+
: "";
|
|
192
|
+
const unionBranches = [];
|
|
193
|
+
// Depth 0: root — direct triple pattern with named graph
|
|
194
|
+
unionBranches.push(`
|
|
195
|
+
{
|
|
196
|
+
${rootJoinClause}
|
|
197
|
+
GRAPH ?linkGraph { ?source ?predicate ?target . }
|
|
198
|
+
FILTER(isIRI(?source) && isIRI(?predicate))
|
|
199
|
+
?linkGraph <ad4m://ontology/author> ?author .
|
|
200
|
+
?linkGraph <ad4m://ontology/timestamp> ?timestamp .
|
|
201
|
+
${rootFilterClause}
|
|
202
|
+
BIND("0" AS ?depth)
|
|
203
|
+
BIND("" AS ?parentBase)
|
|
204
|
+
BIND("" AS ?relationName)
|
|
205
|
+
}
|
|
206
|
+
`);
|
|
207
|
+
// Depth N: include branches
|
|
208
|
+
for (const branch of branches) {
|
|
209
|
+
const childConformance = buildConformanceJoins(branch.targetMetadata, "?source", `d${branch.depth}`);
|
|
210
|
+
const childJoinClause = childConformance.joins.join("\n");
|
|
211
|
+
const childFilterClause = childConformance.filters.length > 0
|
|
212
|
+
? `FILTER(\n ${childConformance.filters.join(" &&\n ")}\n )`
|
|
213
|
+
: "";
|
|
214
|
+
const parentJoinClause = branch.parentDepth === 0 ? rootJoinClause.replace(/\?source/g, '?parentBase') : '';
|
|
215
|
+
const parentFilterClause = branch.parentDepth === 0 ? rootFilterClause.replace(/\?source/g, '?parentBase') : '';
|
|
216
|
+
if (branch.direction === 'forward') {
|
|
217
|
+
// Forward: parent --predicate--> child (source)
|
|
218
|
+
unionBranches.push(`
|
|
219
|
+
{
|
|
220
|
+
# Depth ${branch.depth}: ${branch.relationName} (forward)
|
|
221
|
+
?parentBase ${iri(branch.parentPredicate)} ?source .
|
|
222
|
+
${childJoinClause}
|
|
223
|
+
GRAPH ?linkGraph { ?source ?predicate ?target . }
|
|
224
|
+
FILTER(isIRI(?source) && isIRI(?predicate))
|
|
225
|
+
?linkGraph <ad4m://ontology/author> ?author .
|
|
226
|
+
?linkGraph <ad4m://ontology/timestamp> ?timestamp .
|
|
227
|
+
${childFilterClause}
|
|
228
|
+
${parentJoinClause}
|
|
229
|
+
${parentFilterClause}
|
|
230
|
+
BIND("${branch.depth}" AS ?depth)
|
|
231
|
+
BIND("${branch.relationName}" AS ?relationName)
|
|
232
|
+
}
|
|
233
|
+
`);
|
|
234
|
+
}
|
|
235
|
+
else {
|
|
236
|
+
// Reverse: child (source) --predicate--> parent
|
|
237
|
+
unionBranches.push(`
|
|
238
|
+
{
|
|
239
|
+
# Depth ${branch.depth}: ${branch.relationName} (reverse)
|
|
240
|
+
?source ${iri(branch.parentPredicate)} ?parentBase .
|
|
241
|
+
${childJoinClause}
|
|
242
|
+
GRAPH ?linkGraph { ?source ?predicate ?target . }
|
|
243
|
+
FILTER(isIRI(?source) && isIRI(?predicate))
|
|
244
|
+
?linkGraph <ad4m://ontology/author> ?author .
|
|
245
|
+
?linkGraph <ad4m://ontology/timestamp> ?timestamp .
|
|
246
|
+
${childFilterClause}
|
|
247
|
+
${parentJoinClause}
|
|
248
|
+
${parentFilterClause}
|
|
249
|
+
BIND("${branch.depth}" AS ?depth)
|
|
250
|
+
BIND("${branch.relationName}" AS ?relationName)
|
|
251
|
+
}
|
|
252
|
+
`);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return `
|
|
256
|
+
SELECT ?depth ?parentBase ?relationName ?source ?predicate ?target ?author ?timestamp WHERE {
|
|
257
|
+
${unionBranches.join("\n UNION\n")}
|
|
258
|
+
}
|
|
259
|
+
`.trim();
|
|
260
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SPARQL query building utilities for Ad4mModel.
|
|
3
|
+
*
|
|
4
|
+
* Uses the direct triple + named graph storage model where each AD4M link
|
|
5
|
+
* is stored in a named graph (keyed by link hash) with metadata in the default graph.
|
|
6
|
+
*
|
|
7
|
+
* All AD4M URIs (source, predicate, target) become RDF IRIs.
|
|
8
|
+
*
|
|
9
|
+
* @module
|
|
10
|
+
*/
|
|
11
|
+
import type { RelationMetadataEntry } from "./decorators";
|
|
12
|
+
import type { Query, ModelMetadata } from "./types";
|
|
13
|
+
/**
|
|
14
|
+
* Format a value as a SPARQL string literal (double-quoted).
|
|
15
|
+
*/
|
|
16
|
+
export declare function formatSPARQLValue(value: any): string;
|
|
17
|
+
/**
|
|
18
|
+
* Build a SPARQL query that returns all links belonging to instances of
|
|
19
|
+
* the given model class, optionally filtered by `where` conditions.
|
|
20
|
+
*
|
|
21
|
+
* Uses direct triple patterns: ?source ?predicate ?target
|
|
22
|
+
* with named graph storage and metadata keyed by graph IRI.
|
|
23
|
+
*/
|
|
24
|
+
export declare function buildSPARQLQuery(metadata: ModelMetadata, allRelationsMetadata: Record<string, RelationMetadataEntry>, query: Query, modelClass: any): string;
|
|
25
|
+
/**
|
|
26
|
+
* Build a SPARQL query to fetch all links for a single instance.
|
|
27
|
+
*/
|
|
28
|
+
export declare function buildSPARQLGetDataQuery(baseExpression: string): string;
|
|
29
|
+
/**
|
|
30
|
+
* Group flat SPARQL link rows into the same shape that SPARQL returned:
|
|
31
|
+
* `{ source_uri: string, links: Array<{predicate, target, author, timestamp}> }`
|
|
32
|
+
*/
|
|
33
|
+
export declare function groupSPARQLResults(rows: Array<{
|
|
34
|
+
source: string;
|
|
35
|
+
predicate: string;
|
|
36
|
+
target: string;
|
|
37
|
+
author: string;
|
|
38
|
+
timestamp: string;
|
|
39
|
+
}>): Array<{
|
|
40
|
+
source_uri: string;
|
|
41
|
+
links: Array<{
|
|
42
|
+
predicate: string;
|
|
43
|
+
target: string;
|
|
44
|
+
author: string;
|
|
45
|
+
timestamp: string;
|
|
46
|
+
}>;
|
|
47
|
+
}>;
|