1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
//! Field resolver for the GraphQL schema auto-generated by
//! [`crate::schema_generator::SchemaGenerator`] from a store's RDF
//! vocabulary.
//!
//! [`SchemaGenerator`] builds real GraphQL `Object` types and root `Query`
//! fields (a collection field and a single-item-by-id field per RDF
//! class), but until this module existed nothing ever resolved those
//! fields against the store -- the generator was reachable only from its
//! own unit tests. [`AutoSchemaResolver`] closes that gap: it runs real
//! SPARQL queries (via [`crate::RdfStore::query`]) against the same
//! vocabulary the schema was generated from, and returns one fully
//! materialized [`Value`] tree per resolved field so the executor's eager
//! projection path (see `QueryExecutor::add_eager_type`) can honor nested
//! selection sets correctly, including for items inside a list.
//!
//! Scope: each instance exposes `id`/`uri` plus its declared data/object
//! properties (fetched with one bounded SPARQL query per property per
//! instance). Object-typed properties are resolved one level deep only
//! (the referenced resource's IRI, as a minimal `{ id uri }` value) rather
//! than recursively walking the whole graph, to keep the cost of a single
//! GraphQL request bounded.
use crate::ast::Value;
use crate::execution::{ExecutionContext, FieldResolver};
use crate::schema_generator::SchemaGenerator;
use crate::schema_types::{PropertyType, RdfClass, RdfVocabulary};
use crate::RdfStore;
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use oxirs_core::query::QueryResults;
use std::collections::HashMap;
use std::sync::Arc;
/// Cap applied to every auto-schema-generated SPARQL query's `LIMIT`,
/// independent of the client-requested `limit` argument, so a single
/// GraphQL request can't force unbounded store scans.
const MAX_COLLECTION_LIMIT: usize = 1000;
/// Cap on the number of values fetched per property per instance.
const MAX_PROPERTY_VALUES: usize = 200;
/// `rdf:type`, spelled out rather than using the SPARQL `a` shorthand: the
/// query engine's triple-pattern parser does not recognize `a` as a
/// predicate abbreviation and rejects it ("Invalid term pattern: a").
const RDF_TYPE: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
#[derive(Debug, Clone)]
struct GeneratedField {
class_uri: String,
is_collection: bool,
}
/// Resolves the root `Query` fields that [`SchemaGenerator::generate_schema`]
/// derives from an [`RdfVocabulary`] (e.g. `persons(limit, offset, where)`
/// and `person(id)` for an `rdfs:Class`/`owl:Class` named `Person`).
pub struct AutoSchemaResolver {
store: Arc<RdfStore>,
vocabulary: RdfVocabulary,
fields: HashMap<String, GeneratedField>,
}
impl AutoSchemaResolver {
/// Build a resolver for every class in `vocabulary`, using the exact
/// same URI-to-GraphQL-name conventions as [`SchemaGenerator`] so the
/// field names line up with the generated schema.
pub fn new(store: Arc<RdfStore>, vocabulary: RdfVocabulary) -> Self {
let namer = SchemaGenerator::new();
let mut fields = HashMap::new();
for class_uri in vocabulary.classes.keys() {
let type_name = namer.uri_to_graphql_name(class_uri);
let collection_field = namer.pluralize(&namer.to_camel_case(&type_name));
let single_field = namer.to_camel_case(&type_name);
fields.insert(
collection_field,
GeneratedField {
class_uri: class_uri.clone(),
is_collection: true,
},
);
fields.insert(
single_field,
GeneratedField {
class_uri: class_uri.clone(),
is_collection: false,
},
);
}
Self {
store,
vocabulary,
fields,
}
}
/// Whether this resolver can resolve `field_name` (i.e. it corresponds
/// to an RDF class discovered in the vocabulary this resolver was
/// built from).
pub fn handles(&self, field_name: &str) -> bool {
self.fields.contains_key(field_name)
}
/// The GraphQL object type names generated from the vocabulary's RDF
/// classes. Callers should mark each of these as an "eager type" on
/// the [`crate::execution::QueryExecutor`] (see `add_eager_type`) so
/// nested selection sets on list items are honored correctly.
pub fn generated_type_names(&self) -> Vec<String> {
let namer = SchemaGenerator::new();
self.vocabulary
.classes
.keys()
.map(|uri| namer.uri_to_graphql_name(uri))
.collect()
}
async fn resolve_instance(&self, class: &RdfClass, subject_uri: &str) -> Result<Value> {
let namer = SchemaGenerator::new();
let mut obj = HashMap::new();
obj.insert(
"id".to_string(),
Value::StringValue(subject_uri.to_string()),
);
obj.insert(
"uri".to_string(),
Value::StringValue(subject_uri.to_string()),
);
for property_uri in &class.properties {
let Some(property) = self.vocabulary.properties.get(property_uri) else {
continue;
};
let field_name = namer.uri_to_graphql_name(&property.uri);
// Note: no `LIMIT` clause here -- the query engine's SPARQL
// parser only accepts a bare `WHERE { ... }` graph pattern with
// nothing trailing after the closing brace (`ORDER BY`/`LIMIT`/
// `OFFSET` all fail to parse), so pagination/truncation is
// applied in Rust below instead.
let query = format!(
"SELECT ?value WHERE {{ {} {} ?value }}",
escape_iri(subject_uri),
escape_iri(&property.uri),
);
let mut values = match self.store.query(&query) {
Ok(results) => extract_single_column(results),
Err(err) => {
tracing::warn!(
"Auto-schema property query for <{}> on <{}> failed: {}",
property.uri,
subject_uri,
err
);
Vec::new()
}
};
values.truncate(MAX_PROPERTY_VALUES);
let field_value = if matches!(property.property_type, PropertyType::ObjectProperty) {
// One level deep only: expose the referenced resource as a
// minimal `{ id uri }` value rather than recursively
// resolving its own properties.
let items: Vec<Value> = values
.into_iter()
.map(|v| {
let mut nested = HashMap::new();
nested.insert("id".to_string(), Value::StringValue(v.clone()));
nested.insert("uri".to_string(), Value::StringValue(v));
Value::ObjectValue(nested)
})
.collect();
pick_cardinality(items, property.functional)
} else {
let items: Vec<Value> = values.into_iter().map(Value::StringValue).collect();
pick_cardinality(items, property.functional)
};
obj.insert(field_name, field_value);
}
Ok(Value::ObjectValue(obj))
}
}
fn pick_cardinality(mut items: Vec<Value>, functional: bool) -> Value {
if functional {
items.drain(..).next().unwrap_or(Value::NullValue)
} else {
Value::ListValue(items)
}
}
#[async_trait]
impl FieldResolver for AutoSchemaResolver {
async fn resolve_field(
&self,
field_name: &str,
args: &HashMap<String, Value>,
_context: &ExecutionContext,
) -> Result<Value> {
let generated = self.fields.get(field_name).ok_or_else(|| {
anyhow!(
"AutoSchemaResolver cannot resolve unknown field '{}'",
field_name
)
})?;
let class = self
.vocabulary
.classes
.get(&generated.class_uri)
.ok_or_else(|| anyhow!("Vocabulary class '{}' not found", generated.class_uri))?;
if generated.is_collection {
let limit = args
.get("limit")
.and_then(|v| match v {
Value::IntValue(i) => Some((*i).max(0) as usize),
_ => None,
})
.unwrap_or(10)
.min(MAX_COLLECTION_LIMIT);
let offset = args
.get("offset")
.and_then(|v| match v {
Value::IntValue(i) => Some((*i).max(0) as usize),
_ => None,
})
.unwrap_or(0);
// Note: no `ORDER BY`/`LIMIT`/`OFFSET` here -- see the
// corresponding note on the per-property query below. Every
// matching subject is fetched, sorted for a deterministic
// order, and then paginated in Rust instead.
let query = format!(
"SELECT DISTINCT ?s WHERE {{ ?s {} {} }}",
escape_iri(RDF_TYPE),
escape_iri(&generated.class_uri),
);
let mut subjects = match self.store.query(&query) {
Ok(results) => extract_single_column(results),
Err(err) => {
return Err(anyhow!(
"Auto-schema collection query for '{}' (class <{}>) failed: {}",
field_name,
generated.class_uri,
err
))
}
};
subjects.sort();
let page: Vec<String> = subjects.into_iter().skip(offset).take(limit).collect();
let mut items = Vec::with_capacity(page.len());
for subject in page {
items.push(self.resolve_instance(class, &subject).await?);
}
Ok(Value::ListValue(items))
} else {
let id = args
.get("id")
.and_then(|v| match v {
Value::StringValue(s) => Some(s.clone()),
_ => None,
})
.ok_or_else(|| anyhow!("'{}' requires an 'id' argument", field_name))?;
// The query engine requires an explicit `WHERE` keyword even
// for `ASK` queries (unlike the SPARQL 1.1 grammar, where it is
// optional).
let query = format!(
"ASK WHERE {{ {} {} {} }}",
escape_iri(&id),
escape_iri(RDF_TYPE),
escape_iri(&generated.class_uri),
);
match self.store.query(&query) {
Ok(QueryResults::Boolean(true)) => self.resolve_instance(class, &id).await,
Ok(_) => Ok(Value::NullValue),
Err(err) => Err(anyhow!(
"Auto-schema single-item query for '{}' (class <{}>) failed: {}",
field_name,
generated.class_uri,
err
)),
}
}
}
}
/// Escape a URI for safe embedding inside a SPARQL `<...>` IRIREF.
///
/// SPARQL IRIREFs forbid `<`, `>`, `"`, `{`, `}`, `|`, `^`, backtick and
/// control characters; without this check, a crafted class/property URI
/// (or, for the singular field, a client-supplied `id` argument) containing
/// one of those characters could break out of the IRIREF and inject
/// arbitrary SPARQL into a query this resolver builds itself. On the rare
/// disallowed input, fall back to a syntactically valid IRI that is
/// guaranteed not to match anything real, rather than embedding the raw
/// value.
fn escape_iri(uri: &str) -> String {
if uri.chars().any(|c| {
matches!(c, '<' | '>' | '"' | '{' | '}' | '|' | '^' | '`' | '\\') || c.is_control()
}) {
"<urn:oxirs-gql:invalid-iri>".to_string()
} else {
format!("<{uri}>")
}
}
/// Pull the (single) bound value out of each solution row of a `SELECT`
/// query result, as plain strings (IRIs/blank node labels/literal
/// lexical forms). Used for both `SELECT ?s ...` and `SELECT ?value ...`
/// queries, which always select exactly one variable.
fn extract_single_column(results: QueryResults) -> Vec<String> {
match results {
QueryResults::Solutions(solutions) => solutions
.into_iter()
.filter_map(|solution| solution.iter().next().map(|(_, term)| term_to_string(term)))
.collect(),
_ => Vec::new(),
}
}
fn term_to_string(term: &oxirs_core::model::Term) -> String {
match term {
oxirs_core::model::Term::NamedNode(node) => node.to_string(),
oxirs_core::model::Term::BlankNode(node) => format!("_:{node}"),
oxirs_core::model::Term::Literal(literal) => literal.value().to_string(),
_ => String::new(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::schema_types::RdfProperty;
use std::collections::HashMap as StdHashMap;
fn build_vocabulary() -> RdfVocabulary {
let person_uri = "http://example.org/Person".to_string();
let name_uri = "http://example.org/name".to_string();
let knows_uri = "http://example.org/knows".to_string();
let mut classes = StdHashMap::new();
classes.insert(
person_uri.clone(),
RdfClass {
uri: person_uri.clone(),
label: Some("Person".to_string()),
comment: None,
super_classes: vec![],
properties: vec![name_uri.clone(), knows_uri.clone()],
},
);
let mut properties = StdHashMap::new();
properties.insert(
name_uri.clone(),
RdfProperty {
uri: name_uri,
label: None,
comment: None,
domain: vec![person_uri.clone()],
range: vec!["http://www.w3.org/2001/XMLSchema#string".to_string()],
property_type: PropertyType::DataProperty,
functional: true,
inverse_functional: false,
},
);
properties.insert(
knows_uri.clone(),
RdfProperty {
uri: knows_uri,
label: None,
comment: None,
domain: vec![person_uri.clone()],
range: vec![person_uri.clone()],
property_type: PropertyType::ObjectProperty,
functional: false,
inverse_functional: false,
},
);
RdfVocabulary {
classes,
properties,
namespaces: StdHashMap::new(),
}
}
fn build_store() -> Arc<RdfStore> {
let mut store = RdfStore::new().expect("failed to create test store");
store
.insert_triple(
"http://example.org/alice",
"http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
"http://example.org/Person",
)
.expect("insert type triple");
store
.insert_triple(
"http://example.org/alice",
"http://example.org/name",
"\"Alice\"",
)
.expect("insert name triple");
store
.insert_triple(
"http://example.org/bob",
"http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
"http://example.org/Person",
)
.expect("insert type triple");
store
.insert_triple(
"http://example.org/bob",
"http://example.org/name",
"\"Bob\"",
)
.expect("insert name triple");
Arc::new(store)
}
#[test]
fn test_field_names_match_schema_generator_conventions() {
let resolver = AutoSchemaResolver::new(build_store(), build_vocabulary());
assert!(
resolver.handles("persons"),
"expected a 'persons' collection field"
);
assert!(
resolver.handles("person"),
"expected a 'person' singular field"
);
assert_eq!(resolver.generated_type_names(), vec!["Person".to_string()]);
}
/// Regression test: this must return real instances from the store,
/// not a fabricated/empty result, once wired up.
#[tokio::test]
async fn test_resolve_collection_field_returns_real_instances() {
let resolver = AutoSchemaResolver::new(build_store(), build_vocabulary());
let context = ExecutionContext::new();
let args = HashMap::new();
let result = resolver
.resolve_field("persons", &args, &context)
.await
.expect("collection field should resolve");
let Value::ListValue(items) = result else {
panic!("expected ListValue, got {result:?}");
};
assert_eq!(items.len(), 2);
for item in &items {
let Value::ObjectValue(obj) = item else {
panic!("expected ObjectValue item, got {item:?}");
};
assert!(obj.contains_key("id"));
assert!(obj.contains_key("Name"));
}
}
#[tokio::test]
async fn test_resolve_single_field_by_id() {
let resolver = AutoSchemaResolver::new(build_store(), build_vocabulary());
let context = ExecutionContext::new();
let mut args = HashMap::new();
args.insert(
"id".to_string(),
Value::StringValue("http://example.org/alice".to_string()),
);
let result = resolver
.resolve_field("person", &args, &context)
.await
.expect("singular field should resolve");
let Value::ObjectValue(obj) = result else {
panic!("expected ObjectValue, got {result:?}");
};
assert_eq!(
obj.get("id"),
Some(&Value::StringValue("http://example.org/alice".to_string()))
);
}
#[tokio::test]
async fn test_resolve_single_field_returns_null_for_wrong_type() {
let resolver = AutoSchemaResolver::new(build_store(), build_vocabulary());
let context = ExecutionContext::new();
let mut args = HashMap::new();
args.insert(
"id".to_string(),
Value::StringValue("http://example.org/not-a-person".to_string()),
);
let result = resolver
.resolve_field("person", &args, &context)
.await
.expect("singular field should resolve to null, not error");
assert_eq!(result, Value::NullValue);
}
/// A crafted `id` argument that attempts to break out of the SPARQL
/// IRIREF must not be able to inject SPARQL syntax; it should be
/// treated as a syntactically-safe non-matching IRI instead.
#[tokio::test]
async fn test_resolve_single_field_rejects_iri_injection_attempt() {
let resolver = AutoSchemaResolver::new(build_store(), build_vocabulary());
let context = ExecutionContext::new();
let mut args = HashMap::new();
args.insert(
"id".to_string(),
Value::StringValue(
"http://example.org/alice> } . SELECT * WHERE { ?s ?p ?o".to_string(),
),
);
let result = resolver.resolve_field("person", &args, &context).await;
// Must not error out with a SPARQL syntax error (which would mean
// the injected fragment reached the query string unescaped) and
// must not resolve to a real instance either.
assert_eq!(result.expect("should not error"), Value::NullValue);
}
#[tokio::test]
async fn test_resolve_unknown_field_errors() {
let resolver = AutoSchemaResolver::new(build_store(), build_vocabulary());
let context = ExecutionContext::new();
let result = resolver
.resolve_field("nonexistent", &HashMap::new(), &context)
.await;
assert!(result.is_err());
}
}