1use std::collections::{HashMap, HashSet};
20
21use waratah_storage::EncodedTriplePattern;
22use waratah_storage::IndexPermutation;
23use waratah_storage::PartitionAxis;
24use waratah_storage::SnapshotId;
25use waratah_storage::Term;
26use waratah_storage::vocab::rdfs;
27
28use crate::clients::{
29 BlobStoreClient, HexastoreCatalog, HexastoreGeo, HexastoreScan, StringResolve,
30};
31use crate::error::ComputeError;
32use crate::node::ComputeNode;
33use crate::solutions::QueryResults;
34
35pub const MAX_CLASSES: usize = 200;
37pub const MAX_PROPERTIES: usize = 400;
39pub const AUTO_INSTANCE_COUNT_MAX_TRIPLES: u64 = 2_000_000;
41
42pub struct SchemaSummaryLimits {
44 pub max_classes: usize,
46 pub max_properties: usize,
48}
49
50pub fn schema_summary_limits() -> SchemaSummaryLimits {
53 SchemaSummaryLimits {
54 max_classes: MAX_CLASSES,
55 max_properties: MAX_PROPERTIES,
56 }
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum InstanceCounts {
62 Auto,
64 Always,
66 Never,
68}
69
70#[derive(Debug, Clone)]
73pub struct SchemaSummaryParams {
74 pub class_limit: usize,
76 pub property_limit: usize,
78 pub instance_counts: InstanceCounts,
80 pub triple_count: Option<u64>,
87}
88
89#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct ClassSummary {
92 pub iri: String,
94 pub label: Option<String>,
96 pub comment: Option<String>,
98 pub super_classes: Vec<String>,
105 pub instance_count: Option<u64>,
107}
108
109#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct PropertySummary {
112 pub iri: String,
114 pub label: Option<String>,
116 pub kind: PropertyKind,
119 pub domain: Option<String>,
121 pub range: Option<String>,
123 pub sub_property_of: Vec<String>,
125}
126
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub enum PropertyKind {
130 Object,
132 Data,
134 Other,
136}
137
138#[derive(Debug, Clone, PartialEq, Eq)]
140pub struct SchemaSummary {
141 pub triple_count: u64,
143 pub classes: Vec<ClassSummary>,
146 pub classes_clipped: bool,
148 pub properties: Vec<PropertySummary>,
150 pub properties_clipped: bool,
152 pub instance_counts_computed: bool,
155}
156
157const OWL_OBJECT_PROPERTY: &str = "http://www.w3.org/2002/07/owl#ObjectProperty";
159const OWL_DATATYPE_PROPERTY: &str = "http://www.w3.org/2002/07/owl#DatatypeProperty";
160const RDF_PROPERTY: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#Property";
161
162impl<H: HexastoreScan + HexastoreCatalog + HexastoreGeo, R: StringResolve + BlobStoreClient>
163 ComputeNode<H, R>
164{
165 pub async fn schema_summary(
168 &self,
169 params: &SchemaSummaryParams,
170 ) -> Result<SchemaSummary, ComputeError> {
171 let snapshot = SnapshotId::latest();
172 let triple_count = match params.triple_count {
178 Some(count) => count,
179 None => self.union_quad_count(snapshot).await?,
180 };
181 let count_instances = match params.instance_counts {
182 InstanceCounts::Never => false,
183 InstanceCounts::Always => true,
184 InstanceCounts::Auto => triple_count <= AUTO_INSTANCE_COUNT_MAX_TRIPLES,
185 };
186
187 let ctx = self.context(snapshot).with_default_union(true);
189
190 let (class_rows, instance_counts) = if count_instances {
201 let sparql = format!(
202 "SELECT ?cls (COUNT(DISTINCT ?s) AS ?n) WHERE {{ ?s a ?cls }} \
203 GROUP BY ?cls LIMIT {}",
204 params.class_limit.saturating_add(1)
205 );
206 let rows = self.select_rows(&ctx, &sparql).await?;
207 let counts: HashMap<String, u64> = rows
208 .iter()
209 .filter_map(|row| row.iri(0).zip(row.integer(1)))
210 .collect();
211 (rows, counts)
212 } else {
213 let sparql = format!(
214 "SELECT DISTINCT ?cls WHERE {{ ?s a ?cls }} LIMIT {}",
215 params.class_limit.saturating_add(1)
216 );
217 (self.select_rows(&ctx, &sparql).await?, HashMap::new())
218 };
219 let classes_clipped = class_rows.len() > params.class_limit;
220 let mut class_iris: Vec<String> = class_rows
221 .into_iter()
222 .take(params.class_limit)
223 .filter_map(|row| row.iri(0))
224 .collect();
225 if count_instances {
226 class_iris.sort_by(|a, b| {
230 instance_counts
231 .get(b)
232 .cmp(&instance_counts.get(a))
233 .then_with(|| a.cmp(b))
234 });
235 } else {
236 class_iris.sort_unstable();
237 }
238 class_iris.dedup();
239
240 let property_sparql = format!(
241 "SELECT DISTINCT ?p WHERE {{ ?s ?p ?o }} LIMIT {}",
242 params.property_limit.saturating_add(1)
243 );
244 let properties_clipped_rows = self.select_rows(&ctx, &property_sparql).await?;
245 let properties_clipped = properties_clipped_rows.len() > params.property_limit;
246 let mut property_iris: Vec<String> = properties_clipped_rows
247 .into_iter()
248 .take(params.property_limit)
249 .filter_map(|row| row.iri(0))
250 .collect();
251 property_iris.sort_unstable();
252 property_iris.dedup();
253
254 let mut all_iris = class_iris.clone();
259 all_iris.extend(property_iris.iter().cloned());
260 let labels = self
261 .facet_literals(&ctx, rdfs::LABEL.as_str(), &all_iris)
262 .await?;
263 let comments = self
264 .facet_literals(&ctx, rdfs::COMMENT.as_str(), &class_iris)
265 .await?;
266 let domains = self
267 .facet_iris(&ctx, rdfs::DOMAIN.as_str(), &property_iris)
268 .await?;
269 let ranges = self
270 .facet_iris(&ctx, rdfs::RANGE.as_str(), &property_iris)
271 .await?;
272 let sub_property_of = self
273 .facet_iri_lists(&ctx, rdfs::SUB_PROPERTY_OF.as_str(), &property_iris)
274 .await?;
275 let kinds = self.property_kinds(&ctx, &property_iris).await?;
276
277 let super_edges = self.super_class_edges(&ctx, &class_iris).await?;
280
281 let classes = class_iris
282 .iter()
283 .map(|iri| ClassSummary {
284 iri: iri.clone(),
285 label: labels.get(iri).cloned(),
286 comment: comments.get(iri).cloned(),
287 super_classes: closure_of(iri, &super_edges),
288 instance_count: if count_instances {
289 instance_counts.get(iri).copied()
290 } else {
291 None
292 },
293 })
294 .collect();
295 let properties = property_iris
296 .iter()
297 .map(|iri| PropertySummary {
298 iri: iri.clone(),
299 label: labels.get(iri).cloned(),
300 kind: kinds.get(iri).copied().unwrap_or(PropertyKind::Other),
301 domain: domains.get(iri).cloned(),
302 range: ranges.get(iri).cloned(),
303 sub_property_of: sub_property_of.get(iri).cloned().unwrap_or_default(),
304 })
305 .collect();
306 Ok(SchemaSummary {
307 triple_count,
308 classes,
309 classes_clipped,
310 properties,
311 properties_clipped,
312 instance_counts_computed: count_instances,
313 })
314 }
315
316 pub async fn union_quad_count(&self, snapshot: SnapshotId) -> Result<u64, ComputeError> {
320 let pattern = EncodedTriplePattern {
321 subject: None,
322 predicate: None,
323 object: None,
324 graph_name: None,
325 };
326 self.queries()
327 .count_encoded_pattern(
328 &pattern,
329 snapshot,
330 PartitionAxis::S,
331 Some(IndexPermutation::Spog),
332 )
333 .await
334 }
335
336 async fn select_rows(
339 &self,
340 ctx: &crate::context::QueryContext,
341 sparql: &str,
342 ) -> Result<Vec<Row>, ComputeError> {
343 let solutions = match self.query_with(sparql, ctx).await? {
344 QueryResults::Solutions { solutions, .. } => solutions,
345 _ => Vec::new(),
346 };
347 Ok(solutions.into_iter().map(Row).collect())
348 }
349
350 async fn facet_literals(
355 &self,
356 ctx: &crate::context::QueryContext,
357 predicate: &str,
358 iris: &[String],
359 ) -> Result<HashMap<String, String>, ComputeError> {
360 let mut map = HashMap::new();
361 for row in self.facet_rows(ctx, predicate, iris).await? {
362 if let (Some(key), Some(value)) = (row.iri(0), row.string(1)) {
363 map.entry(key).or_insert(value);
364 }
365 }
366 Ok(map)
367 }
368
369 async fn facet_iris(
371 &self,
372 ctx: &crate::context::QueryContext,
373 predicate: &str,
374 iris: &[String],
375 ) -> Result<HashMap<String, String>, ComputeError> {
376 let mut map = HashMap::new();
377 for row in self.facet_rows(ctx, predicate, iris).await? {
378 if let (Some(key), Some(value)) = (row.iri(0), row.iri(1)) {
379 map.entry(key).or_insert(value);
380 }
381 }
382 Ok(map)
383 }
384
385 async fn facet_iri_lists(
387 &self,
388 ctx: &crate::context::QueryContext,
389 predicate: &str,
390 iris: &[String],
391 ) -> Result<HashMap<String, Vec<String>>, ComputeError> {
392 let mut map: HashMap<String, Vec<String>> = HashMap::new();
393 for row in self.facet_rows(ctx, predicate, iris).await? {
394 if let (Some(key), Some(value)) = (row.iri(0), row.iri(1)) {
395 map.entry(key).or_default().push(value);
396 }
397 }
398 for values in map.values_mut() {
399 values.sort_unstable();
400 values.dedup();
401 }
402 Ok(map)
403 }
404
405 async fn facet_rows(
409 &self,
410 ctx: &crate::context::QueryContext,
411 predicate: &str,
412 iris: &[String],
413 ) -> Result<Vec<Row>, ComputeError> {
414 if iris.is_empty() {
415 return Ok(Vec::new());
416 }
417 let mut sparql = String::from("SELECT ?x ?v WHERE { VALUES ?x { ");
418 for iri in iris {
419 sparql.push_str(&sparql_iri(iri));
420 sparql.push(' ');
421 }
422 sparql.push_str("} ?x ");
423 sparql.push_str(&sparql_iri(predicate));
424 sparql.push_str(" ?v }");
425 let mut rows = self.select_rows(ctx, &sparql).await?;
426 rows.sort_by(|a, b| {
427 a.render(0)
428 .cmp(&b.render(0))
429 .then_with(|| a.render(1).cmp(&b.render(1)))
430 });
431 Ok(rows)
432 }
433
434 async fn property_kinds(
440 &self,
441 ctx: &crate::context::QueryContext,
442 iris: &[String],
443 ) -> Result<HashMap<String, PropertyKind>, ComputeError> {
444 if iris.is_empty() {
445 return Ok(HashMap::new());
446 }
447 let mut sparql = String::from("SELECT ?x ?t WHERE { VALUES ?x { ");
448 for iri in iris {
449 sparql.push_str(&sparql_iri(iri));
450 sparql.push(' ');
451 }
452 sparql.push_str(
453 "} ?x a ?t FILTER(?t IN (\
454 <http://www.w3.org/2002/07/owl#ObjectProperty>, \
455 <http://www.w3.org/2002/07/owl#DatatypeProperty>, \
456 <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property>)) }",
457 );
458 let rows = self.select_rows(ctx, &sparql).await?;
459 let mut kinds: HashMap<String, PropertyKind> = HashMap::new();
460 for row in rows {
461 let (property, declared) = match (row.iri(0), row.iri(1)) {
462 (Some(property), Some(declared)) => (property, declared),
463 _ => continue,
464 };
465 let kind = match declared.as_str() {
466 OWL_OBJECT_PROPERTY => PropertyKind::Object,
467 OWL_DATATYPE_PROPERTY => PropertyKind::Data,
468 RDF_PROPERTY => PropertyKind::Other,
470 _ => continue,
471 };
472 let entry = kinds.entry(property).or_insert(kind);
476 if kind_rank(kind) > kind_rank(*entry) {
477 *entry = kind;
478 }
479 }
480 Ok(kinds)
481 }
482
483 async fn super_class_edges(
490 &self,
491 ctx: &crate::context::QueryContext,
492 seeds: &[String],
493 ) -> Result<HashMap<String, Vec<String>>, ComputeError> {
494 let mut edges: HashMap<String, Vec<String>> = HashMap::new();
495 let mut known: HashSet<String> = seeds.iter().cloned().collect();
496 let mut frontier: Vec<String> = seeds.to_vec();
497 while !frontier.is_empty() {
498 let mut rows = self
499 .facet_rows(ctx, rdfs::SUB_CLASS_OF.as_str(), &frontier)
500 .await?;
501 rows.dedup_by(|a, b| a.iri(0) == b.iri(0) && a.iri(1) == b.iri(1));
502 let mut next = Vec::new();
503 for row in rows {
504 let (child, parent) = match (row.iri(0), row.iri(1)) {
505 (Some(child), Some(parent)) => (child, parent),
506 _ => continue,
507 };
508 edges.entry(child).or_default().push(parent.clone());
509 if known.insert(parent.clone()) {
510 next.push(parent);
511 }
512 }
513 frontier = next;
514 }
515 for parents in edges.values_mut() {
516 parents.sort_unstable();
517 parents.dedup();
518 }
519 Ok(edges)
520 }
521}
522
523#[derive(Debug, Clone)]
527struct Row(Vec<Option<Term>>);
528
529impl Row {
530 fn iri(&self, index: usize) -> Option<String> {
532 match self.0.get(index)? {
533 Some(Term::NamedNode(node)) => Some(node.as_str().to_owned()),
534 _ => None,
535 }
536 }
537
538 fn string(&self, index: usize) -> Option<String> {
540 match self.0.get(index)? {
541 Some(Term::Literal(literal)) => Some(literal.value().to_owned()),
542 _ => None,
543 }
544 }
545
546 fn integer(&self, index: usize) -> Option<u64> {
548 match self.0.get(index)? {
549 Some(Term::Literal(literal)) => literal.value().parse().ok(),
550 _ => None,
551 }
552 }
553
554 fn render(&self, index: usize) -> String {
556 match self.0.get(index) {
557 Some(Some(term)) => term.to_string(),
558 _ => String::new(),
559 }
560 }
561}
562
563fn kind_rank(kind: PropertyKind) -> u8 {
566 match kind {
567 PropertyKind::Object => 2,
568 PropertyKind::Data => 1,
569 PropertyKind::Other => 0,
570 }
571}
572
573fn closure_of(start: &str, edges: &HashMap<String, Vec<String>>) -> Vec<String> {
575 let mut visited: HashSet<String> = HashSet::new();
576 let mut stack: Vec<String> = edges
577 .get(start)
578 .map(|parents| parents.iter().rev().cloned().collect())
579 .unwrap_or_default();
580 while let Some(current) = stack.pop() {
581 if !visited.insert(current.clone()) {
582 continue;
583 }
584 if let Some(parents) = edges.get(¤t) {
585 for parent in parents {
586 stack.push(parent.clone());
587 }
588 }
589 }
590 let mut closure: Vec<String> = visited.into_iter().collect();
591 closure.sort_unstable();
592 closure
593}
594
595fn sparql_iri(iri: &str) -> String {
599 let mut out = String::with_capacity(iri.len() + 2);
600 out.push('<');
601 for character in iri.chars() {
602 let forbidden = matches!(
603 character,
604 '\\' | '<' | '>' | '"' | '{' | '}' | '|' | '^' | '`'
605 ) || character <= '\u{20}';
606 if forbidden {
607 out.push_str(&format!("\\u{:04X}", character as u32));
608 } else {
609 out.push(character);
610 }
611 }
612 out.push('>');
613 out
614}
615
616#[cfg(test)]
617mod tests {
618 use super::*;
619
620 #[test]
621 fn iris_are_escaped_only_where_the_grammar_requires() {
622 assert_eq!(sparql_iri("http://ex/a"), "<http://ex/a>");
623 assert_eq!(
624 sparql_iri("http://ex/a b<c>"),
625 "<http://ex/a\\u0020b\\u003Cc\\u003E>"
626 );
627 assert_eq!(sparql_iri("http://ex/a\\b"), "<http://ex/a\\u005Cb>");
629 }
630
631 #[test]
632 fn closure_is_transitive_and_cycle_safe() {
633 let mut edges = HashMap::new();
634 edges.insert(
635 "http://ex/Person".to_owned(),
636 vec!["http://ex/Agent".to_owned()],
637 );
638 edges.insert(
639 "http://ex/Agent".to_owned(),
640 vec!["http://ex/Thing".to_owned()],
641 );
642 edges.insert(
644 "http://ex/Thing".to_owned(),
645 vec!["http://ex/Person".to_owned()],
646 );
647 assert_eq!(
648 closure_of("http://ex/Person", &edges),
649 vec![
650 "http://ex/Agent".to_owned(),
651 "http://ex/Person".to_owned(),
652 "http://ex/Thing".to_owned()
653 ]
654 );
655 assert!(closure_of("http://ex/Leaf", &edges).is_empty());
656 }
657}