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