@coasys/ad4m 0.13.0-test-1 → 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 +1392 -777
- package/lib/index.js +1376 -775
- 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/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/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/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/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/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/src/model/query-surreal.ts +0 -280
|
@@ -0,0 +1,336 @@
|
|
|
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 { Literal } from "../Literal";
|
|
12
|
+
import { resolveParentPredicate } from "./query-common";
|
|
13
|
+
/**
|
|
14
|
+
* Check if a string value looks like a URI (has a scheme).
|
|
15
|
+
*/
|
|
16
|
+
function looksLikeUri(value) {
|
|
17
|
+
return /^[a-zA-Z][a-zA-Z0-9+\-._]*:/.test(value);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Convert a JS value to its literal: IRI form, matching how the Rust executor
|
|
21
|
+
* stores property values that don't have a resolveLanguage set.
|
|
22
|
+
* Strings that already look like URIs are returned as-is.
|
|
23
|
+
*/
|
|
24
|
+
function valueToLiteralIri(value) {
|
|
25
|
+
if (typeof value === 'string') {
|
|
26
|
+
if (looksLikeUri(value))
|
|
27
|
+
return value;
|
|
28
|
+
return Literal.from(value).toUrl();
|
|
29
|
+
}
|
|
30
|
+
if (typeof value === 'number') {
|
|
31
|
+
return Literal.from(value).toUrl();
|
|
32
|
+
}
|
|
33
|
+
if (typeof value === 'boolean') {
|
|
34
|
+
return Literal.from(value).toUrl();
|
|
35
|
+
}
|
|
36
|
+
return Literal.from(String(value)).toUrl();
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Determine if a property stores values as literal: IRIs (needs parse_literal for comparisons).
|
|
40
|
+
* Properties with resolveLanguage === "literal" AND properties without resolveLanguage
|
|
41
|
+
* both store values as literal: URIs. Only properties with a non-literal resolveLanguage
|
|
42
|
+
* (e.g. file storage) or flag properties store raw URIs.
|
|
43
|
+
*/
|
|
44
|
+
function isLiteralStoredProperty(propMeta) {
|
|
45
|
+
if (propMeta.flag)
|
|
46
|
+
return false;
|
|
47
|
+
// If resolveLanguage is set to something other than "literal", it's a language expression URI
|
|
48
|
+
if (propMeta.resolveLanguage && propMeta.resolveLanguage !== "literal")
|
|
49
|
+
return false;
|
|
50
|
+
// Everything else (resolveLanguage === "literal" or undefined) stores as literal: URIs
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Escape a string for use as a SPARQL string literal.
|
|
55
|
+
*/
|
|
56
|
+
function escapeSPARQL(value) {
|
|
57
|
+
return value
|
|
58
|
+
.replace(/\\/g, "\\\\")
|
|
59
|
+
.replace(/"/g, '\\"')
|
|
60
|
+
.replace(/\n/g, "\\n")
|
|
61
|
+
.replace(/\r/g, "\\r")
|
|
62
|
+
.replace(/\t/g, "\\t");
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Format a value as a SPARQL string literal (double-quoted).
|
|
66
|
+
*/
|
|
67
|
+
export function formatSPARQLValue(value) {
|
|
68
|
+
if (typeof value === "string") {
|
|
69
|
+
return `"${escapeSPARQL(value)}"`;
|
|
70
|
+
}
|
|
71
|
+
return `"${String(value)}"`;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Format an AD4M URI as an RDF IRI for use in SPARQL triple patterns.
|
|
75
|
+
* All AD4M link source/predicate/target values become IRIs in angle brackets.
|
|
76
|
+
* The Rust SPARQL service transparently transforms these to valid IRI format.
|
|
77
|
+
*/
|
|
78
|
+
function iri(value) {
|
|
79
|
+
return `<${value}>`;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Build a SPARQL query that returns all links belonging to instances of
|
|
83
|
+
* the given model class, optionally filtered by `where` conditions.
|
|
84
|
+
*
|
|
85
|
+
* Uses direct triple patterns: ?source ?predicate ?target
|
|
86
|
+
* with named graph storage and metadata keyed by graph IRI.
|
|
87
|
+
*/
|
|
88
|
+
export function buildSPARQLQuery(metadata, allRelationsMetadata, query, modelClass) {
|
|
89
|
+
const joinPatterns = [];
|
|
90
|
+
const filterExpressions = [];
|
|
91
|
+
// Parent filter — direct triple pattern
|
|
92
|
+
if (query.parent) {
|
|
93
|
+
const parentPredicate = resolveParentPredicate(query.parent, modelClass);
|
|
94
|
+
joinPatterns.push(`
|
|
95
|
+
${iri(query.parent.id)} ${iri(parentPredicate)} ?source .`);
|
|
96
|
+
}
|
|
97
|
+
// Required property JOIN patterns — direct triple patterns
|
|
98
|
+
let hasConformance = false;
|
|
99
|
+
for (const [, propMeta] of Object.entries(metadata.properties)) {
|
|
100
|
+
if (propMeta.required) {
|
|
101
|
+
if (propMeta.getter)
|
|
102
|
+
continue;
|
|
103
|
+
hasConformance = true;
|
|
104
|
+
if (propMeta.flag && propMeta.initial) {
|
|
105
|
+
joinPatterns.push(`
|
|
106
|
+
?source ${iri(propMeta.predicate)} ${iri(propMeta.initial)} .`);
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
joinPatterns.push(`
|
|
110
|
+
?source ${iri(propMeta.predicate)} ?cfTarget_${propMeta.name} .`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
// Fallback: initial-value JOIN patterns
|
|
115
|
+
if (!hasConformance) {
|
|
116
|
+
for (const [, propMeta] of Object.entries(metadata.properties)) {
|
|
117
|
+
if (propMeta.initial) {
|
|
118
|
+
hasConformance = true;
|
|
119
|
+
if (propMeta.flag) {
|
|
120
|
+
joinPatterns.push(`
|
|
121
|
+
?source ${iri(propMeta.predicate)} ${iri(propMeta.initial)} .`);
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
joinPatterns.push(`
|
|
125
|
+
?source ${iri(propMeta.predicate)} ?cfInitTarget_${propMeta.name} .`);
|
|
126
|
+
}
|
|
127
|
+
break;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
// Fallback: open-world structural matching
|
|
132
|
+
// Use a subquery with DISTINCT to avoid row multiplication when the main
|
|
133
|
+
// ?source ?predicate ?target pattern cross-joins with multiple structural matches.
|
|
134
|
+
if (!hasConformance && joinPatterns.length === 0) {
|
|
135
|
+
const knownPredicates = [];
|
|
136
|
+
for (const [, propMeta] of Object.entries(metadata.properties)) {
|
|
137
|
+
if (propMeta.predicate) {
|
|
138
|
+
knownPredicates.push(iri(propMeta.predicate));
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (metadata.relations) {
|
|
142
|
+
for (const [, relMeta] of Object.entries(metadata.relations)) {
|
|
143
|
+
if (relMeta.predicate) {
|
|
144
|
+
knownPredicates.push(iri(relMeta.predicate));
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
if (knownPredicates.length > 0) {
|
|
149
|
+
joinPatterns.push(`
|
|
150
|
+
{ SELECT DISTINCT ?source WHERE { ?source ?cf_structPred ?cf_structTarget . FILTER(?cf_structPred IN (${knownPredicates.join(", ")})) } }`);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
// Build WHERE clause filters from user query
|
|
154
|
+
const { joins: userJoins, filters: userFilters } = buildSPARQLWhereFilters(metadata, allRelationsMetadata, query.where);
|
|
155
|
+
joinPatterns.push(...userJoins);
|
|
156
|
+
filterExpressions.push(...userFilters);
|
|
157
|
+
// Main triple pattern — fetches all links for matched sources
|
|
158
|
+
// The direct triple in named graph: GRAPH ?linkGraph { ?source ?predicate ?target }
|
|
159
|
+
// FILTER(isIRI(?source)) excludes non-IRI subjects
|
|
160
|
+
const joinClause = joinPatterns.join("\n");
|
|
161
|
+
const filterClause = filterExpressions.length > 0
|
|
162
|
+
? `FILTER(\n ${filterExpressions.join(" &&\n ")}\n )`
|
|
163
|
+
: "";
|
|
164
|
+
return `
|
|
165
|
+
SELECT ?source ?predicate ?target ?author ?timestamp WHERE {${joinClause}
|
|
166
|
+
GRAPH ?linkGraph { ?source ?predicate ?target . }
|
|
167
|
+
FILTER(isIRI(?source) && isIRI(?predicate))
|
|
168
|
+
?linkGraph <ad4m://ontology/author> ?author .
|
|
169
|
+
?linkGraph <ad4m://ontology/timestamp> ?timestamp .
|
|
170
|
+
${filterClause}
|
|
171
|
+
}
|
|
172
|
+
${buildSPARQLOrderLimitOffset(metadata, query)}
|
|
173
|
+
`.trim();
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Build ORDER BY / LIMIT / OFFSET clauses for the SPARQL query.
|
|
177
|
+
*/
|
|
178
|
+
function buildSPARQLOrderLimitOffset(_metadata, _query) {
|
|
179
|
+
return "";
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Build a SPARQL query to fetch all links for a single instance.
|
|
183
|
+
*/
|
|
184
|
+
export function buildSPARQLGetDataQuery(baseExpression) {
|
|
185
|
+
return `
|
|
186
|
+
SELECT ?source ?predicate ?target ?author ?timestamp WHERE {
|
|
187
|
+
GRAPH ?linkGraph { ${iri(baseExpression)} ?predicate ?target . }
|
|
188
|
+
FILTER(isIRI(?predicate))
|
|
189
|
+
BIND(${iri(baseExpression)} AS ?source)
|
|
190
|
+
?linkGraph <ad4m://ontology/author> ?author .
|
|
191
|
+
?linkGraph <ad4m://ontology/timestamp> ?timestamp .
|
|
192
|
+
}
|
|
193
|
+
`.trim();
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Group flat SPARQL link rows into the same shape that SPARQL returned:
|
|
197
|
+
* `{ source_uri: string, links: Array<{predicate, target, author, timestamp}> }`
|
|
198
|
+
*/
|
|
199
|
+
export function groupSPARQLResults(rows) {
|
|
200
|
+
const grouped = new Map();
|
|
201
|
+
for (const row of rows) {
|
|
202
|
+
const key = row.source;
|
|
203
|
+
if (!grouped.has(key)) {
|
|
204
|
+
grouped.set(key, []);
|
|
205
|
+
}
|
|
206
|
+
grouped.get(key).push({
|
|
207
|
+
predicate: row.predicate,
|
|
208
|
+
target: row.target,
|
|
209
|
+
author: row.author,
|
|
210
|
+
timestamp: row.timestamp,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
return Array.from(grouped.entries()).map(([source_uri, links]) => ({
|
|
214
|
+
source_uri,
|
|
215
|
+
links,
|
|
216
|
+
}));
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Build SPARQL FILTER expressions from user `where` conditions.
|
|
220
|
+
* Uses direct triple patterns instead of link-node reification.
|
|
221
|
+
*/
|
|
222
|
+
function buildSPARQLWhereFilters(metadata, _allRelationsMetadata, where) {
|
|
223
|
+
if (!where)
|
|
224
|
+
return { joins: [], filters: [] };
|
|
225
|
+
const joins = [];
|
|
226
|
+
const filters = [];
|
|
227
|
+
for (const [propertyName, condition] of Object.entries(where)) {
|
|
228
|
+
// 'base' maps to ?source
|
|
229
|
+
if (propertyName === "base" || propertyName === "id") {
|
|
230
|
+
if (Array.isArray(condition)) {
|
|
231
|
+
const formatted = condition.map(v => iri(v)).join(", ");
|
|
232
|
+
filters.push(`?source IN (${formatted})`);
|
|
233
|
+
}
|
|
234
|
+
else if (typeof condition === "object" && condition !== null) {
|
|
235
|
+
const ops = condition;
|
|
236
|
+
if (ops.not !== undefined) {
|
|
237
|
+
if (Array.isArray(ops.not)) {
|
|
238
|
+
const formatted = ops.not.map(v => iri(v)).join(", ");
|
|
239
|
+
filters.push(`!(?source IN (${formatted}))`);
|
|
240
|
+
}
|
|
241
|
+
else {
|
|
242
|
+
filters.push(`?source != ${iri(ops.not)}`);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
filters.push(`?source = ${iri(String(condition))}`);
|
|
248
|
+
}
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
if (propertyName === "author" || propertyName === "timestamp") {
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
const propMeta = metadata.properties[propertyName];
|
|
255
|
+
if (!propMeta)
|
|
256
|
+
continue;
|
|
257
|
+
// Skip reverse relations (belongsToOne / belongsToMany) — these are registered as
|
|
258
|
+
// read-only properties but the link direction is reversed (target→source, not source→target).
|
|
259
|
+
// Adding a forward join pattern would match nothing. These are filtered in JS post-filter.
|
|
260
|
+
const relMeta = _allRelationsMetadata[propertyName];
|
|
261
|
+
if (relMeta && (relMeta.kind === 'belongsToOne' || relMeta.kind === 'belongsToMany')) {
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
// Determine if this property stores values as literal: IRIs
|
|
265
|
+
const useParseLiteral = isLiteralStoredProperty(propMeta);
|
|
266
|
+
// For literal-stored properties, skip SPARQL-level FILTER expressions entirely.
|
|
267
|
+
// The parse_literal custom function is unreliable across oxigraph versions and
|
|
268
|
+
// environments. All property-level where filtering is done in JS post-filter
|
|
269
|
+
// (instancesFromQueryResult) after hydration resolves values to JS primitives.
|
|
270
|
+
// We only add a JOIN pattern to ensure the property exists (conformance check).
|
|
271
|
+
if (useParseLiteral) {
|
|
272
|
+
// Just ensure the property exists — no value filtering in SPARQL
|
|
273
|
+
if (typeof condition === "object" && condition !== null && !Array.isArray(condition)) {
|
|
274
|
+
const ops = condition;
|
|
275
|
+
const hasCompOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
276
|
+
ops.lt !== undefined || ops.lte !== undefined ||
|
|
277
|
+
ops.between !== undefined || ops.contains !== undefined ||
|
|
278
|
+
ops.not !== undefined;
|
|
279
|
+
if (hasCompOps) {
|
|
280
|
+
joins.push(`
|
|
281
|
+
?source ${iri(propMeta.predicate)} ?wTarget_cmp_${propertyName} .`);
|
|
282
|
+
}
|
|
283
|
+
// NOT filters: no SPARQL-level filtering — handled in JS
|
|
284
|
+
}
|
|
285
|
+
else {
|
|
286
|
+
// Simple equality or IN — add join for conformance.
|
|
287
|
+
// NOTE: push-down FILTER with fn::parse_literal was attempted but removed because
|
|
288
|
+
// Oxigraph's query parser rejects the fn:: custom function syntax at parse time
|
|
289
|
+
// (custom functions are only available at execution time). All literal property
|
|
290
|
+
// filtering is done in JS post-filter after hydration resolves values.
|
|
291
|
+
joins.push(`
|
|
292
|
+
?source ${iri(propMeta.predicate)} ?wTarget_${propertyName} .`);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
else if (Array.isArray(condition)) {
|
|
296
|
+
const formatted = condition.map(v => iri(v)).join(", ");
|
|
297
|
+
joins.push(`
|
|
298
|
+
?source ${iri(propMeta.predicate)} ?wTarget_${propertyName} .`);
|
|
299
|
+
filters.push(`?wTarget_${propertyName} IN (${formatted})`);
|
|
300
|
+
}
|
|
301
|
+
else if (typeof condition === "object" && condition !== null) {
|
|
302
|
+
const ops = condition;
|
|
303
|
+
if (ops.not !== undefined) {
|
|
304
|
+
if (Array.isArray(ops.not)) {
|
|
305
|
+
const formatted = ops.not.map(v => iri(v)).join(", ");
|
|
306
|
+
filters.push(`
|
|
307
|
+
NOT EXISTS {
|
|
308
|
+
?source ${iri(propMeta.predicate)} ?wTarget_not_${propertyName} .
|
|
309
|
+
FILTER(?wTarget_not_${propertyName} IN (${formatted}))
|
|
310
|
+
}
|
|
311
|
+
`);
|
|
312
|
+
}
|
|
313
|
+
else {
|
|
314
|
+
filters.push(`
|
|
315
|
+
NOT EXISTS {
|
|
316
|
+
?source ${iri(propMeta.predicate)} ${iri(ops.not)} .
|
|
317
|
+
}
|
|
318
|
+
`);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
const hasCompOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
322
|
+
ops.lt !== undefined || ops.lte !== undefined ||
|
|
323
|
+
ops.between !== undefined || ops.contains !== undefined;
|
|
324
|
+
if (hasCompOps) {
|
|
325
|
+
joins.push(`
|
|
326
|
+
?source ${iri(propMeta.predicate)} ?wTarget_cmp_${propertyName} .`);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
else {
|
|
330
|
+
// Simple equality — non-literal property, use exact IRI match
|
|
331
|
+
joins.push(`
|
|
332
|
+
?source ${iri(propMeta.predicate)} ${iri(String(condition))} .`);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
return { joins, filters };
|
|
336
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared query 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
|
+
* All output uses native SPARQL syntax.
|
|
8
|
+
*/
|
|
9
|
+
import type { WhereCondition, Where, ModelMetadata } from "./types";
|
|
10
|
+
/**
|
|
11
|
+
* Format a JavaScript value for embedding in a query expression.
|
|
12
|
+
*
|
|
13
|
+
* - Strings are single-quoted with backslash / quote / newline escaping
|
|
14
|
+
* - Numbers and booleans are passed through as-is
|
|
15
|
+
* - Arrays are recursed
|
|
16
|
+
*/
|
|
17
|
+
export declare function formatQueryValue(value: any): string;
|
|
18
|
+
/**
|
|
19
|
+
* Compile a single Where condition for a property into a SPARQL triple pattern
|
|
20
|
+
* that can be embedded in a getter's WHERE clause.
|
|
21
|
+
*
|
|
22
|
+
* The generated pattern operates on `?target` — e.g.:
|
|
23
|
+
* `?target <pred> <value> .`
|
|
24
|
+
* `FILTER EXISTS { ?target <pred> ?_v0 }`
|
|
25
|
+
*
|
|
26
|
+
* @param predicate - The predicate URI for the property
|
|
27
|
+
* @param condition - The Where condition value
|
|
28
|
+
* @param opts - Optional settings (e.g. `resolveLanguage`)
|
|
29
|
+
* @returns A single SPARQL condition string
|
|
30
|
+
*/
|
|
31
|
+
export declare function buildWhereCondition(predicate: string, condition: WhereCondition, opts?: {
|
|
32
|
+
resolveLanguage?: string;
|
|
33
|
+
}): string;
|
|
34
|
+
/**
|
|
35
|
+
* Compile a full `Where` clause to an array of SPARQL condition strings.
|
|
36
|
+
*
|
|
37
|
+
* When `metadata` is provided, property names are resolved to predicates
|
|
38
|
+
* using the model's property metadata. When `metadata` is `null`, property
|
|
39
|
+
* names are treated as raw predicate URIs.
|
|
40
|
+
*
|
|
41
|
+
* Only handles **regular properties** — special fields (`id`, `author`,
|
|
42
|
+
* `timestamp`) and relation fields are skipped (they are only relevant at
|
|
43
|
+
* runtime query time, not for compile-time getter generation).
|
|
44
|
+
*/
|
|
45
|
+
export declare function compileWhereClause(where: Where, metadata: ModelMetadata | null): string[];
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared query 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
|
+
* All output uses native SPARQL syntax.
|
|
8
|
+
*/
|
|
9
|
+
import { escapeQueryString } from "../utils";
|
|
10
|
+
/**
|
|
11
|
+
* Format a JavaScript value for embedding in a query expression.
|
|
12
|
+
*
|
|
13
|
+
* - Strings are single-quoted with backslash / quote / newline escaping
|
|
14
|
+
* - Numbers and booleans are passed through as-is
|
|
15
|
+
* - Arrays are recursed
|
|
16
|
+
*/
|
|
17
|
+
export function formatQueryValue(value) {
|
|
18
|
+
if (typeof value === 'string') {
|
|
19
|
+
// Escape backslashes first, then single quotes and other special characters
|
|
20
|
+
const escaped = value
|
|
21
|
+
.replace(/\\/g, '\\\\') // Backslash -> \\
|
|
22
|
+
.replace(/'/g, "\\'") // Single quote -> \'
|
|
23
|
+
.replace(/"/g, '\\"') // Double quote -> \"
|
|
24
|
+
.replace(/\n/g, '\\n') // Newline -> \n
|
|
25
|
+
.replace(/\r/g, '\\r') // Carriage return -> \r
|
|
26
|
+
.replace(/\t/g, '\\t'); // Tab -> \t
|
|
27
|
+
return `'${escaped}'`;
|
|
28
|
+
}
|
|
29
|
+
else if (typeof value === 'number' || typeof value === 'boolean') {
|
|
30
|
+
return String(value);
|
|
31
|
+
}
|
|
32
|
+
else if (Array.isArray(value)) {
|
|
33
|
+
return `[${value.map(v => formatQueryValue(v)).join(', ')}]`;
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
return String(value);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Compile a single Where condition for a property into a SPARQL triple pattern
|
|
41
|
+
* that can be embedded in a getter's WHERE clause.
|
|
42
|
+
*
|
|
43
|
+
* The generated pattern operates on `?target` — e.g.:
|
|
44
|
+
* `?target <pred> <value> .`
|
|
45
|
+
* `FILTER EXISTS { ?target <pred> ?_v0 }`
|
|
46
|
+
*
|
|
47
|
+
* @param predicate - The predicate URI for the property
|
|
48
|
+
* @param condition - The Where condition value
|
|
49
|
+
* @param opts - Optional settings (e.g. `resolveLanguage`)
|
|
50
|
+
* @returns A single SPARQL condition string
|
|
51
|
+
*/
|
|
52
|
+
export function buildWhereCondition(predicate, condition, opts) {
|
|
53
|
+
const escapedPredicate = escapeQueryString(predicate);
|
|
54
|
+
// For literal-resolved properties, we match against the raw IRI (which is a literal: URI)
|
|
55
|
+
// For language-resolved properties, we match against the plain URI
|
|
56
|
+
// For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
|
|
57
|
+
// For language-resolved properties, values are plain URIs
|
|
58
|
+
const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
|
|
59
|
+
function formatValue(v) {
|
|
60
|
+
if (typeof v === 'string') {
|
|
61
|
+
return isLiteral
|
|
62
|
+
? `<literal:string:${escapeQueryString(v)}>`
|
|
63
|
+
: `<${escapeQueryString(v)}>`;
|
|
64
|
+
}
|
|
65
|
+
// Numbers/booleans — also stored as literal:string: in AD4M
|
|
66
|
+
return `<literal:string:${v}>`;
|
|
67
|
+
}
|
|
68
|
+
if (Array.isArray(condition)) {
|
|
69
|
+
// Array values → FILTER IN
|
|
70
|
+
const formattedValues = condition.map(formatValue).join(', ');
|
|
71
|
+
return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
|
|
72
|
+
}
|
|
73
|
+
else if (typeof condition === 'object' && condition !== null) {
|
|
74
|
+
// Operator object
|
|
75
|
+
const ops = condition;
|
|
76
|
+
const parts = [];
|
|
77
|
+
if (ops.not !== undefined) {
|
|
78
|
+
if (Array.isArray(ops.not)) {
|
|
79
|
+
const formattedValues = ops.not.map((v) => formatValue(v)).join(', ');
|
|
80
|
+
parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ?_nval . FILTER(?_nval IN (${formattedValues})) }`);
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ${formatValue(ops.not)} }`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
// Comparison operators — ensure property exists
|
|
87
|
+
const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
88
|
+
ops.lt !== undefined || ops.lte !== undefined ||
|
|
89
|
+
ops.between !== undefined || ops.contains !== undefined;
|
|
90
|
+
if (hasComparisonOps) {
|
|
91
|
+
parts.push(`FILTER EXISTS { ?target <${escapedPredicate}> ?_cmp }`);
|
|
92
|
+
}
|
|
93
|
+
return parts.join(' ');
|
|
94
|
+
}
|
|
95
|
+
else {
|
|
96
|
+
// Simple equality
|
|
97
|
+
return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Compile a full `Where` clause to an array of SPARQL condition strings.
|
|
102
|
+
*
|
|
103
|
+
* When `metadata` is provided, property names are resolved to predicates
|
|
104
|
+
* using the model's property metadata. When `metadata` is `null`, property
|
|
105
|
+
* names are treated as raw predicate URIs.
|
|
106
|
+
*
|
|
107
|
+
* Only handles **regular properties** — special fields (`id`, `author`,
|
|
108
|
+
* `timestamp`) and relation fields are skipped (they are only relevant at
|
|
109
|
+
* runtime query time, not for compile-time getter generation).
|
|
110
|
+
*/
|
|
111
|
+
export function compileWhereClause(where, metadata) {
|
|
112
|
+
const conditions = [];
|
|
113
|
+
for (const [propertyName, condition] of Object.entries(where)) {
|
|
114
|
+
// Skip special fields that don't apply at compile time
|
|
115
|
+
if (['id', 'author', 'timestamp'].includes(propertyName))
|
|
116
|
+
continue;
|
|
117
|
+
let predicate;
|
|
118
|
+
let resolveLanguage;
|
|
119
|
+
if (metadata) {
|
|
120
|
+
const propMeta = metadata.properties[propertyName];
|
|
121
|
+
if (propMeta) {
|
|
122
|
+
predicate = propMeta.predicate;
|
|
123
|
+
resolveLanguage = propMeta.resolveLanguage;
|
|
124
|
+
}
|
|
125
|
+
else {
|
|
126
|
+
// Property not found in metadata — treat name as raw predicate URI
|
|
127
|
+
predicate = propertyName;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
else {
|
|
131
|
+
// No metadata — treat name as raw predicate URI
|
|
132
|
+
predicate = propertyName;
|
|
133
|
+
}
|
|
134
|
+
const cond = buildWhereCondition(predicate, condition, { resolveLanguage });
|
|
135
|
+
if (cond) {
|
|
136
|
+
conditions.push(cond);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return conditions;
|
|
140
|
+
}
|
|
@@ -20,7 +20,7 @@ var __metadata = (this && this.__metadata) || function (k, v) {
|
|
|
20
20
|
import { Ad4mModel } from "./Ad4mModel";
|
|
21
21
|
import { Model, Property, Flag, HasMany, Optional, buildConformanceFilter, } from "./decorators";
|
|
22
22
|
import { SHACLShape, } from "../shacl/SHACLShape";
|
|
23
|
-
import { compileWhereClause } from "./
|
|
23
|
+
import { compileWhereClause } from "./query-utils";
|
|
24
24
|
// ============================================================================
|
|
25
25
|
// Test models
|
|
26
26
|
// ============================================================================
|
|
@@ -88,7 +88,7 @@ __decorate([
|
|
|
88
88
|
], ParentWithRelations.prototype, "unfilteredItems", void 0);
|
|
89
89
|
__decorate([
|
|
90
90
|
HasMany({
|
|
91
|
-
getter: "
|
|
91
|
+
getter: "SELECT ?target WHERE { ?target <test://custom> ?source . }",
|
|
92
92
|
}),
|
|
93
93
|
__metadata("design:type", Array)
|
|
94
94
|
], ParentWithRelations.prototype, "customItems", void 0);
|
|
@@ -113,8 +113,8 @@ describe("buildConformanceFilter()", () => {
|
|
|
113
113
|
expect(reqCond).toBeDefined();
|
|
114
114
|
expect(reqCond.predicate).toBe("test://name");
|
|
115
115
|
expect(reqCond.value).toBeUndefined();
|
|
116
|
-
// Getter string should be a
|
|
117
|
-
expect(result.getter).toContain("
|
|
116
|
+
// Getter string should be a SPARQL expression
|
|
117
|
+
expect(result.getter).toContain("SELECT ?target WHERE");
|
|
118
118
|
expect(result.getter).toContain("test://has_flagged");
|
|
119
119
|
expect(result.getter).toContain("test://type");
|
|
120
120
|
expect(result.getter).toContain("test://flagged_type");
|
|
@@ -161,7 +161,7 @@ describe("buildConformanceFilter()", () => {
|
|
|
161
161
|
Property({
|
|
162
162
|
through: "test://computed",
|
|
163
163
|
required: true,
|
|
164
|
-
getter: "
|
|
164
|
+
getter: "SELECT ?target WHERE { ?target <test://custom> ?source . } LIMIT 1",
|
|
165
165
|
}),
|
|
166
166
|
__metadata("design:type", String)
|
|
167
167
|
], CustomGetterTarget.prototype, "computed", void 0);
|
|
@@ -179,7 +179,7 @@ describe("buildConformanceFilter()", () => {
|
|
|
179
179
|
// SHACL serialization round-trip tests
|
|
180
180
|
// ============================================================================
|
|
181
181
|
describe("SHACL shape getter serialization", () => {
|
|
182
|
-
const testGetter = "
|
|
182
|
+
const testGetter = "SELECT ?target WHERE { <Base> <test://pred> ?target . ?target <test://type> <test://flag> . }";
|
|
183
183
|
const testConditions = [
|
|
184
184
|
{ type: "flag", predicate: "test://type", value: "test://flag" },
|
|
185
185
|
{ type: "required", predicate: "test://name" },
|
|
@@ -198,7 +198,7 @@ describe("SHACL shape getter serialization", () => {
|
|
|
198
198
|
// Verify getter link exists
|
|
199
199
|
const getterLink = links.find(l => l.predicate === "ad4m://getter");
|
|
200
200
|
expect(getterLink).toBeDefined();
|
|
201
|
-
expect(getterLink.target).toBe(`literal
|
|
201
|
+
expect(getterLink.target).toBe(`literal:string:${testGetter}`);
|
|
202
202
|
// Verify conditions link exists
|
|
203
203
|
const conditionsLink = links.find(l => l.predicate === "ad4m://conformanceConditions");
|
|
204
204
|
expect(conditionsLink).toBeDefined();
|
|
@@ -321,7 +321,7 @@ describe("Ad4mModel.getModelMetadata() relation filtering fields", () => {
|
|
|
321
321
|
it("should expose explicit getter on relations with custom getter", () => {
|
|
322
322
|
const metadata = ParentWithRelations.getModelMetadata();
|
|
323
323
|
// Explicit getter provided via decorator (getter-only, no predicate)
|
|
324
|
-
expect(metadata.relations.customItems.getter).toBe("
|
|
324
|
+
expect(metadata.relations.customItems.getter).toBe("SELECT ?target WHERE { ?target <test://custom> ?source . }");
|
|
325
325
|
expect(metadata.relations.customItems.predicate).toBe("");
|
|
326
326
|
// Auto-generated getter is NOT in decorator metadata (it's in the SHACL shape)
|
|
327
327
|
expect(metadata.relations.flaggedItems.getter).toBeUndefined();
|
|
@@ -364,7 +364,7 @@ describe("Relation decorator validation", () => {
|
|
|
364
364
|
};
|
|
365
365
|
__decorate([
|
|
366
366
|
HasMany({
|
|
367
|
-
getter: "
|
|
367
|
+
getter: "SELECT ?target WHERE { ?target ?p ?source . }",
|
|
368
368
|
target: () => FlaggedTarget,
|
|
369
369
|
}),
|
|
370
370
|
__metadata("design:type", Array)
|
|
@@ -384,7 +384,7 @@ describe("Relation decorator validation", () => {
|
|
|
384
384
|
};
|
|
385
385
|
__decorate([
|
|
386
386
|
HasMany({
|
|
387
|
-
getter: "
|
|
387
|
+
getter: "SELECT ?target WHERE { ?target ?p ?source . }",
|
|
388
388
|
through: "test://pred",
|
|
389
389
|
}),
|
|
390
390
|
__metadata("design:type", Array)
|
|
@@ -404,7 +404,7 @@ describe("Relation decorator validation", () => {
|
|
|
404
404
|
};
|
|
405
405
|
__decorate([
|
|
406
406
|
HasMany({
|
|
407
|
-
getter: "
|
|
407
|
+
getter: "SELECT ?target WHERE { ?target ?p ?source . }",
|
|
408
408
|
}),
|
|
409
409
|
__metadata("design:type", Array)
|
|
410
410
|
], _Valid.prototype, "items", void 0);
|
|
@@ -541,7 +541,7 @@ describe("where clause validation", () => {
|
|
|
541
541
|
__decorate([
|
|
542
542
|
HasMany({
|
|
543
543
|
where: { status: "active" },
|
|
544
|
-
getter: "
|
|
544
|
+
getter: "SELECT ?target WHERE { ?target ?p ?source . }",
|
|
545
545
|
}),
|
|
546
546
|
__metadata("design:type", Array)
|
|
547
547
|
], _Invalid.prototype, "items", void 0);
|
|
@@ -573,7 +573,7 @@ describe("where clause validation", () => {
|
|
|
573
573
|
});
|
|
574
574
|
});
|
|
575
575
|
describe("where clause compilation", () => {
|
|
576
|
-
it("should compile where clause to
|
|
576
|
+
it("should compile where clause to SPARQL getter", () => {
|
|
577
577
|
let WhereTarget = class WhereTarget extends Ad4mModel {
|
|
578
578
|
constructor() {
|
|
579
579
|
super(...arguments);
|
|
@@ -810,7 +810,7 @@ describe("where clause compilation", () => {
|
|
|
810
810
|
// compileWhereClause() unit tests
|
|
811
811
|
// ============================================================================
|
|
812
812
|
describe("compileWhereClause()", () => {
|
|
813
|
-
it("should compile simple equality to
|
|
813
|
+
it("should compile simple equality to SPARQL condition", () => {
|
|
814
814
|
const conditions = compileWhereClause({ status: "active" }, { properties: { status: { name: "status", predicate: "test://status", required: false, readOnly: false } }, relations: {}, className: "Test" });
|
|
815
815
|
expect(conditions).toHaveLength(1);
|
|
816
816
|
expect(conditions[0]).toContain("test://status");
|
|
@@ -819,7 +819,7 @@ describe("compileWhereClause()", () => {
|
|
|
819
819
|
it("should compile not operator", () => {
|
|
820
820
|
const conditions = compileWhereClause({ status: { not: "archived" } }, { properties: { status: { name: "status", predicate: "test://status", required: false, readOnly: false } }, relations: {}, className: "Test" });
|
|
821
821
|
expect(conditions).toHaveLength(1);
|
|
822
|
-
expect(conditions[0]).toContain("
|
|
822
|
+
expect(conditions[0]).toContain("NOT EXISTS"); // negation
|
|
823
823
|
expect(conditions[0]).toContain("archived");
|
|
824
824
|
});
|
|
825
825
|
it("should compile array values to IN clause", () => {
|
package/lib/src/model/sdna.js
CHANGED
|
@@ -73,7 +73,7 @@ export function buildSDNA(subjectName, obj, properties, allRelationsMeta) {
|
|
|
73
73
|
// Optional properties (required: false) are excluded — they should
|
|
74
74
|
// remain unset (undefined) until explicitly assigned.
|
|
75
75
|
const effectiveInitial = initial
|
|
76
|
-
?? (required && writable && !flag && through ? "literal
|
|
76
|
+
?? (required && writable && !flag && through ? "literal:string:" : undefined);
|
|
77
77
|
if (effectiveInitial) {
|
|
78
78
|
constructorActions.push({
|
|
79
79
|
action: "addLink",
|