@coasys/ad4m 0.13.0-test-1 → 0.13.0-test-3
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 +2377 -849
- package/lib/index.js +2354 -846
- package/lib/src/Literal.js +6 -5
- package/lib/src/agent/AgentClient.d.ts +5 -1
- package/lib/src/agent/AgentClient.js +48 -2
- package/lib/src/expression/ExpressionRef.js +2 -2
- package/lib/src/index.d.ts +0 -1
- package/lib/src/index.js +0 -1
- package/lib/src/language/Language.d.ts +26 -176
- package/lib/src/language/Language.js +28 -2
- package/lib/src/model/Ad4mModel.d.ts +52 -28
- package/lib/src/model/Ad4mModel.js +255 -118
- package/lib/src/model/Ad4mModel.test.js +1727 -537
- package/lib/src/model/ModelQueryBuilder.d.ts +67 -34
- package/lib/src/model/ModelQueryBuilder.js +208 -79
- 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-batching.test.d.ts +7 -0
- package/lib/src/model/hydration-batching.test.js +456 -0
- package/lib/src/model/hydration.d.ts +4 -3
- package/lib/src/model/hydration.js +365 -86
- 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 +124 -0
- package/lib/src/model/query-sparql.js +767 -0
- package/lib/src/model/query-sparql.test.d.ts +1 -0
- package/lib/src/model/query-sparql.test.js +495 -0
- package/lib/src/model/{surreal-utils.d.ts → query-utils.d.ts} +12 -9
- package/lib/src/model/{surreal-utils.js → query-utils.js} +43 -27
- 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-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/model/types.d.ts +52 -4
- package/lib/src/model/types.js +1 -1
- package/lib/src/perspectives/PerspectiveClient.d.ts +3 -17
- package/lib/src/perspectives/PerspectiveClient.js +42 -66
- package/lib/src/perspectives/PerspectiveClient.test.d.ts +1 -0
- package/lib/src/perspectives/PerspectiveClient.test.js +169 -0
- package/lib/src/perspectives/PerspectiveProxy.d.ts +54 -30
- package/lib/src/perspectives/PerspectiveProxy.js +239 -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/RuntimeResolver.d.ts +11 -0
- package/lib/src/runtime/RuntimeResolver.js +56 -0
- package/lib/src/schema.gql +11 -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 +11 -1
- package/lib/src/utils.d.ts +6 -6
- package/lib/src/utils.js +6 -6
- package/package.json +1 -1
- package/src/Ad4mClient.test.ts +56 -1
- package/src/Literal.test.ts +10 -5
- package/src/Literal.ts +6 -5
- package/src/agent/AgentClient.ts +53 -1
- package/src/expression/ExpressionRef.ts +2 -2
- package/src/index.ts +0 -1
- package/src/language/Language.ts +55 -231
- package/src/model/Ad4mModel.test.ts +1709 -572
- package/src/model/Ad4mModel.ts +274 -120
- package/src/model/ModelQueryBuilder.ts +234 -87
- 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-batching.test.ts +563 -0
- package/src/model/hydration.ts +349 -84
- 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.test.ts +568 -0
- package/src/model/query-sparql.ts +820 -0
- package/src/model/{surreal-utils.ts → query-utils.ts} +44 -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-delta.test.ts +207 -0
- package/src/model/subscription-pool.ts +211 -0
- package/src/model/types.ts +53 -4
- package/src/perspectives/PerspectiveClient.test.ts +204 -0
- package/src/perspectives/PerspectiveClient.ts +41 -68
- package/src/perspectives/PerspectiveProxy.ts +244 -181
- package/src/perspectives/PerspectiveResolver.ts +0 -8
- package/src/perspectives/WakerSubscriptionManager.ts +8 -9
- package/src/runtime/RuntimeResolver.ts +43 -0
- package/src/shacl/SHACLFlow.ts +9 -9
- package/src/shacl/SHACLShape.ts +39 -39
- package/src/utils.ts +6 -6
- package/lib/src/model/query-surreal.d.ts +0 -44
- package/lib/src/model/query-surreal.js +0 -249
- package/src/language/LanguageContext.ts +0 -37
- package/src/model/query-surreal.ts +0 -280
- package/tsconfig-browser.json +0 -82
|
@@ -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,124 @@
|
|
|
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 { Where, Query, ModelMetadata } from "./types";
|
|
13
|
+
/**
|
|
14
|
+
* Check whether a `where` clause contains filters that cannot be pushed down
|
|
15
|
+
* to SPARQL and must be evaluated in JS after hydration.
|
|
16
|
+
*
|
|
17
|
+
* JS-only filters include:
|
|
18
|
+
* - Literal-stored properties (equality, comparison, contains, etc.)
|
|
19
|
+
* - Reverse relations (belongsToOne / belongsToMany)
|
|
20
|
+
* - author / timestamp filters (skipped by buildSPARQLWhereFilters)
|
|
21
|
+
*
|
|
22
|
+
* When JS-only filters exist, SPARQL-level LIMIT/OFFSET must NOT be applied
|
|
23
|
+
* because the database would cap the candidate set before JS filters run,
|
|
24
|
+
* potentially discarding matches beyond the LIMIT.
|
|
25
|
+
*/
|
|
26
|
+
export declare function hasJsOnlyWhereFilters(metadata: ModelMetadata, allRelationsMetadata: Record<string, RelationMetadataEntry>, where?: Where): boolean;
|
|
27
|
+
/**
|
|
28
|
+
* Format a value as a SPARQL string literal (double-quoted).
|
|
29
|
+
*/
|
|
30
|
+
export declare function formatSPARQLValue(value: any): string;
|
|
31
|
+
/**
|
|
32
|
+
* Build a SPARQL query that returns all links belonging to instances of
|
|
33
|
+
* the given model class, optionally filtered by `where` conditions.
|
|
34
|
+
*
|
|
35
|
+
* Uses direct triple patterns: ?source ?predicate ?target
|
|
36
|
+
* with named graph storage and metadata keyed by graph IRI.
|
|
37
|
+
*/
|
|
38
|
+
export declare function buildSPARQLQuery(metadata: ModelMetadata, allRelationsMetadata: Record<string, RelationMetadataEntry>, query: Query, modelClass: any): string;
|
|
39
|
+
/**
|
|
40
|
+
* Build ORDER BY / LIMIT / OFFSET clauses for the SPARQL query.
|
|
41
|
+
*
|
|
42
|
+
* NOTE: The outer SELECT returns multiple rows per instance (one per link),
|
|
43
|
+
* so LIMIT/OFFSET at the outer level would cut off links mid-instance.
|
|
44
|
+
* This function is kept for backward compatibility and always returns "".
|
|
45
|
+
* SPARQL-level pagination is handled via a subquery in buildSPARQLQuery
|
|
46
|
+
* using buildPaginationSubquery().
|
|
47
|
+
*/
|
|
48
|
+
export declare function buildSPARQLOrderLimitOffset(_metadata: ModelMetadata, query: Query): string;
|
|
49
|
+
/**
|
|
50
|
+
* Build an inner subquery that selects DISTINCT ?source URIs with
|
|
51
|
+
* ORDER BY, LIMIT, and OFFSET applied at the instance level.
|
|
52
|
+
*
|
|
53
|
+
* Because the outer SELECT returns multiple rows per instance (one per link),
|
|
54
|
+
* we cannot apply LIMIT/OFFSET there. Instead this subquery constrains
|
|
55
|
+
* ?source to only the instances on the requested page.
|
|
56
|
+
*
|
|
57
|
+
* @internal — used by buildSPARQLQuery when SPARQL-level pagination is safe.
|
|
58
|
+
*/
|
|
59
|
+
export declare function buildPaginationSubquery(joinPatterns: string[], filterExpressions: string[], metadata: ModelMetadata, query: Query): string;
|
|
60
|
+
/**
|
|
61
|
+
* Build a SPARQL COUNT query that returns the total number of matching
|
|
62
|
+
* instances WITHOUT hydrating them. Uses the same WHERE clause as
|
|
63
|
+
* buildSPARQLQuery but wraps it in SELECT (COUNT(DISTINCT ?source) AS ?count).
|
|
64
|
+
*
|
|
65
|
+
* LIMIT/OFFSET from the query are stripped internally — this always counts
|
|
66
|
+
* the full result set.
|
|
67
|
+
*/
|
|
68
|
+
export declare function buildSPARQLCountQuery(metadata: ModelMetadata, allRelationsMetadata: Record<string, RelationMetadataEntry>, query: Query, modelClass: any): string;
|
|
69
|
+
/**
|
|
70
|
+
* Build a SPARQL query to fetch all links for a single instance.
|
|
71
|
+
*/
|
|
72
|
+
export declare function buildSPARQLGetDataQuery(baseExpression: string): string;
|
|
73
|
+
/**
|
|
74
|
+
* Group flat SPARQL link rows into the same shape that SPARQL returned:
|
|
75
|
+
* `{ source_uri: string, links: Array<{predicate, target, author, timestamp}> }`
|
|
76
|
+
*/
|
|
77
|
+
export declare function groupSPARQLResults(rows: Array<{
|
|
78
|
+
source: string;
|
|
79
|
+
predicate: string;
|
|
80
|
+
target: string;
|
|
81
|
+
author: string;
|
|
82
|
+
timestamp: string;
|
|
83
|
+
}>): Array<{
|
|
84
|
+
source_uri: string;
|
|
85
|
+
links: Array<{
|
|
86
|
+
predicate: string;
|
|
87
|
+
target: string;
|
|
88
|
+
author: string;
|
|
89
|
+
timestamp: string;
|
|
90
|
+
}>;
|
|
91
|
+
}>;
|
|
92
|
+
/**
|
|
93
|
+
* Parse a SPARQL COUNT result row into a number.
|
|
94
|
+
* Handles `row.count?.value` (RDF binding), `row.count` (direct number/string),
|
|
95
|
+
* NaN results, and empty/malformed results.
|
|
96
|
+
*
|
|
97
|
+
* @returns The parsed count, or `null` if the result cannot be interpreted.
|
|
98
|
+
*/
|
|
99
|
+
export declare function parseSparqlCount(result: any[]): number | null;
|
|
100
|
+
/**
|
|
101
|
+
* Build a SPARQL query that counts child instances grouped by parent IRI.
|
|
102
|
+
*
|
|
103
|
+
* Used by the projection Path A (`count: true`) in `hydrateRelations` to get
|
|
104
|
+
* per-parent counts in a single round-trip with zero instance hydration.
|
|
105
|
+
*
|
|
106
|
+
* Includes the full named graph block so that `?author` and `?timestamp` are
|
|
107
|
+
* bound and available for SPARQL FILTER expressions (unlike the intentionally
|
|
108
|
+
* minimal `buildSPARQLCountQuery` which omits them for speed).
|
|
109
|
+
*
|
|
110
|
+
* @param metadata - Model metadata for the **child** (target) class
|
|
111
|
+
* @param allRelationsMetadata - Relations metadata for the child class
|
|
112
|
+
* @param relationPredicate - The predicate linking `?parent` → `?source` (child)
|
|
113
|
+
* @param parentIds - IRI strings of all parent instances to count for
|
|
114
|
+
* @param where - Optional filter applied to child instances
|
|
115
|
+
*/
|
|
116
|
+
export declare function buildSPARQLGroupedCountQuery(metadata: ModelMetadata, allRelationsMetadata: Record<string, RelationMetadataEntry>, relationPredicate: string, parentIds: string[], where?: import('./types').Where): string;
|
|
117
|
+
/**
|
|
118
|
+
* Parse the result of `buildSPARQLGroupedCountQuery` into a map from parent IRI
|
|
119
|
+
* to count. Missing parents (zero matches) are absent from the map — callers
|
|
120
|
+
* should use `map.get(id) ?? 0`.
|
|
121
|
+
*
|
|
122
|
+
* @returns Map from parentId string → count number
|
|
123
|
+
*/
|
|
124
|
+
export declare function parseSparqlGroupedCount(result: any[]): Map<string, number>;
|