diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e94dd6af..44cb4e041 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ### Added - `sparopt`: `GraphPattern::join_order_variables`, exposing the join / variable-elimination order chosen by `Optimizer::optimize_graph_pattern` for consumption by external execution engines (e.g. worst-case-optimal join executors). +- `oxigraph`: `Store::count_quads_for_pattern`, `Snapshot::count_quads_for_pattern` and `Transaction::count_quads_for_pattern`, returning how many quads match a pattern without decoding them. +- Python: the `Store.count_quads_for_pattern` method, counting the quads matching a pattern without building the `Quad` objects. ### Fixed - Turtle, TriG, N-Triples, N-Quads, RDF/XML and SPARQL JSON and XML results: a triple term nested more than 128 deep is now a syntax error, the same limit as `Term::from_str`. Very deeply nested terms overflowed the stack when they were cloned, dropped or printed. A SPARQL XML results `` must have exactly one subject, predicate and object. diff --git a/lib/oxigraph/src/storage/mod.rs b/lib/oxigraph/src/storage/mod.rs index 97f740723..b3356fa30 100644 --- a/lib/oxigraph/src/storage/mod.rs +++ b/lib/oxigraph/src/storage/mod.rs @@ -250,6 +250,29 @@ impl<'a> StorageReader<'a> { } } + pub fn count_quads_for_pattern( + &self, + subject: Option<&EncodedTerm>, + predicate: Option<&EncodedTerm>, + object: Option<&EncodedTerm>, + graph_name: Option<&EncodedTerm>, + ) -> Result { + match &self.kind { + #[cfg(all(not(target_family = "wasm"), feature = "rocksdb"))] + StorageReaderKind::RocksDb(reader) => { + let mut count = 0; + for quad in reader.quads_for_pattern(subject, predicate, object, graph_name) { + quad?; + count += 1; + } + Ok(count) + } + StorageReaderKind::Memory(reader) => Ok(reader + .quads_for_pattern(subject, predicate, object, graph_name) + .count()), + } + } + pub fn triples_for_pattern( &self, subject: Option<&EncodedTerm>, diff --git a/lib/oxigraph/src/store.rs b/lib/oxigraph/src/store.rs index 407ddc6b6..a3893b219 100644 --- a/lib/oxigraph/src/store.rs +++ b/lib/oxigraph/src/store.rs @@ -242,6 +242,44 @@ impl Store { .quads_for_pattern(subject, predicate, object, graph_name) } + /// Returns the number of quads matching a filter on each quad component. + /// + /// This is faster than counting the results of [`quads_for_pattern`](Store::quads_for_pattern): + /// the matching quads are counted in the index without being decoded. + /// + ///
This function executes a full scan of the matching quads.
+ /// + /// Usage example: + /// ``` + /// use oxigraph::model::*; + /// use oxigraph::store::Store; + /// + /// let store = Store::new()?; + /// let ex = NamedNode::new("http://example.com")?; + /// let g: GraphName = NamedNode::new("http://example.com/g")?.into(); + /// store.insert(Quad::new(ex.clone(), ex.clone(), ex.clone(), g.clone()))?; + /// store.insert(Quad::new( + /// ex.clone(), + /// ex.clone(), + /// ex.clone(), + /// GraphName::DefaultGraph, + /// ))?; + /// + /// assert_eq!(2, store.count_quads_for_pattern(None, None, None, None)?); + /// assert_eq!(1, store.count_quads_for_pattern(None, None, None, Some(&g))?); + /// # Result::<_, Box>::Ok(()) + /// ``` + pub fn count_quads_for_pattern( + &self, + subject: Option<&NamedOrBlankNode>, + predicate: Option<&NamedNode>, + object: Option<&Term>, + graph_name: Option<&GraphName>, + ) -> Result { + self.snapshot() + .count_quads_for_pattern(subject, predicate, object, graph_name) + } + /// Returns all the quads contained in the store. /// /// Usage example: @@ -919,6 +957,24 @@ impl Snapshot { } } + /// Returns the number of quads matching a filter on each quad component. + /// + /// See [`Store::count_quads_for_pattern`]. + pub fn count_quads_for_pattern( + &self, + subject: Option<&NamedOrBlankNode>, + predicate: Option<&NamedNode>, + object: Option<&Term>, + graph_name: Option<&GraphName>, + ) -> Result { + self.reader.count_quads_for_pattern( + subject.map(EncodedTerm::from).as_ref(), + predicate.map(EncodedTerm::from).as_ref(), + object.map(EncodedTerm::from).as_ref(), + graph_name.map(EncodedTerm::from).as_ref(), + ) + } + /// Returns all the quads contained in the snapshot. pub fn iter(&self) -> QuadIter<'static> { self.quads_for_pattern(None, None, None, None) @@ -1008,6 +1064,24 @@ impl<'a> Transaction<'a> { } } + /// Returns the number of quads matching a filter on each quad component. + /// + /// See [`Store::count_quads_for_pattern`]. + pub fn count_quads_for_pattern( + &self, + subject: Option<&NamedOrBlankNode>, + predicate: Option<&NamedNode>, + object: Option<&Term>, + graph_name: Option<&GraphName>, + ) -> Result { + self.inner.reader().count_quads_for_pattern( + subject.map(EncodedTerm::from).as_ref(), + predicate.map(EncodedTerm::from).as_ref(), + object.map(EncodedTerm::from).as_ref(), + graph_name.map(EncodedTerm::from).as_ref(), + ) + } + /// Returns all the quads contained in the store. pub fn iter(&self) -> QuadIter<'_> { self.quads_for_pattern(None, None, None, None) diff --git a/lib/oxigraph/tests/store.rs b/lib/oxigraph/tests/store.rs index 39d89ef79..2a58627e0 100644 --- a/lib/oxigraph/tests/store.rs +++ b/lib/oxigraph/tests/store.rs @@ -784,3 +784,133 @@ fn test_snapshot_is_pinned_to_one_state() -> Result<(), Box> { ); Ok(()) } + +fn insert_count_quads_for_pattern_data(store: &Store) -> Result<(), Box> { + let s = NamedNode::new("http://example.com/s")?; + let s2 = NamedNode::new("http://example.com/s2")?; + let p = NamedNode::new("http://example.com/p")?; + let o = NamedNode::new("http://example.com/o")?; + let g = NamedNode::new("http://example.com/g")?; + // The same triple in the default graph and in a named graph. + store.insert(Quad::new( + s.clone(), + p.clone(), + o.clone(), + GraphName::DefaultGraph, + ))?; + store.insert(Quad::new(s.clone(), p.clone(), o.clone(), g.clone()))?; + store.insert(Quad::new(s2, p.clone(), o, g.clone()))?; + store.insert(Quad::new(s, p, Literal::new_simple_literal("o2"), g))?; + Ok(()) +} + +/// `count_quads_for_pattern` must return exactly what `quads_for_pattern` yields, +/// for every combination of bound, unbound and unmatched components. +fn assert_count_quads_for_pattern_matches_iteration(store: &Store) -> Result<(), Box> { + let missing = NamedNode::new("http://example.com/missing")?; + let subjects = [ + None, + Some(NamedOrBlankNode::from(NamedNode::new( + "http://example.com/s", + )?)), + Some(NamedOrBlankNode::from(NamedNode::new( + "http://example.com/s2", + )?)), + Some(NamedOrBlankNode::from(missing.clone())), + ]; + let predicates = [ + None, + Some(NamedNode::new("http://example.com/p")?), + Some(missing.clone()), + ]; + let objects = [ + None, + Some(Term::from(NamedNode::new("http://example.com/o")?)), + Some(Term::from(Literal::new_simple_literal("o2"))), + Some(Term::from(missing.clone())), + ]; + let graph_names = [ + None, + Some(GraphName::DefaultGraph), + Some(GraphName::from(NamedNode::new("http://example.com/g")?)), + Some(GraphName::from(missing)), + ]; + + for subject in &subjects { + for predicate in &predicates { + for object in &objects { + for graph_name in &graph_names { + let subject = subject.as_ref(); + let predicate = predicate.as_ref(); + let object = object.as_ref(); + let graph_name = graph_name.as_ref(); + assert_eq!( + store.count_quads_for_pattern(subject, predicate, object, graph_name)?, + store + .quads_for_pattern(subject, predicate, object, graph_name) + .collect::, _>>()? + .len(), + "pattern ({subject:?}, {predicate:?}, {object:?}, {graph_name:?})" + ); + } + } + } + } + Ok(()) +} + +#[test] +fn test_count_quads_for_pattern() -> Result<(), Box> { + let store = Store::new()?; + insert_count_quads_for_pattern_data(&store)?; + assert_eq!(store.count_quads_for_pattern(None, None, None, None)?, 4); + assert_count_quads_for_pattern_matches_iteration(&store)?; + Ok(()) +} + +#[test] +#[cfg(all(not(target_family = "wasm"), feature = "rocksdb"))] +fn test_count_quads_for_pattern_on_disk() -> Result<(), Box> { + let dir = TempDir::new()?; + let store = Store::open(&dir)?; + insert_count_quads_for_pattern_data(&store)?; + assert_eq!(store.count_quads_for_pattern(None, None, None, None)?, 4); + assert_count_quads_for_pattern_matches_iteration(&store)?; + Ok(()) +} + +#[test] +fn test_count_quads_for_pattern_on_empty_store() -> Result<(), Box> { + let store = Store::new()?; + let ex = NamedNode::new("http://example.com")?; + assert_eq!(store.count_quads_for_pattern(None, None, None, None)?, 0); + assert_eq!( + store.count_quads_for_pattern(None, None, None, Some(&ex.into()))?, + 0 + ); + Ok(()) +} + +#[test] +fn test_count_quads_for_pattern_isolation() -> Result<(), Box> { + let ex = NamedNode::new("http://example.com")?; + let q1 = Quad::new(ex.clone(), ex.clone(), ex.clone(), GraphName::DefaultGraph); + let q2 = Quad::new(ex.clone(), ex.clone(), ex.clone(), ex); + let store = Store::new()?; + store.insert(q1)?; + let snapshot = store.snapshot(); + + let mut transaction = store.start_transaction()?; + transaction.insert(q2); + // A transaction reads its own writes. + assert_eq!( + transaction.count_quads_for_pattern(None, None, None, None)?, + 2 + ); + transaction.commit()?; + + assert_eq!(store.count_quads_for_pattern(None, None, None, None)?, 2); + // The snapshot stays pinned to the state it was taken in. + assert_eq!(snapshot.count_quads_for_pattern(None, None, None, None)?, 1); + Ok(()) +} diff --git a/python/src/store.rs b/python/src/store.rs index ffb6501d6..85f015f80 100644 --- a/python/src/store.rs +++ b/python/src/store.rs @@ -221,6 +221,51 @@ impl PyStore { } } + /// Returns the number of quads matching a given pattern. + /// + /// This is faster than counting the results of :py:meth:`Store.quads_for_pattern`: + /// the matching quads are counted inside of the store without being converted + /// to Python objects. + /// + /// :param subject: the quad subject or :py:const:`None` to match everything. + /// :type subject: NamedNode or BlankNode or Triple or None + /// :param predicate: the quad predicate or :py:const:`None` to match everything. + /// :type predicate: NamedNode or None + /// :param object: the quad object or :py:const:`None` to match everything. + /// :type object: NamedNode or BlankNode or Literal or Triple or None + /// :param graph_name: the quad graph name. To match only the default graph, use :py:class:`DefaultGraph`. To match everything use :py:const:`None`. + /// :type graph_name: NamedNode or BlankNode or DefaultGraph or None, optional + /// :return: the number of quads matching the pattern. + /// :rtype: int + /// :raises OSError: if an error happens during the quads lookup. + /// + /// >>> store = Store() + /// >>> store.add(Quad(NamedNode('http://example.com'), NamedNode('http://example.com/p'), Literal('1'), NamedNode('http://example.com/g'))) + /// >>> store.count_quads_for_pattern(NamedNode('http://example.com'), None, None, None) + /// 1 + /// >>> store.count_quads_for_pattern(None, None, None, DefaultGraph()) + /// 0 + #[pyo3(signature = (subject, predicate, object, graph_name = None))] + fn count_quads_for_pattern( + &self, + subject: Option, + predicate: Option, + object: Option, + graph_name: Option, + py: Python<'_>, + ) -> PyResult { + py.detach(|| { + self.inner + .count_quads_for_pattern( + subject.map(Into::into).as_ref(), + predicate.map(Into::into).as_ref(), + object.map(Into::into).as_ref(), + graph_name.map(Into::into).as_ref(), + ) + .map_err(map_storage_error) + }) + } + /// Executes a `SPARQL 1.1 query `_. /// /// :param query: the query to execute. diff --git a/python/tests/test_store.py b/python/tests/test_store.py index 1099e2cc1..6582bd29b 100644 --- a/python/tests/test_store.py +++ b/python/tests/test_store.py @@ -107,6 +107,45 @@ def test_quads_for_pattern(self) -> None: {Quad(foo, bar, baz, DefaultGraph())}, ) + def test_count_quads_for_pattern(self) -> None: + store = Store() + store.add(Quad(foo, bar, baz, DefaultGraph())) + store.add(Quad(foo, bar, baz, graph)) + store.add(Quad(bar, bar, baz, graph)) + self.assertEqual(store.count_quads_for_pattern(None, None, None), 3) + self.assertEqual(store.count_quads_for_pattern(foo, None, None), 2) + self.assertEqual(store.count_quads_for_pattern(None, None, None, graph), 2) + self.assertEqual(store.count_quads_for_pattern(None, None, None, DefaultGraph()), 1) + self.assertEqual(store.count_quads_for_pattern(foo, bar, baz, graph), 1) + self.assertEqual(store.count_quads_for_pattern(baz, None, None), 0) + self.assertEqual( + store.count_quads_for_pattern(None, None, None, NamedNode("http://other")), + 0, + ) + + def test_count_quads_for_pattern_matches_quads_for_pattern(self) -> None: + store = Store() + store.add(Quad(foo, bar, baz, DefaultGraph())) + store.add(Quad(foo, bar, baz, graph)) + store.add(Quad(bar, bar, triple, graph)) + patterns: list[tuple] = [ + (None, None, None, None), + (foo, None, None, None), + (None, bar, None, None), + (None, None, baz, None), + (None, None, None, graph), + (None, None, None, DefaultGraph()), + (foo, bar, baz, graph), + (bar, bar, triple, None), + (baz, None, None, None), + ] + for pattern in patterns: + with self.subTest(pattern=pattern): + self.assertEqual( + store.count_quads_for_pattern(*pattern), + len(list(store.quads_for_pattern(*pattern))), + ) + def test_ask_query(self) -> None: store = Store() store.add(Quad(foo, foo, foo))