Enables more Clippy lints and enforces them

pull/171/head
Tpt 3 years ago
parent 1abda73dc9
commit f084cfe332
  1. 1
      clippy.toml
  2. 4
      lib/Cargo.toml
  3. 6
      lib/src/error.rs
  4. 12
      lib/src/io/format.rs
  5. 20
      lib/src/io/read.rs
  6. 2
      lib/src/io/write.rs
  7. 87
      lib/src/lib.rs
  8. 55
      lib/src/model/dataset.rs
  9. 4
      lib/src/model/graph.rs
  10. 4
      lib/src/model/interning.rs
  11. 56
      lib/src/model/literal.rs
  12. 6
      lib/src/model/parser.rs
  13. 50
      lib/src/model/sophia.rs
  14. 4
      lib/src/model/triple.rs
  15. 2
      lib/src/model/vocab.rs
  16. 44
      lib/src/model/xsd/date_time.rs
  17. 18
      lib/src/model/xsd/decimal.rs
  18. 32
      lib/src/model/xsd/duration.rs
  19. 12
      lib/src/model/xsd/parser.rs
  20. 16
      lib/src/sophia.rs
  21. 16
      lib/src/sparql/algebra.rs
  22. 8
      lib/src/sparql/dataset.rs
  23. 2
      lib/src/sparql/error.rs
  24. 133
      lib/src/sparql/eval.rs
  25. 31
      lib/src/sparql/http/simple.rs
  26. 16
      lib/src/sparql/mod.rs
  27. 16
      lib/src/sparql/model.rs
  28. 234
      lib/src/sparql/plan.rs
  29. 13
      lib/src/sparql/plan_builder.rs
  30. 166
      lib/src/sparql/update.rs
  31. 8
      lib/src/sparql/xml_results.rs
  32. 11
      lib/src/storage/io.rs
  33. 41
      lib/src/storage/mod.rs
  34. 41
      lib/src/storage/numeric_encoder.rs
  35. 6
      lib/src/storage/small_string.rs
  36. 6
      lib/src/store.rs
  37. 2
      server/src/main.rs
  38. 2
      spargebra/Cargo.toml
  39. 106
      spargebra/src/algebra.rs
  40. 8
      spargebra/src/parser.rs
  41. 4
      spargebra/src/term.rs
  42. 8
      wikibase/src/main.rs

@ -1,3 +1,4 @@
avoid-breaking-exported-api = false
cognitive-complexity-threshold = 50
too-many-arguments-threshold = 10
type-complexity-threshold = 500

@ -39,7 +39,7 @@ hex = "0.4"
nom = "6"
siphasher = "0.3"
lasso = "0.5"
sophia_api = { version = "0.6.2", optional = true }
sophia_api = { version = "0.7", optional = true }
http = "0.2"
httparse = { version = "1", optional = true }
native-tls = { version = "0.2", optional = true }
@ -50,7 +50,7 @@ spargebra = { version = "0.1", path="../spargebra", features = ["rdf-star"] }
[dev-dependencies]
rayon = "1"
criterion = "0.3"
sophia_api = { version = "0.6.2", features = ["test_macro"] }
sophia_api = { version = "0.7", features = ["test_macro"] }
[[bench]]
name = "store"

@ -3,7 +3,7 @@ use std::error::Error;
use std::io;
/// Traits that allows unwrapping only infallible results
pub(crate) trait UnwrapInfallible {
pub trait UnwrapInfallible {
type Value;
fn unwrap_infallible(self) -> Self::Value;
@ -20,10 +20,10 @@ impl<T> UnwrapInfallible for Result<T, Infallible> {
}
}
pub(crate) fn invalid_data_error(error: impl Into<Box<dyn Error + Send + Sync>>) -> io::Error {
pub fn invalid_data_error(error: impl Into<Box<dyn Error + Send + Sync>>) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, error)
}
pub(crate) fn invalid_input_error(error: impl Into<Box<dyn Error + Send + Sync>>) -> io::Error {
pub fn invalid_input_error(error: impl Into<Box<dyn Error + Send + Sync>>) -> io::Error {
io::Error::new(io::ErrorKind::InvalidInput, error)
}

@ -74,11 +74,9 @@ impl GraphFormat {
pub fn from_media_type(media_type: &str) -> Option<Self> {
if let Some(base_type) = media_type.split(';').next() {
match base_type.trim() {
"application/n-triples" | "text/plain" => Some(GraphFormat::NTriples),
"text/turtle" | "application/turtle" | "application/x-turtle" => {
Some(GraphFormat::Turtle)
}
"application/rdf+xml" | "application/xml" | "text/xml" => Some(GraphFormat::RdfXml),
"application/n-triples" | "text/plain" => Some(Self::NTriples),
"text/turtle" | "application/turtle" | "application/x-turtle" => Some(Self::Turtle),
"application/rdf+xml" | "application/xml" | "text/xml" => Some(Self::RdfXml),
_ => None,
}
} else {
@ -158,9 +156,9 @@ impl DatasetFormat {
if let Some(base_type) = media_type.split(';').next() {
match base_type.trim() {
"application/n-quads" | "text/x-nquads" | "text/nquads" => {
Some(DatasetFormat::NQuads)
Some(Self::NQuads)
}
"application/trig" | "application/x-trig" => Some(DatasetFormat::TriG),
"application/trig" | "application/x-trig" => Some(Self::TriG),
_ => None,
}
} else {

@ -66,6 +66,7 @@ impl GraphParser {
}
/// Executes the parsing itself on a [`BufRead`](std::io::BufRead) implementation and returns an iterator of triples
#[allow(clippy::unnecessary_wraps)]
pub fn read_triples<R: BufRead>(&self, reader: R) -> io::Result<TripleReader<R>> {
Ok(TripleReader {
mapper: RioMapper::default(),
@ -214,6 +215,7 @@ impl DatasetParser {
}
/// Executes the parsing itself on a [`BufRead`](std::io::BufRead) implementation and returns an iterator of quads
#[allow(clippy::unnecessary_wraps)]
pub fn read_quads<R: BufRead>(&self, reader: R) -> io::Result<QuadReader<R>> {
Ok(QuadReader {
mapper: RioMapper::default(),
@ -307,7 +309,7 @@ struct RioMapper {
}
impl<'a> RioMapper {
fn named_node(&self, node: rio::NamedNode<'a>) -> NamedNode {
fn named_node(node: rio::NamedNode<'a>) -> NamedNode {
NamedNode::new_unchecked(node.iri)
}
@ -318,21 +320,21 @@ impl<'a> RioMapper {
.clone()
}
fn literal(&self, literal: rio::Literal<'a>) -> Literal {
fn literal(literal: rio::Literal<'a>) -> Literal {
match literal {
rio::Literal::Simple { value } => Literal::new_simple_literal(value),
rio::Literal::LanguageTaggedString { value, language } => {
Literal::new_language_tagged_literal_unchecked(value, language)
}
rio::Literal::Typed { value, datatype } => {
Literal::new_typed_literal(value, self.named_node(datatype))
Literal::new_typed_literal(value, Self::named_node(datatype))
}
}
}
fn subject(&mut self, node: rio::Subject<'a>) -> Subject {
match node {
rio::Subject::NamedNode(node) => self.named_node(node).into(),
rio::Subject::NamedNode(node) => Self::named_node(node).into(),
rio::Subject::BlankNode(node) => self.blank_node(node).into(),
rio::Subject::Triple(triple) => self.triple(triple).into(),
}
@ -340,9 +342,9 @@ impl<'a> RioMapper {
fn term(&mut self, node: rio::Term<'a>) -> Term {
match node {
rio::Term::NamedNode(node) => self.named_node(node).into(),
rio::Term::NamedNode(node) => Self::named_node(node).into(),
rio::Term::BlankNode(node) => self.blank_node(node).into(),
rio::Term::Literal(literal) => self.literal(literal).into(),
rio::Term::Literal(literal) => Self::literal(literal).into(),
rio::Term::Triple(triple) => self.triple(triple).into(),
}
}
@ -350,14 +352,14 @@ impl<'a> RioMapper {
fn triple(&mut self, triple: &rio::Triple<'a>) -> Triple {
Triple {
subject: self.subject(triple.subject),
predicate: self.named_node(triple.predicate),
predicate: Self::named_node(triple.predicate),
object: self.term(triple.object),
}
}
fn graph_name(&mut self, graph_name: Option<rio::GraphName<'a>>) -> GraphName {
match graph_name {
Some(rio::GraphName::NamedNode(node)) => self.named_node(node).into(),
Some(rio::GraphName::NamedNode(node)) => Self::named_node(node).into(),
Some(rio::GraphName::BlankNode(node)) => self.blank_node(node).into(),
None => GraphName::DefaultGraph,
}
@ -366,7 +368,7 @@ impl<'a> RioMapper {
fn quad(&mut self, quad: &rio::Quad<'a>) -> Quad {
Quad {
subject: self.subject(quad.subject),
predicate: self.named_node(quad.predicate),
predicate: Self::named_node(quad.predicate),
object: self.term(quad.object),
graph_name: self.graph_name(quad.graph_name),
}

@ -183,6 +183,7 @@ impl DatasetSerializer {
}
/// Returns a `QuadWriter` allowing writing triples into the given [`Write`](std::io::Write) implementation
#[allow(clippy::unnecessary_wraps)]
pub fn quad_writer<W: Write>(&self, writer: W) -> io::Result<QuadWriter<W>> {
Ok(QuadWriter {
formatter: match self.format {
@ -250,6 +251,7 @@ impl<W: Write> QuadWriter<W> {
}
/// Writes the last bytes of the file
#[allow(clippy::unused_self, clippy::unnecessary_wraps)]
pub fn finish(self) -> io::Result<()> {
Ok(())
}

@ -46,10 +46,6 @@
)]
#![doc(html_favicon_url = "https://raw.githubusercontent.com/oxigraph/oxigraph/master/logo.svg")]
#![doc(html_logo_url = "https://raw.githubusercontent.com/oxigraph/oxigraph/master/logo.svg")]
#![allow(
clippy::multiple_crate_versions, //TODO
clippy::rc_buffer //TODO: enforce
)]
#![warn(
clippy::cast_lossless,
clippy::cast_possible_truncation,
@ -57,56 +53,119 @@
clippy::cast_precision_loss,
clippy::cast_sign_loss,
clippy::checked_conversions,
clippy::cloned_instead_of_copied,
clippy::copy_iterator,
clippy::dbg_macro,
clippy::debug_assert_with_mut_call,
clippy::decimal_literal_representation,
//TODO clippy::doc_markdown,
//clippy::else_if_without_else,
// clippy::else_if_without_else,
clippy::empty_line_after_outer_attr,
clippy::empty_enum,
clippy::enum_glob_use,
clippy::expect_used,
clippy::expl_impl_clone_on_copy,
clippy::explicit_deref_methods,
clippy::explicit_into_iter_loop,
clippy::explicit_iter_loop,
clippy::expl_impl_clone_on_copy,
clippy::fallible_impl_from,
clippy::manual_filter_map,
clippy::filter_map_next,
clippy::manual_find_map,
clippy::flat_map_option,
clippy::from_iter_instead_of_collect,
clippy::get_unwrap,
clippy::if_not_else,
// clippy::if_then_some_else_none,
clippy::implicit_clone,
clippy::implicit_saturating_sub,
clippy::imprecise_flops,
clippy::inconsistent_struct_constructor,
// clippy::indexing_slicing,
clippy::inefficient_to_string,
clippy::inline_always,
clippy::invalid_upcast_comparisons,
clippy::items_after_statements,
clippy::map_entry,
clippy::large_digit_groups,
clippy::large_stack_arrays,
clippy::large_types_passed_by_value,
clippy::let_underscore_drop,
clippy::let_underscore_must_use,
clippy::let_unit_value,
clippy::linkedlist,
clippy::macro_use_imports,
clippy::manual_ok_or,
//TODO clippy::map_err_ignore,
clippy::map_flatten,
clippy::map_unwrap_or,
//TODO clippy::match_same_arms,
clippy::match_bool,
// clippy::match_on_vec_items,
clippy::match_same_arms,
clippy::match_wildcard_for_single_variants,
clippy::maybe_infinite_iter,
clippy::mem_forget,
//TODO clippy::must_use_candidate,
//TODO clippy::missing_const_for_fn,
//TODO clippy::module_name_repetitions,
clippy::multiple_crate_versions,
clippy::multiple_inherent_impl,
//TODO clippy::must_use_candidate,
clippy::mut_mut,
clippy::needless_borrow,
clippy::mutex_integer,
clippy::naive_bytecount,
clippy::needless_bitwise_bool,
clippy::needless_continue,
clippy::needless_pass_by_value,
clippy::non_ascii_literal,
// clippy::panic, does not work well with tests
//TODO clippy::nonstandard_macro_braces,
//TODO clippy::option_if_let_else,
// clippy::panic, clippy::panic_in_result_fn, does not work well with tests
clippy::path_buf_push_overwrite,
clippy::print_stderr,
clippy::print_stdout,
clippy::range_minus_one,
clippy::range_plus_one,
//TODO clippy::rc_mutex,
//TODO clippy::redundant_closure_for_method_calls,
clippy::redundant_else,
clippy::redundant_pub_crate,
clippy::ref_binding_to_reference,
clippy::ref_option_ref,
clippy::rest_pat_in_fully_bound_structs,
clippy::same_functions_in_if_condition,
// clippy::shadow_reuse,
// clippy::shadow_same,
// clippy::shadow_unrelated,
// clippy::single_match_else,
clippy::str_to_string,
clippy::string_add,
clippy::string_add_assign,
clippy::string_lit_as_bytes,
clippy::string_to_string,
clippy::suboptimal_flops,
clippy::suspicious_operation_groupings,
clippy::todo,
clippy::trait_duplication_in_bounds,
clippy::transmute_ptr_to_ptr,
clippy::trivial_regex,
clippy::trivially_copy_pass_by_ref,
clippy::type_repetition_in_bounds,
clippy::unicode_not_nfc,
clippy::unimplemented,
clippy::unnecessary_self_imports,
clippy::unnecessary_wraps,
clippy::unneeded_field_pattern,
clippy::unnested_or_patterns,
clippy::unreadable_literal,
clippy::unseparated_literal_suffix,
clippy::unused_async,
clippy::unused_self,
clippy::use_debug,
clippy::use_self,
clippy::used_underscore_binding,
clippy::wildcard_dependencies
clippy::useless_let_if_seq,
clippy::useless_transmute,
clippy::verbose_bit_mask,
clippy::verbose_file_reads,
clippy::wildcard_dependencies,
clippy::zero_sized_map_values
)]
#![doc(test(attr(deny(warnings))))]

@ -222,13 +222,13 @@ impl Dataset {
let predicate = self
.encoded_named_node(predicate)
.unwrap_or_else(InternedNamedNode::impossible);
self.interned_quads_for_predicate(&predicate)
self.interned_quads_for_predicate(predicate)
.map(move |q| self.decode_spog(q))
}
fn interned_quads_for_predicate(
&self,
predicate: &InternedNamedNode,
predicate: InternedNamedNode,
) -> impl Iterator<
Item = (
&InternedSubject,
@ -240,7 +240,7 @@ impl Dataset {
self.posg
.range(
&(
*predicate,
predicate,
InternedTerm::first(),
InternedSubject::first(),
InternedGraphName::first(),
@ -653,7 +653,7 @@ impl Dataset {
self.interned_quads_for_subject(&InternedSubject::BlankNode(*bnode))
{
to_hash.push((
self.hash_named_node(p),
self.hash_named_node(*p),
self.hash_term(o, &hashes),
self.hash_graph_name(g, &hashes),
0,
@ -663,7 +663,7 @@ impl Dataset {
{
to_hash.push((
self.hash_subject(s, &hashes),
self.hash_named_node(p),
self.hash_named_node(*p),
self.hash_graph_name(g, &hashes),
1,
));
@ -673,13 +673,13 @@ impl Dataset {
{
to_hash.push((
self.hash_subject(s, &hashes),
self.hash_named_node(p),
self.hash_named_node(*p),
self.hash_term(o, &hashes),
2,
));
}
to_hash.sort_unstable();
let hash = self.hash_tuple((old_hash, &to_hash));
let hash = Self::hash_tuple((old_hash, &to_hash));
to_hash.clear();
new_hashes.insert(*bnode, hash);
partition.entry(hash).or_default().push(*bnode);
@ -695,8 +695,8 @@ impl Dataset {
}
}
fn hash_named_node(&self, node: &InternedNamedNode) -> u64 {
self.hash_tuple(node.decode_from(&self.interner))
fn hash_named_node(&self, node: InternedNamedNode) -> u64 {
Self::hash_tuple(node.decode_from(&self.interner))
}
fn hash_subject(
@ -709,7 +709,7 @@ impl Dataset {
} else if let InternedSubject::Triple(triple) = node {
self.hash_triple(triple, bnodes_hash)
} else {
self.hash_tuple(node.decode_from(&self.interner))
Self::hash_tuple(node.decode_from(&self.interner))
}
}
@ -719,7 +719,7 @@ impl Dataset {
} else if let InternedTerm::Triple(triple) = term {
self.hash_triple(triple, bnodes_hash)
} else {
self.hash_tuple(term.decode_from(&self.interner))
Self::hash_tuple(term.decode_from(&self.interner))
}
}
@ -731,7 +731,7 @@ impl Dataset {
if let InternedGraphName::BlankNode(bnode) = graph_name {
bnodes_hash[bnode]
} else {
self.hash_tuple(graph_name.decode_from(&self.interner))
Self::hash_tuple(graph_name.decode_from(&self.interner))
}
}
@ -740,14 +740,14 @@ impl Dataset {
triple: &InternedTriple,
bnodes_hash: &HashMap<InternedBlankNode, u64>,
) -> u64 {
self.hash_tuple((
Self::hash_tuple((
self.hash_subject(&triple.subject, bnodes_hash),
self.hash_named_node(&triple.predicate),
self.hash_named_node(triple.predicate),
self.hash_term(&triple.object, bnodes_hash),
))
}
fn hash_tuple(&self, v: impl Hash) -> u64 {
fn hash_tuple(v: impl Hash) -> u64 {
let mut hasher = DefaultHasher::new();
v.hash(&mut hasher);
hasher.finish()
@ -771,7 +771,7 @@ impl Dataset {
.iter()
.map(|b| {
let mut hash_prime = hash.clone();
hash_prime.insert(*b, self.hash_tuple((hash_prime[b], 22)));
hash_prime.insert(*b, Self::hash_tuple((hash_prime[b], 22)));
let (hash_prime_prime, partition_prime) = self.hash_bnodes(hash_prime);
self.distinguish(&hash_prime_prime, &partition_prime)
})
@ -808,7 +808,7 @@ impl Dataset {
.map(|(s, p, o, g)| {
(
if let InternedSubject::BlankNode(bnode) = s {
InternedSubject::BlankNode(self.map_bnode(&bnode, hashes))
InternedSubject::BlankNode(self.map_bnode(bnode, hashes))
} else if let InternedSubject::Triple(triple) = s {
InternedSubject::Triple(Box::new(InternedTriple::encoded_into(
self.label_triple(&triple, hashes).as_ref(),
@ -819,7 +819,7 @@ impl Dataset {
},
p,
if let InternedTerm::BlankNode(bnode) = o {
InternedTerm::BlankNode(self.map_bnode(&bnode, hashes))
InternedTerm::BlankNode(self.map_bnode(bnode, hashes))
} else if let InternedTerm::Triple(triple) = o {
InternedTerm::Triple(Box::new(InternedTriple::encoded_into(
self.label_triple(&triple, hashes).as_ref(),
@ -829,7 +829,7 @@ impl Dataset {
o
},
if let InternedGraphName::BlankNode(bnode) = g {
InternedGraphName::BlankNode(self.map_bnode(&bnode, hashes))
InternedGraphName::BlankNode(self.map_bnode(bnode, hashes))
} else {
g
},
@ -847,7 +847,7 @@ impl Dataset {
) -> Triple {
Triple {
subject: if let InternedSubject::BlankNode(bnode) = &triple.subject {
self.gen_bnode(bnode, hashes).into()
Self::gen_bnode(*bnode, hashes).into()
} else if let InternedSubject::Triple(t) = &triple.subject {
self.label_triple(t, hashes).into()
} else {
@ -855,7 +855,7 @@ impl Dataset {
},
predicate: triple.predicate.decode_from(&self.interner).into_owned(),
object: if let InternedTerm::BlankNode(bnode) = &triple.object {
self.gen_bnode(bnode, hashes).into()
Self::gen_bnode(*bnode, hashes).into()
} else if let InternedTerm::Triple(t) = &triple.object {
self.label_triple(t, hashes).into()
} else {
@ -866,21 +866,20 @@ impl Dataset {
fn map_bnode(
&mut self,
old_bnode: &InternedBlankNode,
old_bnode: InternedBlankNode,
hashes: &HashMap<InternedBlankNode, u64>,
) -> InternedBlankNode {
InternedBlankNode::encoded_into(
self.gen_bnode(old_bnode, hashes).as_ref(),
Self::gen_bnode(old_bnode, hashes).as_ref(),
&mut self.interner,
)
}
fn gen_bnode(
&self,
old_bnode: &InternedBlankNode,
old_bnode: InternedBlankNode,
hashes: &HashMap<InternedBlankNode, u64>,
) -> BlankNode {
BlankNode::new_from_unique_id(hashes[old_bnode])
BlankNode::new_from_unique_id(hashes[&old_bnode])
}
}
@ -911,7 +910,7 @@ impl<'a> IntoIterator for &'a Dataset {
impl FromIterator<Quad> for Dataset {
fn from_iter<I: IntoIterator<Item = Quad>>(iter: I) -> Self {
let mut g = Dataset::new();
let mut g = Self::new();
g.extend(iter);
g
}
@ -919,7 +918,7 @@ impl FromIterator<Quad> for Dataset {
impl<'a, T: Into<QuadRef<'a>>> FromIterator<T> for Dataset {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut g = Dataset::new();
let mut g = Self::new();
g.extend(iter);
g
}

@ -285,7 +285,7 @@ impl<'a> IntoIterator for &'a Graph {
impl FromIterator<Triple> for Graph {
fn from_iter<I: IntoIterator<Item = Triple>>(iter: I) -> Self {
let mut g = Graph::new();
let mut g = Self::new();
g.extend(iter);
g
}
@ -293,7 +293,7 @@ impl FromIterator<Triple> for Graph {
impl<'a, T: Into<TripleRef<'a>>> FromIterator<T> for Graph {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut g = Graph::new();
let mut g = Self::new();
g.extend(iter);
g
}

@ -37,7 +37,7 @@ impl InternedNamedNode {
Self { id: fist_spur() }
}
pub fn next(&self) -> Self {
pub fn next(self) -> Self {
Self {
id: next_spur(self.id),
}
@ -72,7 +72,7 @@ impl InternedBlankNode {
BlankNodeRef::new_unchecked(interner.strings.resolve(&self.id))
}
pub fn next(&self) -> Self {
pub fn next(self) -> Self {
Self {
id: next_spur(self.id),
}

@ -47,7 +47,7 @@ impl Literal {
/// Builds an RDF [simple literal](https://www.w3.org/TR/rdf11-concepts/#dfn-simple-literal)
#[inline]
pub fn new_simple_literal(value: impl Into<String>) -> Self {
Literal(LiteralContent::String(value.into()))
Self(LiteralContent::String(value.into()))
}
/// Builds an RDF [literal](https://www.w3.org/TR/rdf11-concepts/#dfn-literal) with a [datatype](https://www.w3.org/TR/rdf11-concepts/#dfn-datatype-iri)
@ -55,7 +55,7 @@ impl Literal {
pub fn new_typed_literal(value: impl Into<String>, datatype: impl Into<NamedNode>) -> Self {
let value = value.into();
let datatype = datatype.into();
Literal(if datatype == xsd::STRING {
Self(if datatype == xsd::STRING {
LiteralContent::String(value)
} else {
LiteralContent::TypedLiteral { value, datatype }
@ -88,7 +88,7 @@ impl Literal {
value: impl Into<String>,
language: impl Into<String>,
) -> Self {
Literal(LiteralContent::LanguageTaggedString {
Self(LiteralContent::LanguageTaggedString {
value: value.into(),
language: language.into(),
})
@ -164,28 +164,28 @@ impl fmt::Display for Literal {
impl<'a> From<&'a str> for Literal {
#[inline]
fn from(value: &'a str) -> Self {
Literal(LiteralContent::String(value.into()))
Self(LiteralContent::String(value.into()))
}
}
impl From<String> for Literal {
#[inline]
fn from(value: String) -> Self {
Literal(LiteralContent::String(value))
Self(LiteralContent::String(value))
}
}
impl<'a> From<Cow<'a, str>> for Literal {
#[inline]
fn from(value: Cow<'a, str>) -> Self {
Literal(LiteralContent::String(value.into()))
Self(LiteralContent::String(value.into()))
}
}
impl From<bool> for Literal {
#[inline]
fn from(value: bool) -> Self {
Literal(LiteralContent::TypedLiteral {
Self(LiteralContent::TypedLiteral {
value: value.to_string(),
datatype: xsd::BOOLEAN.into(),
})
@ -195,7 +195,7 @@ impl From<bool> for Literal {
impl From<i128> for Literal {
#[inline]
fn from(value: i128) -> Self {
Literal(LiteralContent::TypedLiteral {
Self(LiteralContent::TypedLiteral {
value: value.to_string(),
datatype: xsd::INTEGER.into(),
})
@ -205,7 +205,7 @@ impl From<i128> for Literal {
impl From<i64> for Literal {
#[inline]
fn from(value: i64) -> Self {
Literal(LiteralContent::TypedLiteral {
Self(LiteralContent::TypedLiteral {
value: value.to_string(),
datatype: xsd::INTEGER.into(),
})
@ -215,7 +215,7 @@ impl From<i64> for Literal {
impl From<i32> for Literal {
#[inline]
fn from(value: i32) -> Self {
Literal(LiteralContent::TypedLiteral {
Self(LiteralContent::TypedLiteral {
value: value.to_string(),
datatype: xsd::INTEGER.into(),
})
@ -225,7 +225,7 @@ impl From<i32> for Literal {
impl From<i16> for Literal {
#[inline]
fn from(value: i16) -> Self {
Literal(LiteralContent::TypedLiteral {
Self(LiteralContent::TypedLiteral {
value: value.to_string(),
datatype: xsd::INTEGER.into(),
})
@ -235,7 +235,7 @@ impl From<i16> for Literal {
impl From<u64> for Literal {
#[inline]
fn from(value: u64) -> Self {
Literal(LiteralContent::TypedLiteral {
Self(LiteralContent::TypedLiteral {
value: value.to_string(),
datatype: xsd::INTEGER.into(),
})
@ -245,7 +245,7 @@ impl From<u64> for Literal {
impl From<u32> for Literal {
#[inline]
fn from(value: u32) -> Self {
Literal(LiteralContent::TypedLiteral {
Self(LiteralContent::TypedLiteral {
value: value.to_string(),
datatype: xsd::INTEGER.into(),
})
@ -255,7 +255,7 @@ impl From<u32> for Literal {
impl From<u16> for Literal {
#[inline]
fn from(value: u16) -> Self {
Literal(LiteralContent::TypedLiteral {
Self(LiteralContent::TypedLiteral {
value: value.to_string(),
datatype: xsd::INTEGER.into(),
})
@ -265,7 +265,7 @@ impl From<u16> for Literal {
impl From<f32> for Literal {
#[inline]
fn from(value: f32) -> Self {
Literal(LiteralContent::TypedLiteral {
Self(LiteralContent::TypedLiteral {
value: value.to_string(),
datatype: xsd::FLOAT.into(),
})
@ -275,7 +275,7 @@ impl From<f32> for Literal {
impl From<f64> for Literal {
#[inline]
fn from(value: f64) -> Self {
Literal(LiteralContent::TypedLiteral {
Self(LiteralContent::TypedLiteral {
value: value.to_string(),
datatype: xsd::DOUBLE.into(),
})
@ -285,7 +285,7 @@ impl From<f64> for Literal {
impl From<Decimal> for Literal {
#[inline]
fn from(value: Decimal) -> Self {
Literal(LiteralContent::TypedLiteral {
Self(LiteralContent::TypedLiteral {
value: value.to_string(),
datatype: xsd::DECIMAL.into(),
})
@ -295,7 +295,7 @@ impl From<Decimal> for Literal {
impl From<DateTime> for Literal {
#[inline]
fn from(value: DateTime) -> Self {
Literal(LiteralContent::TypedLiteral {
Self(LiteralContent::TypedLiteral {
value: value.to_string(),
datatype: xsd::DATE_TIME.into(),
})
@ -305,7 +305,7 @@ impl From<DateTime> for Literal {
impl From<Time> for Literal {
#[inline]
fn from(value: Time) -> Self {
Literal(LiteralContent::TypedLiteral {
Self(LiteralContent::TypedLiteral {
value: value.to_string(),
datatype: xsd::TIME.into(),
})
@ -315,7 +315,7 @@ impl From<Time> for Literal {
impl From<Date> for Literal {
#[inline]
fn from(value: Date) -> Self {
Literal(LiteralContent::TypedLiteral {
Self(LiteralContent::TypedLiteral {
value: value.to_string(),
datatype: xsd::DATE.into(),
})
@ -325,7 +325,7 @@ impl From<Date> for Literal {
impl From<GYearMonth> for Literal {
#[inline]
fn from(value: GYearMonth) -> Self {
Literal(LiteralContent::TypedLiteral {
Self(LiteralContent::TypedLiteral {
value: value.to_string(),
datatype: xsd::G_YEAR_MONTH.into(),
})
@ -335,7 +335,7 @@ impl From<GYearMonth> for Literal {
impl From<GYear> for Literal {
#[inline]
fn from(value: GYear) -> Self {
Literal(LiteralContent::TypedLiteral {
Self(LiteralContent::TypedLiteral {
value: value.to_string(),
datatype: xsd::G_YEAR.into(),
})
@ -345,7 +345,7 @@ impl From<GYear> for Literal {
impl From<GMonthDay> for Literal {
#[inline]
fn from(value: GMonthDay) -> Self {
Literal(LiteralContent::TypedLiteral {
Self(LiteralContent::TypedLiteral {
value: value.to_string(),
datatype: xsd::G_MONTH_DAY.into(),
})
@ -355,7 +355,7 @@ impl From<GMonthDay> for Literal {
impl From<GMonth> for Literal {
#[inline]
fn from(value: GMonth) -> Self {
Literal(LiteralContent::TypedLiteral {
Self(LiteralContent::TypedLiteral {
value: value.to_string(),
datatype: xsd::G_MONTH.into(),
})
@ -365,7 +365,7 @@ impl From<GMonth> for Literal {
impl From<GDay> for Literal {
#[inline]
fn from(value: GDay) -> Self {
Literal(LiteralContent::TypedLiteral {
Self(LiteralContent::TypedLiteral {
value: value.to_string(),
datatype: xsd::G_DAY.into(),
})
@ -375,7 +375,7 @@ impl From<GDay> for Literal {
impl From<Duration> for Literal {
#[inline]
fn from(value: Duration) -> Self {
Literal(LiteralContent::TypedLiteral {
Self(LiteralContent::TypedLiteral {
value: value.to_string(),
datatype: xsd::DURATION.into(),
})
@ -385,7 +385,7 @@ impl From<Duration> for Literal {
impl From<YearMonthDuration> for Literal {
#[inline]
fn from(value: YearMonthDuration) -> Self {
Literal(LiteralContent::TypedLiteral {
Self(LiteralContent::TypedLiteral {
value: value.to_string(),
datatype: xsd::YEAR_MONTH_DURATION.into(),
})
@ -395,7 +395,7 @@ impl From<YearMonthDuration> for Literal {
impl From<DayTimeDuration> for Literal {
#[inline]
fn from(value: DayTimeDuration) -> Self {
Literal(LiteralContent::TypedLiteral {
Self(LiteralContent::TypedLiteral {
value: value.to_string(),
datatype: xsd::DAY_TIME_DURATION.into(),
})

@ -120,7 +120,7 @@ impl FromStr for Variable {
"Variable serialization should start with ? or $",
));
}
Variable::new(&s[1..]).map_err(|error| TermParseError {
Self::new(&s[1..]).map_err(|error| TermParseError {
kind: TermParseErrorKind::Variable {
value: s.to_owned(),
error,
@ -238,7 +238,7 @@ fn read_literal(s: &str) -> Result<(Literal, &str), TermParseError> {
}
let mut cursor = match input.get(0) {
Some(b'+') | Some(b'-') => 1,
Some(b'+' | b'-') => 1,
_ => 0,
};
let mut with_dot = false;
@ -262,7 +262,7 @@ fn read_literal(s: &str) -> Result<(Literal, &str), TermParseError> {
if cursor < input.len() && (input[cursor] == b'e' || input[cursor] == b'E') {
cursor += 1;
cursor += match input.get(cursor) {
Some(b'+') | Some(b'-') => 1,
Some(b'+' | b'-') => 1,
_ => 0,
};
let mut count_exponent = 0;

@ -26,7 +26,7 @@ impl TryCopyTerm for BlankNode {
T: TTerm + ?Sized,
{
match other.kind() {
TermKind::BlankNode => Ok(BlankNode::new_unchecked(other.value_raw().0)),
TermKind::BlankNode => Ok(Self::new_unchecked(other.value_raw().0)),
_ => Err(SophiaToOxigraphConversionError),
}
}
@ -52,18 +52,18 @@ impl TTerm for Literal {
}
fn value_raw(&self) -> RawValue<'_> {
Literal::value(self).into()
Self::value(self).into()
}
fn datatype(&self) -> Option<SimpleIri<'_>> {
Some(SimpleIri::new_unchecked(
Literal::datatype(self).as_str(),
Self::datatype(self).as_str(),
None,
))
}
fn language(&self) -> Option<&str> {
Literal::language(self)
Self::language(self)
}
fn as_dyn(&self) -> &dyn TTerm {
@ -80,11 +80,11 @@ impl TryCopyTerm for Literal {
{
match other.kind() {
TermKind::Literal => match other.language() {
Some(tag) => Ok(Literal::new_language_tagged_literal_unchecked(
Some(tag) => Ok(Self::new_language_tagged_literal_unchecked(
other.value_raw().0,
tag,
)),
None => Ok(Literal::new_typed_literal(
None => Ok(Self::new_typed_literal(
other.value_raw().0,
other.datatype().unwrap(),
)),
@ -141,7 +141,7 @@ impl TryCopyTerm for NamedNode {
T: TTerm + ?Sized,
{
match other.kind() {
TermKind::Iri => Ok(NamedNode::new_unchecked(other.value())),
TermKind::Iri => Ok(Self::new_unchecked(other.value())),
_ => Err(SophiaToOxigraphConversionError),
}
}
@ -149,7 +149,7 @@ impl TryCopyTerm for NamedNode {
impl<'a> From<SimpleIri<'a>> for NamedNode {
fn from(other: SimpleIri<'a>) -> Self {
NamedNode::new_unchecked(other.value())
Self::new_unchecked(other.value())
}
}
@ -169,22 +169,20 @@ impl<'a> TTerm for NamedNodeRef<'a> {
impl From<GraphName> for Option<Term> {
fn from(other: GraphName) -> Self {
use GraphName::*;
match other {
NamedNode(n) => Some(n.into()),
BlankNode(n) => Some(n.into()),
DefaultGraph => None,
GraphName::NamedNode(n) => Some(n.into()),
GraphName::BlankNode(n) => Some(n.into()),
GraphName::DefaultGraph => None,
}
}
}
impl<'a> From<GraphNameRef<'a>> for Option<TermRef<'a>> {
fn from(other: GraphNameRef<'a>) -> Self {
use GraphNameRef::*;
match other {
NamedNode(n) => Some(n.into()),
BlankNode(n) => Some(n.into()),
DefaultGraph => None,
GraphNameRef::NamedNode(n) => Some(n.into()),
GraphNameRef::BlankNode(n) => Some(n.into()),
GraphNameRef::DefaultGraph => None,
}
}
}
@ -312,7 +310,7 @@ impl TryCopyTerm for Term {
TermKind::Iri => Ok(NamedNode::try_copy(other).unwrap().into()),
TermKind::BlankNode => Ok(BlankNode::try_copy(other).unwrap().into()),
TermKind::Literal => Ok(Literal::try_copy(other).unwrap().into()),
_ => Err(SophiaToOxigraphConversionError),
TermKind::Variable => Err(SophiaToOxigraphConversionError),
}
}
}
@ -327,15 +325,6 @@ impl<'a> TTerm for TermRef<'a> {
}
}
fn value_raw(&self) -> RawValue<'_> {
match self {
Self::NamedNode(n) => n.value_raw(),
Self::BlankNode(n) => n.value_raw(),
Self::Literal(l) => l.value_raw(),
Self::Triple(_) => panic!("RDF-star is not supported yet by Sophia"),
}
}
fn datatype(&self) -> Option<SimpleIri<'_>> {
if let Self::Literal(l) = self {
TTerm::datatype(l)
@ -352,6 +341,15 @@ impl<'a> TTerm for TermRef<'a> {
}
}
fn value_raw(&self) -> RawValue<'_> {
match self {
Self::NamedNode(n) => n.value_raw(),
Self::BlankNode(n) => n.value_raw(),
Self::Literal(l) => l.value_raw(),
Self::Triple(_) => panic!("RDF-star is not supported yet by Sophia"),
}
}
fn as_dyn(&self) -> &dyn TTerm {
match self {
Self::NamedNode(n) => n.as_dyn(),

@ -856,7 +856,7 @@ impl fmt::Display for GraphName {
impl From<NamedNode> for GraphName {
#[inline]
fn from(node: NamedNode) -> Self {
GraphName::NamedNode(node)
Self::NamedNode(node)
}
}
@ -870,7 +870,7 @@ impl From<NamedNodeRef<'_>> for GraphName {
impl From<BlankNode> for GraphName {
#[inline]
fn from(node: BlankNode) -> Self {
GraphName::BlankNode(node)
Self::BlankNode(node)
}
}

@ -69,7 +69,7 @@ pub mod rdfs {
/// The class of RDF containers.
pub const CONTAINER: NamedNodeRef<'_> =
NamedNodeRef::new_unchecked("http://www.w3.org/2000/01/rdf-schema#Container");
/// The class of container membership properties, rdf:_1, rdf:_2, ..., all of which are sub-properties of 'member'.
/// The class of container membership properties, `rdf:_1`, `rdf:_2`, ..., all of which are sub-properties of `member`.
pub const CONTAINER_MEMBERSHIP_PROPERTY: NamedNodeRef<'_> = NamedNodeRef::new_unchecked(
"http://www.w3.org/2000/01/rdf-schema#ContainerMembershipProperty",
);

@ -182,7 +182,7 @@ impl TryFrom<Date> for DateTime {
type Error = DateTimeError;
fn try_from(date: Date) -> Result<Self, DateTimeError> {
DateTime::new(
Self::new(
date.year(),
date.month(),
date.day(),
@ -347,7 +347,7 @@ impl TryFrom<DateTime> for Time {
type Error = DateTimeError;
fn try_from(date_time: DateTime) -> Result<Self, DateTimeError> {
Time::new(
Self::new(
date_time.hour(),
date_time.minute(),
date_time.second(),
@ -499,7 +499,7 @@ impl TryFrom<DateTime> for Date {
type Error = DateTimeError;
fn try_from(date_time: DateTime) -> Result<Self, DateTimeError> {
Date::new(
Self::new(
date_time.year(),
date_time.month(),
date_time.day(),
@ -591,7 +591,7 @@ impl TryFrom<DateTime> for GYearMonth {
type Error = DateTimeError;
fn try_from(date_time: DateTime) -> Result<Self, DateTimeError> {
GYearMonth::new(
Self::new(
date_time.year(),
date_time.month(),
date_time.timezone_offset(),
@ -604,7 +604,7 @@ impl TryFrom<Date> for GYearMonth {
type Error = DateTimeError;
fn try_from(date: Date) -> Result<Self, DateTimeError> {
GYearMonth::new(date.year(), date.month(), date.timezone_offset())
Self::new(date.year(), date.month(), date.timezone_offset())
}
}
@ -686,7 +686,7 @@ impl TryFrom<DateTime> for GYear {
type Error = DateTimeError;
fn try_from(date_time: DateTime) -> Result<Self, DateTimeError> {
GYear::new(date_time.year(), date_time.timezone_offset())
Self::new(date_time.year(), date_time.timezone_offset())
}
}
@ -695,7 +695,7 @@ impl TryFrom<Date> for GYear {
type Error = DateTimeError;
fn try_from(date: Date) -> Result<Self, DateTimeError> {
GYear::new(date.year(), date.timezone_offset())
Self::new(date.year(), date.timezone_offset())
}
}
@ -703,7 +703,7 @@ impl TryFrom<GYearMonth> for GYear {
type Error = DateTimeError;
fn try_from(year_month: GYearMonth) -> Result<Self, DateTimeError> {
GYear::new(year_month.year(), year_month.timezone_offset())
Self::new(year_month.year(), year_month.timezone_offset())
}
}
@ -790,7 +790,7 @@ impl TryFrom<DateTime> for GMonthDay {
type Error = DateTimeError;
fn try_from(date_time: DateTime) -> Result<Self, DateTimeError> {
GMonthDay::new(
Self::new(
date_time.month(),
date_time.day(),
date_time.timezone_offset(),
@ -803,7 +803,7 @@ impl TryFrom<Date> for GMonthDay {
type Error = DateTimeError;
fn try_from(date: Date) -> Result<Self, DateTimeError> {
GMonthDay::new(date.month(), date.day(), date.timezone_offset())
Self::new(date.month(), date.day(), date.timezone_offset())
}
}
@ -881,7 +881,7 @@ impl TryFrom<DateTime> for GMonth {
type Error = DateTimeError;
fn try_from(date_time: DateTime) -> Result<Self, DateTimeError> {
GMonth::new(date_time.month(), date_time.timezone_offset())
Self::new(date_time.month(), date_time.timezone_offset())
}
}
@ -890,7 +890,7 @@ impl TryFrom<Date> for GMonth {
type Error = DateTimeError;
fn try_from(date: Date) -> Result<Self, DateTimeError> {
GMonth::new(date.month(), date.timezone_offset())
Self::new(date.month(), date.timezone_offset())
}
}
@ -898,7 +898,7 @@ impl TryFrom<GYearMonth> for GMonth {
type Error = DateTimeError;
fn try_from(year_month: GYearMonth) -> Result<Self, DateTimeError> {
GMonth::new(year_month.month(), year_month.timezone_offset())
Self::new(year_month.month(), year_month.timezone_offset())
}
}
@ -906,7 +906,7 @@ impl TryFrom<GMonthDay> for GMonth {
type Error = DateTimeError;
fn try_from(month_day: GMonthDay) -> Result<Self, DateTimeError> {
GMonth::new(month_day.month(), month_day.timezone_offset())
Self::new(month_day.month(), month_day.timezone_offset())
}
}
@ -984,7 +984,7 @@ impl TryFrom<DateTime> for GDay {
type Error = DateTimeError;
fn try_from(date_time: DateTime) -> Result<Self, DateTimeError> {
GDay::new(date_time.day(), date_time.timezone_offset())
Self::new(date_time.day(), date_time.timezone_offset())
}
}
@ -993,7 +993,7 @@ impl TryFrom<Date> for GDay {
type Error = DateTimeError;
fn try_from(date: Date) -> Result<Self, DateTimeError> {
GDay::new(date.day(), date.timezone_offset())
Self::new(date.day(), date.timezone_offset())
}
}
@ -1001,7 +1001,7 @@ impl TryFrom<GMonthDay> for GDay {
type Error = DateTimeError;
fn try_from(month_day: GMonthDay) -> Result<Self, DateTimeError> {
GDay::new(month_day.day(), month_day.timezone_offset())
Self::new(month_day.day(), month_day.timezone_offset())
}
}
@ -1039,7 +1039,7 @@ impl TimezoneOffset {
}
pub fn from_be_bytes(bytes: [u8; 2]) -> Self {
TimezoneOffset {
Self {
offset: i16::from_be_bytes(bytes),
}
}
@ -1051,13 +1051,13 @@ impl TimezoneOffset {
impl From<i16> for TimezoneOffset {
fn from(offset: i16) -> Self {
TimezoneOffset { offset }
Self { offset }
}
}
impl From<TimezoneOffset> for DayTimeDuration {
fn from(value: TimezoneOffset) -> Self {
DayTimeDuration::new(i32::from(value.offset) * 60)
Self::new(i32::from(value.offset) * 60)
}
}
@ -1163,7 +1163,7 @@ impl Timestamp {
}
fn now() -> Result<Self, DateTimeError> {
Timestamp::new(
Self::new(
&date_time_plus_duration(
since_unix_epoch()?,
&DateTimeSevenPropertyModel {
@ -1311,7 +1311,7 @@ impl Timestamp {
})
}
fn checked_sub(&self, rhs: Timestamp) -> Option<Duration> {
fn checked_sub(&self, rhs: Self) -> Option<Duration> {
match (self.timezone_offset, rhs.timezone_offset) {
(Some(_), Some(_)) | (None, None) => {
Some(Duration::new(0, self.value.checked_sub(rhs.value)?))

@ -99,7 +99,7 @@ impl Decimal {
/// [fn:abs](https://www.w3.org/TR/xpath-functions/#func-abs)
#[inline]
pub const fn abs(&self) -> Decimal {
pub const fn abs(&self) -> Self {
Self {
value: self.value.abs(),
}
@ -107,7 +107,7 @@ impl Decimal {
/// [fn:round](https://www.w3.org/TR/xpath-functions/#func-round)
#[inline]
pub fn round(&self) -> Decimal {
pub fn round(&self) -> Self {
let value = self.value / DECIMAL_PART_POW_MINUS_ONE;
Self {
value: if value >= 0 {
@ -120,7 +120,7 @@ impl Decimal {
/// [fn:ceiling](https://www.w3.org/TR/xpath-functions/#func-ceiling)
#[inline]
pub fn ceil(&self) -> Decimal {
pub fn ceil(&self) -> Self {
Self {
value: if self.value >= 0 && self.value % DECIMAL_PART_POW != 0 {
(self.value / DECIMAL_PART_POW + 1) * DECIMAL_PART_POW
@ -132,7 +132,7 @@ impl Decimal {
/// [fn:floor](https://www.w3.org/TR/xpath-functions/#func-floor)
#[inline]
pub fn floor(&self) -> Decimal {
pub fn floor(&self) -> Self {
Self {
value: if self.value >= 0 || self.value % DECIMAL_PART_POW == 0 {
(self.value / DECIMAL_PART_POW) * DECIMAL_PART_POW
@ -184,21 +184,21 @@ impl Decimal {
}
#[cfg(test)]
pub(super) const fn min_value() -> Decimal {
pub(super) const fn min_value() -> Self {
Self {
value: i128::min_value(),
}
}
#[cfg(test)]
pub(super) const fn max_value() -> Decimal {
pub(super) const fn max_value() -> Self {
Self {
value: i128::max_value(),
}
}
#[cfg(test)]
pub(super) const fn step() -> Decimal {
pub(super) const fn step() -> Self {
Self { value: 1 }
}
}
@ -445,7 +445,7 @@ impl fmt::Display for Decimal {
let last_non_zero = i - 1;
let first_non_zero = digits
.iter()
.cloned()
.copied()
.enumerate()
.find_map(|(i, v)| if v == b'0' { None } else { Some(i) })
.unwrap_or(40);
@ -503,7 +503,7 @@ impl Neg for Decimal {
impl TryFrom<Decimal> for i64 {
type Error = DecimalOverflowError;
fn try_from(value: Decimal) -> Result<i64, DecimalOverflowError> {
fn try_from(value: Decimal) -> Result<Self, DecimalOverflowError> {
value
.value
.checked_div(DECIMAL_PART_POW)

@ -240,36 +240,40 @@ impl YearMonthDuration {
}
/// [fn:years-from-duration](https://www.w3.org/TR/xpath-functions/#func-years-from-duration)
pub fn years(&self) -> i64 {
pub fn years(self) -> i64 {
self.months / 12
}
/// [fn:months-from-duration](https://www.w3.org/TR/xpath-functions/#func-months-from-duration)
pub fn months(&self) -> i64 {
pub fn months(self) -> i64 {
self.months % 12
}
/// [fn:days-from-duration](https://www.w3.org/TR/xpath-functions/#func-days-from-duration)
pub fn days(&self) -> i64 {
#[allow(clippy::unused_self)]
pub fn days(self) -> i64 {
0
}
/// [fn:hours-from-duration](https://www.w3.org/TR/xpath-functions/#func-hours-from-duration)
pub fn hours(&self) -> i64 {
#[allow(clippy::unused_self)]
pub fn hours(self) -> i64 {
0
}
/// [fn:minutes-from-duration](https://www.w3.org/TR/xpath-functions/#func-minutes-from-duration)
pub fn minutes(&self) -> i64 {
#[allow(clippy::unused_self)]
pub fn minutes(self) -> i64 {
0
}
/// [fn:seconds-from-duration](https://www.w3.org/TR/xpath-functions/#func-seconds-from-duration)
pub fn seconds(&self) -> Decimal {
#[allow(clippy::unused_self)]
pub fn seconds(self) -> Decimal {
Decimal::default()
}
pub(super) const fn all_months(&self) -> i64 {
pub(super) const fn all_months(self) -> i64 {
self.months
}
@ -278,7 +282,7 @@ impl YearMonthDuration {
}
/// [op:add-yearMonthDurations](https://www.w3.org/TR/xpath-functions/#func-add-yearMonthDurations)
pub fn checked_add(&self, rhs: impl Into<Self>) -> Option<Self> {
pub fn checked_add(self, rhs: impl Into<Self>) -> Option<Self> {
let rhs = rhs.into();
Some(Self {
months: self.months.checked_add(rhs.months)?,
@ -286,7 +290,7 @@ impl YearMonthDuration {
}
/// [op:subtract-yearMonthDurations](https://www.w3.org/TR/xpath-functions/#func-subtract-yearMonthDurations)
pub fn checked_sub(&self, rhs: impl Into<Self>) -> Option<Self> {
pub fn checked_sub(self, rhs: impl Into<Self>) -> Option<Self> {
let rhs = rhs.into();
Some(Self {
months: self.months.checked_sub(rhs.months)?,
@ -341,7 +345,7 @@ impl PartialEq<Duration> for YearMonthDuration {
impl PartialEq<YearMonthDuration> for Duration {
fn eq(&self, other: &YearMonthDuration) -> bool {
self.eq(&Duration::from(*other))
self.eq(&Self::from(*other))
}
}
@ -353,7 +357,7 @@ impl PartialOrd<Duration> for YearMonthDuration {
impl PartialOrd<YearMonthDuration> for Duration {
fn partial_cmp(&self, other: &YearMonthDuration) -> Option<Ordering> {
self.partial_cmp(&Duration::from(*other))
self.partial_cmp(&Self::from(*other))
}
}
@ -389,11 +393,13 @@ impl DayTimeDuration {
}
/// [fn:years-from-duration](https://www.w3.org/TR/xpath-functions/#func-years-from-duration)
#[allow(clippy::unused_self)]
pub fn years(&self) -> i64 {
0
}
/// [fn:months-from-duration](https://www.w3.org/TR/xpath-functions/#func-months-from-duration)
#[allow(clippy::unused_self)]
pub fn months(&self) -> i64 {
0
}
@ -502,7 +508,7 @@ impl PartialEq<Duration> for DayTimeDuration {
impl PartialEq<DayTimeDuration> for Duration {
fn eq(&self, other: &DayTimeDuration) -> bool {
self.eq(&Duration::from(*other))
self.eq(&Self::from(*other))
}
}
@ -526,7 +532,7 @@ impl PartialOrd<Duration> for DayTimeDuration {
impl PartialOrd<DayTimeDuration> for Duration {
fn partial_cmp(&self, other: &DayTimeDuration) -> Option<Ordering> {
self.partial_cmp(&Duration::from(*other))
self.partial_cmp(&Self::from(*other))
}
}

@ -106,7 +106,7 @@ impl ParseError<&str> for XsdParseError {
impl From<ParseIntError> for XsdParseError {
fn from(error: ParseIntError) -> Self {
XsdParseError {
Self {
kind: XsdParseErrorKind::ParseInt(error),
}
}
@ -114,7 +114,7 @@ impl From<ParseIntError> for XsdParseError {
impl From<ParseDecimalError> for XsdParseError {
fn from(error: ParseDecimalError) -> Self {
XsdParseError {
Self {
kind: XsdParseErrorKind::ParseDecimal(error),
}
}
@ -122,16 +122,16 @@ impl From<ParseDecimalError> for XsdParseError {
impl From<DateTimeError> for XsdParseError {
fn from(error: DateTimeError) -> Self {
XsdParseError {
Self {
kind: XsdParseErrorKind::DateTime(error),
}
}
}
impl From<Err<XsdParseError>> for XsdParseError {
fn from(err: Err<XsdParseError>) -> Self {
impl From<Err<Self>> for XsdParseError {
fn from(err: Err<Self>) -> Self {
match err {
Err::Incomplete(needed) => XsdParseError {
Err::Incomplete(needed) => Self {
kind: XsdParseErrorKind::MissingData(needed),
},
Err::Error(e) | Err::Failure(e) => e,

@ -6,7 +6,7 @@ use crate::model::{
use crate::sparql::{EvaluationError, QueryResults};
use crate::store::Store;
use sophia_api::dataset::{
CollectibleDataset, DQuadSource, DResultTermSet, DTerm, Dataset, MDResult, MutableDataset,
CollectibleDataset, DQuadSource, DResultTermSet, DTerm, Dataset, MdResult, MutableDataset,
};
use sophia_api::quad::stream::{QuadSource, StreamResult};
use sophia_api::quad::streaming_mode::{ByValue, StreamedQuad};
@ -380,7 +380,7 @@ impl MutableDataset for Store {
p: &TP,
o: &TO,
g: Option<&TG>,
) -> MDResult<Self, bool>
) -> MdResult<Self, bool>
where
TS: TTerm + ?Sized,
TP: TTerm + ?Sized,
@ -396,7 +396,7 @@ impl MutableDataset for Store {
Some(quad) => quad,
None => return Ok(false),
};
Store::insert(self, quadref).map(|_| true)
Self::insert(self, quadref).map(|_| true)
}
fn remove<TS, TP, TO, TG>(
@ -405,7 +405,7 @@ impl MutableDataset for Store {
p: &TP,
o: &TO,
g: Option<&TG>,
) -> MDResult<Self, bool>
) -> MdResult<Self, bool>
where
TS: TTerm + ?Sized,
TP: TTerm + ?Sized,
@ -421,13 +421,13 @@ impl MutableDataset for Store {
Some(quad) => quad,
None => return Ok(false),
};
Store::remove(self, quadref).map(|_| true)
Self::remove(self, quadref).map(|_| true)
}
}
impl CollectibleDataset for Store {
fn from_quad_source<QS: QuadSource>(quads: QS) -> StreamResult<Self, QS::Error, Self::Error> {
let mut d = Store::new().map_err(sophia_api::quad::stream::StreamError::SinkError)?;
let mut d = Self::new().map_err(sophia_api::quad::stream::StreamError::SinkError)?;
d.insert_all(quads)?;
Ok(d)
}
@ -488,7 +488,7 @@ where
};
Some(lit.into())
}
_ => None,
TermKind::Variable => None,
}
}
@ -569,7 +569,7 @@ where
Some(QuadRef::new(s, p, o, g))
}
/// Execute a SPARQL query in a store, and return the result as a HashSet,
/// Execute a SPARQL query in a store, and return the result as a `HashSet`,
/// mapping the error (if any) through the given function.
///
/// # Precondition

@ -39,10 +39,10 @@ impl Query {
let query = spargebra::Query::parse(query, base_iri)?;
Ok(Self {
dataset: QueryDataset::from_algebra(match &query {
spargebra::Query::Select { dataset, .. } => dataset,
spargebra::Query::Construct { dataset, .. } => dataset,
spargebra::Query::Describe { dataset, .. } => dataset,
spargebra::Query::Ask { dataset, .. } => dataset,
spargebra::Query::Select { dataset, .. }
| spargebra::Query::Construct { dataset, .. }
| spargebra::Query::Describe { dataset, .. }
| spargebra::Query::Ask { dataset, .. } => dataset,
}),
inner: query,
})
@ -128,12 +128,16 @@ impl Update {
/// Returns [the query dataset specification](https://www.w3.org/TR/sparql11-query/#specifyingDataset) in [DELETE/INSERT operations](https://www.w3.org/TR/sparql11-update/#deleteInsert).
pub fn using_datasets(&self) -> impl Iterator<Item = &QueryDataset> {
self.using_datasets.iter().filter_map(|q| q.as_ref())
self.using_datasets
.iter()
.filter_map(std::option::Option::as_ref)
}
/// Returns [the query dataset specification](https://www.w3.org/TR/sparql11-query/#specifyingDataset) in [DELETE/INSERT operations](https://www.w3.org/TR/sparql11-update/#deleteInsert).
pub fn using_datasets_mut(&mut self) -> impl Iterator<Item = &mut QueryDataset> {
self.using_datasets.iter_mut().filter_map(|q| q.as_mut())
self.using_datasets
.iter_mut()
.filter_map(std::option::Option::as_mut)
}
}

@ -10,14 +10,14 @@ use std::collections::HashMap;
use std::convert::Infallible;
use std::iter::empty;
pub(crate) struct DatasetView {
pub struct DatasetView {
storage: Storage,
extra: RefCell<HashMap<StrHash, String>>,
dataset: EncodedDatasetSpec,
}
impl DatasetView {
pub fn new(storage: Storage, dataset: &QueryDataset) -> Result<Self, EvaluationError> {
pub fn new(storage: Storage, dataset: &QueryDataset) -> Self {
let dataset = EncodedDatasetSpec {
default: dataset
.default_graph_graphs()
@ -26,11 +26,11 @@ impl DatasetView {
.available_named_graphs()
.map(|graphs| graphs.iter().map(|g| g.as_ref().into()).collect::<Vec<_>>()),
};
Ok(Self {
Self {
storage,
extra: RefCell::new(HashMap::default()),
dataset,
})
}
}
fn store_encoded_quads_for_pattern(

@ -106,7 +106,7 @@ impl From<io::Error> for EvaluationError {
}
}
impl<E: Into<EvaluationError>> From<DecoderError<E>> for EvaluationError {
impl<E: Into<Self>> From<DecoderError<E>> for EvaluationError {
fn from(error: DecoderError<E>) -> Self {
match error {
DecoderError::Store(error) => error.into(),

@ -33,7 +33,7 @@ const REGEX_SIZE_LIMIT: usize = 1_000_000;
type EncodedTuplesIterator = Box<dyn Iterator<Item = Result<EncodedTuple, EvaluationError>>>;
#[derive(Clone)]
pub(crate) struct SimpleEvaluator {
pub struct SimpleEvaluator {
dataset: Rc<DatasetView>,
base_iri: Option<Rc<Iri<String>>>,
now: DateTime,
@ -58,11 +58,9 @@ impl SimpleEvaluator {
&self,
plan: &PlanNode,
variables: Rc<Vec<Variable>>,
) -> Result<QueryResults, EvaluationError> {
) -> QueryResults {
let iter = self.eval_plan(plan, EncodedTuple::with_capacity(variables.len()));
Ok(QueryResults::Solutions(
self.decode_bindings(iter, variables),
))
QueryResults::Solutions(self.decode_bindings(iter, variables))
}
pub fn evaluate_ask_plan(&self, plan: &PlanNode) -> Result<QueryResults, EvaluationError> {
@ -78,9 +76,9 @@ impl SimpleEvaluator {
&self,
plan: &PlanNode,
template: Vec<TripleTemplate>,
) -> Result<QueryResults, EvaluationError> {
) -> QueryResults {
let from = EncodedTuple::with_capacity(plan.maybe_bound_variables().len());
Ok(QueryResults::Graph(QueryTripleIter {
QueryResults::Graph(QueryTripleIter {
iter: Box::new(ConstructIterator {
eval: self.clone(),
iter: self.eval_plan(plan, from),
@ -88,18 +86,18 @@ impl SimpleEvaluator {
buffered_results: Vec::default(),
bnodes: Vec::default(),
}),
}))
})
}
pub fn evaluate_describe_plan(&self, plan: &PlanNode) -> Result<QueryResults, EvaluationError> {
pub fn evaluate_describe_plan(&self, plan: &PlanNode) -> QueryResults {
let from = EncodedTuple::with_capacity(plan.maybe_bound_variables().len());
Ok(QueryResults::Graph(QueryTripleIter {
QueryResults::Graph(QueryTripleIter {
iter: Box::new(DescribeIterator {
eval: self.clone(),
iter: self.eval_plan(plan, from),
quads: Box::new(empty()),
}),
}))
})
}
pub fn eval_plan(&self, node: &PlanNode, from: EncodedTuple) -> EncodedTuplesIterator {
@ -114,7 +112,7 @@ impl SimpleEvaluator {
..
} => {
match self.evaluate_service(service_name, graph_pattern, variables.clone(), &from) {
Ok(result) => Box::new(result.flat_map(move |binding| {
Ok(result) => Box::new(result.filter_map(move |binding| {
binding
.map(|binding| binding.combine_with(&from))
.transpose()
@ -274,7 +272,7 @@ impl SimpleEvaluator {
//TODO: dumb implementation
let right: Vec<_> = self
.eval_plan(right, from.clone())
.filter_map(|result| result.ok())
.filter_map(std::result::Result::ok)
.collect();
Box::new(AntiJoinIterator {
left_iter: self.eval_plan(left, from),
@ -986,17 +984,19 @@ impl SimpleEvaluator {
PlanExpression::Not(e) => self
.to_bool(&self.eval_expression(e, tuple)?)
.map(|v| (!v).into()),
PlanExpression::Str(e) => Some(self.build_string_literal_from_id(
self.to_string_id(&self.eval_expression(e, tuple)?)?,
)),
PlanExpression::Str(e) | PlanExpression::StringCast(e) => {
Some(Self::build_string_literal_from_id(
self.to_string_id(&self.eval_expression(e, tuple)?)?,
))
}
PlanExpression::Lang(e) => match self.eval_expression(e, tuple)? {
EncodedTerm::SmallSmallLangStringLiteral { language, .. }
| EncodedTerm::BigSmallLangStringLiteral { language, .. } => {
Some(self.build_string_literal_from_id(language.into()))
Some(Self::build_string_literal_from_id(language.into()))
}
EncodedTerm::SmallBigLangStringLiteral { language_id, .. }
| EncodedTerm::BigBigLangStringLiteral { language_id, .. } => {
Some(self.build_string_literal_from_id(language_id.into()))
Some(Self::build_string_literal_from_id(language_id.into()))
}
e if e.is_literal() => Some(self.build_string_literal("")),
_ => None,
@ -1129,7 +1129,7 @@ impl SimpleEvaluator {
.char_indices()
.skip(starting_location.checked_sub(1)?)
.peekable();
let result = if let Some((start_position, _)) = start_iter.peek().cloned() {
let result = if let Some((start_position, _)) = start_iter.peek().copied() {
if let Some(length) = length {
let mut end_iter = start_iter.skip(length).peekable();
if let Some((end_position, _)) = end_iter.peek() {
@ -1355,8 +1355,8 @@ impl SimpleEvaluator {
}
}
PlanExpression::StrLang(lexical_form, lang_tag) => {
Some(self.build_lang_string_literal_from_id(
self.to_simple_string_id(&self.eval_expression(lexical_form, tuple)?)?,
Some(Self::build_lang_string_literal_from_id(
Self::to_simple_string_id(&self.eval_expression(lexical_form, tuple)?)?,
self.build_language_id(&self.eval_expression(lang_tag, tuple)?)?,
))
}
@ -1569,9 +1569,6 @@ impl SimpleEvaluator {
}
_ => None,
},
PlanExpression::StringCast(e) => Some(self.build_string_literal_from_id(
self.to_string_id(&self.eval_expression(e, tuple)?)?,
)),
}
}
@ -1592,9 +1589,9 @@ impl SimpleEvaluator {
fn to_string_id(&self, term: &EncodedTerm) -> Option<SmallStringOrId> {
match term {
EncodedTerm::DefaultGraph => None,
EncodedTerm::NamedNode { iri_id } => Some((*iri_id).into()),
EncodedTerm::NumericalBlankNode { .. }
EncodedTerm::DefaultGraph
| EncodedTerm::NumericalBlankNode { .. }
| EncodedTerm::SmallBlankNode { .. }
| EncodedTerm::BigBlankNode { .. }
| EncodedTerm::Triple(_) => None,
@ -1639,7 +1636,7 @@ impl SimpleEvaluator {
}
}
fn to_simple_string_id(&self, term: &EncodedTerm) -> Option<SmallStringOrId> {
fn to_simple_string_id(term: &EncodedTerm) -> Option<SmallStringOrId> {
match term {
EncodedTerm::SmallStringLiteral(value) => Some((*value).into()),
EncodedTerm::BigStringLiteral { value_id } => Some((*value_id).into()),
@ -1700,10 +1697,10 @@ impl SimpleEvaluator {
}
fn build_string_literal(&self, value: &str) -> EncodedTerm {
self.build_string_literal_from_id(self.build_string_id(value))
Self::build_string_literal_from_id(self.build_string_id(value))
}
fn build_string_literal_from_id(&self, id: SmallStringOrId) -> EncodedTerm {
fn build_string_literal_from_id(id: SmallStringOrId) -> EncodedTerm {
match id {
SmallStringOrId::Small(value) => EncodedTerm::SmallStringLiteral(value),
SmallStringOrId::Big(value_id) => EncodedTerm::BigStringLiteral { value_id },
@ -1711,11 +1708,10 @@ impl SimpleEvaluator {
}
fn build_lang_string_literal(&self, value: &str, language_id: SmallStringOrId) -> EncodedTerm {
self.build_lang_string_literal_from_id(self.build_string_id(value), language_id)
Self::build_lang_string_literal_from_id(self.build_string_id(value), language_id)
}
fn build_lang_string_literal_from_id(
&self,
value_id: SmallStringOrId,
language_id: SmallStringOrId,
) -> EncodedTerm {
@ -1797,8 +1793,7 @@ impl SimpleEvaluator {
'x' => {
regex_builder.ignore_whitespace(true);
}
'q' => (), //TODO: implement
_ => (),
_ => (), //TODO: implement q
}
}
}
@ -2311,115 +2306,115 @@ impl NumericBinaryOperands {
fn new(a: &EncodedTerm, b: &EncodedTerm) -> Option<Self> {
match (a, b) {
(EncodedTerm::FloatLiteral(v1), EncodedTerm::FloatLiteral(v2)) => {
Some(NumericBinaryOperands::Float(*v1, *v2))
Some(Self::Float(*v1, *v2))
}
(EncodedTerm::FloatLiteral(v1), EncodedTerm::DoubleLiteral(v2)) => {
Some(NumericBinaryOperands::Double((*v1).into(), *v2))
Some(Self::Double((*v1).into(), *v2))
}
(EncodedTerm::FloatLiteral(v1), EncodedTerm::IntegerLiteral(v2)) => {
Some(NumericBinaryOperands::Float(*v1, *v2 as f32))
Some(Self::Float(*v1, *v2 as f32))
}
(EncodedTerm::FloatLiteral(v1), EncodedTerm::DecimalLiteral(v2)) => {
Some(NumericBinaryOperands::Float(*v1, v2.to_f32()))
Some(Self::Float(*v1, v2.to_f32()))
}
(EncodedTerm::DoubleLiteral(v1), EncodedTerm::FloatLiteral(v2)) => {
Some(NumericBinaryOperands::Double(*v1, (*v2).into()))
Some(Self::Double(*v1, (*v2).into()))
}
(EncodedTerm::DoubleLiteral(v1), EncodedTerm::DoubleLiteral(v2)) => {
Some(NumericBinaryOperands::Double(*v1, *v2))
Some(Self::Double(*v1, *v2))
}
(EncodedTerm::DoubleLiteral(v1), EncodedTerm::IntegerLiteral(v2)) => {
Some(NumericBinaryOperands::Double(*v1, *v2 as f64))
Some(Self::Double(*v1, *v2 as f64))
}
(EncodedTerm::DoubleLiteral(v1), EncodedTerm::DecimalLiteral(v2)) => {
Some(NumericBinaryOperands::Double(*v1, v2.to_f64()))
Some(Self::Double(*v1, v2.to_f64()))
}
(EncodedTerm::IntegerLiteral(v1), EncodedTerm::FloatLiteral(v2)) => {
Some(NumericBinaryOperands::Float(*v1 as f32, *v2))
Some(Self::Float(*v1 as f32, *v2))
}
(EncodedTerm::IntegerLiteral(v1), EncodedTerm::DoubleLiteral(v2)) => {
Some(NumericBinaryOperands::Double(*v1 as f64, *v2))
Some(Self::Double(*v1 as f64, *v2))
}
(EncodedTerm::IntegerLiteral(v1), EncodedTerm::IntegerLiteral(v2)) => {
Some(NumericBinaryOperands::Integer(*v1, *v2))
Some(Self::Integer(*v1, *v2))
}
(EncodedTerm::IntegerLiteral(v1), EncodedTerm::DecimalLiteral(v2)) => {
Some(NumericBinaryOperands::Decimal(Decimal::from(*v1), *v2))
Some(Self::Decimal(Decimal::from(*v1), *v2))
}
(EncodedTerm::DecimalLiteral(v1), EncodedTerm::FloatLiteral(v2)) => {
Some(NumericBinaryOperands::Float(v1.to_f32(), *v2))
Some(Self::Float(v1.to_f32(), *v2))
}
(EncodedTerm::DecimalLiteral(v1), EncodedTerm::DoubleLiteral(v2)) => {
Some(NumericBinaryOperands::Double(v1.to_f64(), *v2))
Some(Self::Double(v1.to_f64(), *v2))
}
(EncodedTerm::DecimalLiteral(v1), EncodedTerm::IntegerLiteral(v2)) => {
Some(NumericBinaryOperands::Decimal(*v1, Decimal::from(*v2)))
Some(Self::Decimal(*v1, Decimal::from(*v2)))
}
(EncodedTerm::DecimalLiteral(v1), EncodedTerm::DecimalLiteral(v2)) => {
Some(NumericBinaryOperands::Decimal(*v1, *v2))
Some(Self::Decimal(*v1, *v2))
}
(EncodedTerm::DurationLiteral(v1), EncodedTerm::DurationLiteral(v2)) => {
Some(NumericBinaryOperands::Duration(*v1, *v2))
Some(Self::Duration(*v1, *v2))
}
(EncodedTerm::DurationLiteral(v1), EncodedTerm::YearMonthDurationLiteral(v2)) => {
Some(NumericBinaryOperands::Duration(*v1, (*v2).into()))
Some(Self::Duration(*v1, (*v2).into()))
}
(EncodedTerm::DurationLiteral(v1), EncodedTerm::DayTimeDurationLiteral(v2)) => {
Some(NumericBinaryOperands::Duration(*v1, (*v2).into()))
Some(Self::Duration(*v1, (*v2).into()))
}
(EncodedTerm::YearMonthDurationLiteral(v1), EncodedTerm::DurationLiteral(v2)) => {
Some(NumericBinaryOperands::Duration((*v1).into(), *v2))
Some(Self::Duration((*v1).into(), *v2))
}
(
EncodedTerm::YearMonthDurationLiteral(v1),
EncodedTerm::YearMonthDurationLiteral(v2),
) => Some(NumericBinaryOperands::YearMonthDuration(*v1, *v2)),
) => Some(Self::YearMonthDuration(*v1, *v2)),
(
EncodedTerm::YearMonthDurationLiteral(v1),
EncodedTerm::DayTimeDurationLiteral(v2),
) => Some(NumericBinaryOperands::Duration((*v1).into(), (*v2).into())),
) => Some(Self::Duration((*v1).into(), (*v2).into())),
(EncodedTerm::DayTimeDurationLiteral(v1), EncodedTerm::DurationLiteral(v2)) => {
Some(NumericBinaryOperands::Duration((*v1).into(), *v2))
Some(Self::Duration((*v1).into(), *v2))
}
(
EncodedTerm::DayTimeDurationLiteral(v1),
EncodedTerm::YearMonthDurationLiteral(v2),
) => Some(NumericBinaryOperands::Duration((*v1).into(), (*v2).into())),
) => Some(Self::Duration((*v1).into(), (*v2).into())),
(EncodedTerm::DayTimeDurationLiteral(v1), EncodedTerm::DayTimeDurationLiteral(v2)) => {
Some(NumericBinaryOperands::DayTimeDuration(*v1, *v2))
Some(Self::DayTimeDuration(*v1, *v2))
}
(EncodedTerm::DateTimeLiteral(v1), EncodedTerm::DateTimeLiteral(v2)) => {
Some(NumericBinaryOperands::DateTime(*v1, *v2))
Some(Self::DateTime(*v1, *v2))
}
(EncodedTerm::DateLiteral(v1), EncodedTerm::DateLiteral(v2)) => {
Some(NumericBinaryOperands::Date(*v1, *v2))
Some(Self::Date(*v1, *v2))
}
(EncodedTerm::TimeLiteral(v1), EncodedTerm::TimeLiteral(v2)) => {
Some(NumericBinaryOperands::Time(*v1, *v2))
Some(Self::Time(*v1, *v2))
}
(EncodedTerm::DateTimeLiteral(v1), EncodedTerm::DurationLiteral(v2)) => {
Some(NumericBinaryOperands::DateTimeDuration(*v1, *v2))
Some(Self::DateTimeDuration(*v1, *v2))
}
(EncodedTerm::DateTimeLiteral(v1), EncodedTerm::YearMonthDurationLiteral(v2)) => {
Some(NumericBinaryOperands::DateTimeYearMonthDuration(*v1, *v2))
Some(Self::DateTimeYearMonthDuration(*v1, *v2))
}
(EncodedTerm::DateTimeLiteral(v1), EncodedTerm::DayTimeDurationLiteral(v2)) => {
Some(NumericBinaryOperands::DateTimeDayTimeDuration(*v1, *v2))
Some(Self::DateTimeDayTimeDuration(*v1, *v2))
}
(EncodedTerm::DateLiteral(v1), EncodedTerm::DurationLiteral(v2)) => {
Some(NumericBinaryOperands::DateDuration(*v1, *v2))
Some(Self::DateDuration(*v1, *v2))
}
(EncodedTerm::DateLiteral(v1), EncodedTerm::YearMonthDurationLiteral(v2)) => {
Some(NumericBinaryOperands::DateYearMonthDuration(*v1, *v2))
Some(Self::DateYearMonthDuration(*v1, *v2))
}
(EncodedTerm::DateLiteral(v1), EncodedTerm::DayTimeDurationLiteral(v2)) => {
Some(NumericBinaryOperands::DateDayTimeDuration(*v1, *v2))
Some(Self::DateDayTimeDuration(*v1, *v2))
}
(EncodedTerm::TimeLiteral(v1), EncodedTerm::DurationLiteral(v2)) => {
Some(NumericBinaryOperands::TimeDuration(*v1, *v2))
Some(Self::TimeDuration(*v1, *v2))
}
(EncodedTerm::TimeLiteral(v1), EncodedTerm::DayTimeDurationLiteral(v2)) => {
Some(NumericBinaryOperands::TimeDayTimeDuration(*v1, *v2))
Some(Self::TimeDayTimeDuration(*v1, *v2))
}
_ => None,
}

@ -18,6 +18,7 @@ impl Client {
Self {}
}
#[allow(clippy::unused_self)]
pub fn request(
&self,
request: &Request<Option<Vec<u8>>>,
@ -48,8 +49,8 @@ impl Client {
match scheme {
"http" => {
let mut stream = TcpStream::connect((host, port))?;
self.encode(request, &mut stream)?;
self.decode(stream)
Self::encode(request, &mut stream)?;
Self::decode(stream)
}
"https" => {
let connector =
@ -58,8 +59,8 @@ impl Client {
let mut stream = connector
.connect(host, stream)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
self.encode(request, &mut stream)?;
self.decode(stream)
Self::encode(request, &mut stream)?;
Self::decode(stream)
}
_ => Err(invalid_input_error(format!(
"Not supported URL scheme: {}",
@ -68,11 +69,7 @@ impl Client {
}
}
fn encode(
&self,
request: &Request<Option<Vec<u8>>>,
mut writer: &mut impl Write,
) -> io::Result<()> {
fn encode(request: &Request<Option<Vec<u8>>>, mut writer: &mut impl Write) -> io::Result<()> {
if request.headers().contains_key(CONTENT_LENGTH) {
return Err(invalid_input_error(
"content-length header is set by the client library",
@ -136,7 +133,7 @@ impl Client {
Ok(())
}
fn decode<'a>(&self, reader: impl Read + 'a) -> io::Result<Response<Box<dyn BufRead + 'a>>> {
fn decode<'a>(reader: impl Read + 'a) -> io::Result<Response<Box<dyn BufRead + 'a>>> {
let mut reader = BufReader::new(reader);
// Let's read the headers
@ -313,7 +310,7 @@ mod tests {
#[test]
fn encode_get_request() -> io::Result<()> {
let mut buffer = Vec::new();
Client::new().encode(
Client::encode(
&Request::builder()
.method(Method::GET)
.uri("http://example.com/foo/bar?query#fragment")
@ -332,7 +329,7 @@ mod tests {
#[test]
fn encode_post_request() -> io::Result<()> {
let mut buffer = Vec::new();
Client::new().encode(
Client::encode(
&Request::builder()
.method(Method::POST)
.uri("http://example.com/foo/bar?query#fragment")
@ -350,9 +347,7 @@ mod tests {
#[test]
fn decode_response_without_payload() -> io::Result<()> {
let response = Client::new()
.decode(Cursor::new("HTTP/1.1 404 Not Found\r\n\r\n"))
.unwrap();
let response = Client::decode(Cursor::new("HTTP/1.1 404 Not Found\r\n\r\n")).unwrap();
assert_eq!(response.status(), StatusCode::NOT_FOUND);
let mut buf = String::new();
response.into_body().read_to_string(&mut buf)?;
@ -362,7 +357,7 @@ mod tests {
#[test]
fn decode_response_with_fixed_payload() -> io::Result<()> {
let response = Client::new().decode(Cursor::new(
let response = Client::decode(Cursor::new(
"HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\ncontent-length:8\r\n\r\ntestbody",
))?;
assert_eq!(response.status(), StatusCode::OK);
@ -383,7 +378,7 @@ mod tests {
#[test]
fn decode_response_with_chunked_payload() -> io::Result<()> {
let response = Client::new().decode(Cursor::new(
let response = Client::decode(Cursor::new(
"HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\ntransfer-encoding:chunked\r\n\r\n4\r\nWiki\r\n5\r\npedia\r\nE\r\n in\r\n\r\nchunks.\r\n0\r\n\r\n",
))?;
assert_eq!(response.status(), StatusCode::OK);
@ -404,7 +399,7 @@ mod tests {
#[test]
fn decode_response_with_trailer() -> io::Result<()> {
let response = Client::new().decode(Cursor::new(
let response = Client::decode(Cursor::new(
"HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\ntransfer-encoding:chunked\r\n\r\n4\r\nWiki\r\n5\r\npedia\r\nE\r\n in\r\n\r\nchunks.\r\n0\r\ntest: foo\r\n\r\n",
))?;
assert_eq!(response.status(), StatusCode::OK);

@ -40,14 +40,14 @@ pub(crate) fn evaluate_query(
query: impl TryInto<Query, Error = impl Into<EvaluationError>>,
options: QueryOptions,
) -> Result<QueryResults, EvaluationError> {
let query = query.try_into().map_err(|e| e.into())?;
let dataset = DatasetView::new(storage, &query.dataset)?;
let query = query.try_into().map_err(std::convert::Into::into)?;
let dataset = DatasetView::new(storage, &query.dataset);
match query.inner {
spargebra::Query::Select {
pattern, base_iri, ..
} => {
let (plan, variables) = PlanBuilder::build(&dataset, &pattern)?;
SimpleEvaluator::new(
Ok(SimpleEvaluator::new(
Rc::new(dataset),
base_iri.map(Rc::new),
options.service_handler,
@ -60,7 +60,7 @@ pub(crate) fn evaluate_query(
.map(|v| Variable::new_unchecked(v.name))
.collect(),
),
)
))
}
spargebra::Query::Ask {
pattern, base_iri, ..
@ -81,23 +81,23 @@ pub(crate) fn evaluate_query(
} => {
let (plan, variables) = PlanBuilder::build(&dataset, &pattern)?;
let construct = PlanBuilder::build_graph_template(&dataset, &template, variables);
SimpleEvaluator::new(
Ok(SimpleEvaluator::new(
Rc::new(dataset),
base_iri.map(Rc::new),
options.service_handler,
)
.evaluate_construct_plan(&plan, construct)
.evaluate_construct_plan(&plan, construct))
}
spargebra::Query::Describe {
pattern, base_iri, ..
} => {
let (plan, _) = PlanBuilder::build(&dataset, &pattern)?;
SimpleEvaluator::new(
Ok(SimpleEvaluator::new(
Rc::new(dataset),
base_iri.map(Rc::new),
options.service_handler,
)
.evaluate_describe_plan(&plan)
.evaluate_describe_plan(&plan))
}
}
}

@ -109,7 +109,7 @@ impl QueryResults {
impl From<QuerySolutionIter> for QueryResults {
#[inline]
fn from(value: QuerySolutionIter) -> Self {
QueryResults::Solutions(value)
Self::Solutions(value)
}
}
@ -193,13 +193,13 @@ impl QueryResultsFormat {
if let Some(base_type) = media_type.split(';').next() {
match base_type {
"application/sparql-results+xml" | "application/xml" | "text/xml" => {
Some(QueryResultsFormat::Xml)
Some(Self::Xml)
}
"application/sparql-results+json" | "application/json" | "text/json" => {
Some(QueryResultsFormat::Json)
Some(Self::Json)
}
"text/csv" => Some(QueryResultsFormat::Csv),
"text/tab-separated-values" | "text/tsv" => Some(QueryResultsFormat::Tsv),
"text/csv" => Some(Self::Csv),
"text/tab-separated-values" | "text/tsv" => Some(Self::Tsv),
_ => None,
}
} else {
@ -287,7 +287,7 @@ impl QuerySolution {
/// ```
#[inline]
pub fn get(&self, index: impl VariableSolutionIndex) -> Option<&Term> {
self.values.get(index.index(self)?).and_then(|e| e.as_ref())
self.values.get(index.index(self)?).and_then(std::option::Option::as_ref)
}
/// The number of variables which could be bound
@ -314,7 +314,7 @@ impl QuerySolution {
/// Returns an iterator over all values, bound or not
#[inline]
pub fn values(&self) -> impl Iterator<Item = Option<&Term>> {
self.values.iter().map(|v| v.as_ref())
self.values.iter().map(std::option::Option::as_ref)
}
}
@ -425,7 +425,7 @@ impl Variable {
/// [`Variable::new()`] is a safe version of this constructor and should be used for untrusted data.
#[inline]
pub fn new_unchecked(name: impl Into<String>) -> Self {
Variable { name: name.into() }
Self { name: name.into() }
}
#[inline]

@ -13,71 +13,71 @@ pub enum PlanNode {
Service {
service_name: PatternValue,
variables: Rc<Vec<Variable>>,
child: Rc<PlanNode>,
child: Rc<Self>,
graph_pattern: Rc<GraphPattern>,
silent: bool,
},
QuadPatternJoin {
child: Rc<PlanNode>,
child: Rc<Self>,
subject: PatternValue,
predicate: PatternValue,
object: PatternValue,
graph_name: PatternValue,
},
PathPatternJoin {
child: Rc<PlanNode>,
child: Rc<Self>,
subject: PatternValue,
path: Rc<PlanPropertyPath>,
object: PatternValue,
graph_name: PatternValue,
},
Join {
left: Rc<PlanNode>,
right: Rc<PlanNode>,
left: Rc<Self>,
right: Rc<Self>,
},
AntiJoin {
left: Rc<PlanNode>,
right: Rc<PlanNode>,
left: Rc<Self>,
right: Rc<Self>,
},
Filter {
child: Rc<PlanNode>,
child: Rc<Self>,
expression: Rc<PlanExpression>,
},
Union {
children: Vec<Rc<PlanNode>>,
children: Vec<Rc<Self>>,
},
LeftJoin {
left: Rc<PlanNode>,
right: Rc<PlanNode>,
left: Rc<Self>,
right: Rc<Self>,
possible_problem_vars: Rc<Vec<usize>>, //Variables that should not be part of the entry of the left join
},
Extend {
child: Rc<PlanNode>,
child: Rc<Self>,
position: usize,
expression: Rc<PlanExpression>,
},
Sort {
child: Rc<PlanNode>,
child: Rc<Self>,
by: Vec<Comparator>,
},
HashDeduplicate {
child: Rc<PlanNode>,
child: Rc<Self>,
},
Skip {
child: Rc<PlanNode>,
child: Rc<Self>,
count: usize,
},
Limit {
child: Rc<PlanNode>,
child: Rc<Self>,
count: usize,
},
Project {
child: Rc<PlanNode>,
child: Rc<Self>,
mapping: Rc<Vec<(usize, usize)>>, // pairs of (variable key in child, variable key in output)
},
Aggregate {
// By definition the group by key are the range 0..key_mapping.len()
child: Rc<PlanNode>,
child: Rc<Self>,
key_mapping: Rc<Vec<(usize, usize)>>, // aggregate key pairs of (variable key in child, variable key in output)
aggregates: Rc<Vec<(PlanAggregation, usize)>>,
},
@ -212,109 +212,109 @@ pub enum PlanExpression {
Constant(EncodedTerm),
Variable(usize),
Exists(Rc<PlanNode>),
Or(Box<PlanExpression>, Box<PlanExpression>),
And(Box<PlanExpression>, Box<PlanExpression>),
Equal(Box<PlanExpression>, Box<PlanExpression>),
Greater(Box<PlanExpression>, Box<PlanExpression>),
GreaterOrEqual(Box<PlanExpression>, Box<PlanExpression>),
Less(Box<PlanExpression>, Box<PlanExpression>),
LessOrEqual(Box<PlanExpression>, Box<PlanExpression>),
In(Box<PlanExpression>, Vec<PlanExpression>),
Add(Box<PlanExpression>, Box<PlanExpression>),
Subtract(Box<PlanExpression>, Box<PlanExpression>),
Multiply(Box<PlanExpression>, Box<PlanExpression>),
Divide(Box<PlanExpression>, Box<PlanExpression>),
UnaryPlus(Box<PlanExpression>),
UnaryMinus(Box<PlanExpression>),
Not(Box<PlanExpression>),
Str(Box<PlanExpression>),
Lang(Box<PlanExpression>),
LangMatches(Box<PlanExpression>, Box<PlanExpression>),
Datatype(Box<PlanExpression>),
Or(Box<Self>, Box<Self>),
And(Box<Self>, Box<Self>),
Equal(Box<Self>, Box<Self>),
Greater(Box<Self>, Box<Self>),
GreaterOrEqual(Box<Self>, Box<Self>),
Less(Box<Self>, Box<Self>),
LessOrEqual(Box<Self>, Box<Self>),
In(Box<Self>, Vec<Self>),
Add(Box<Self>, Box<Self>),
Subtract(Box<Self>, Box<Self>),
Multiply(Box<Self>, Box<Self>),
Divide(Box<Self>, Box<Self>),
UnaryPlus(Box<Self>),
UnaryMinus(Box<Self>),
Not(Box<Self>),
Str(Box<Self>),
Lang(Box<Self>),
LangMatches(Box<Self>, Box<Self>),
Datatype(Box<Self>),
Bound(usize),
Iri(Box<PlanExpression>),
BNode(Option<Box<PlanExpression>>),
Iri(Box<Self>),
BNode(Option<Box<Self>>),
Rand,
Abs(Box<PlanExpression>),
Ceil(Box<PlanExpression>),
Floor(Box<PlanExpression>),
Round(Box<PlanExpression>),
Concat(Vec<PlanExpression>),
Abs(Box<Self>),
Ceil(Box<Self>),
Floor(Box<Self>),
Round(Box<Self>),
Concat(Vec<Self>),
SubStr(
Box<PlanExpression>,
Box<PlanExpression>,
Option<Box<PlanExpression>>,
Box<Self>,
Box<Self>,
Option<Box<Self>>,
),
StrLen(Box<PlanExpression>),
StrLen(Box<Self>),
Replace(
Box<PlanExpression>,
Box<PlanExpression>,
Box<PlanExpression>,
Option<Box<PlanExpression>>,
Box<Self>,
Box<Self>,
Box<Self>,
Option<Box<Self>>,
),
UCase(Box<PlanExpression>),
LCase(Box<PlanExpression>),
EncodeForUri(Box<PlanExpression>),
Contains(Box<PlanExpression>, Box<PlanExpression>),
StrStarts(Box<PlanExpression>, Box<PlanExpression>),
StrEnds(Box<PlanExpression>, Box<PlanExpression>),
StrBefore(Box<PlanExpression>, Box<PlanExpression>),
StrAfter(Box<PlanExpression>, Box<PlanExpression>),
Year(Box<PlanExpression>),
Month(Box<PlanExpression>),
Day(Box<PlanExpression>),
Hours(Box<PlanExpression>),
Minutes(Box<PlanExpression>),
Seconds(Box<PlanExpression>),
Timezone(Box<PlanExpression>),
Tz(Box<PlanExpression>),
UCase(Box<Self>),
LCase(Box<Self>),
EncodeForUri(Box<Self>),
Contains(Box<Self>, Box<Self>),
StrStarts(Box<Self>, Box<Self>),
StrEnds(Box<Self>, Box<Self>),
StrBefore(Box<Self>, Box<Self>),
StrAfter(Box<Self>, Box<Self>),
Year(Box<Self>),
Month(Box<Self>),
Day(Box<Self>),
Hours(Box<Self>),
Minutes(Box<Self>),
Seconds(Box<Self>),
Timezone(Box<Self>),
Tz(Box<Self>),
Now,
Uuid,
StrUuid,
Md5(Box<PlanExpression>),
Sha1(Box<PlanExpression>),
Sha256(Box<PlanExpression>),
Sha384(Box<PlanExpression>),
Sha512(Box<PlanExpression>),
Coalesce(Vec<PlanExpression>),
Md5(Box<Self>),
Sha1(Box<Self>),
Sha256(Box<Self>),
Sha384(Box<Self>),
Sha512(Box<Self>),
Coalesce(Vec<Self>),
If(
Box<PlanExpression>,
Box<PlanExpression>,
Box<PlanExpression>,
Box<Self>,
Box<Self>,
Box<Self>,
),
StrLang(Box<PlanExpression>, Box<PlanExpression>),
StrDt(Box<PlanExpression>, Box<PlanExpression>),
SameTerm(Box<PlanExpression>, Box<PlanExpression>),
IsIri(Box<PlanExpression>),
IsBlank(Box<PlanExpression>),
IsLiteral(Box<PlanExpression>),
IsNumeric(Box<PlanExpression>),
StrLang(Box<Self>, Box<Self>),
StrDt(Box<Self>, Box<Self>),
SameTerm(Box<Self>, Box<Self>),
IsIri(Box<Self>),
IsBlank(Box<Self>),
IsLiteral(Box<Self>),
IsNumeric(Box<Self>),
Regex(
Box<PlanExpression>,
Box<PlanExpression>,
Option<Box<PlanExpression>>,
Box<Self>,
Box<Self>,
Option<Box<Self>>,
),
Triple(
Box<PlanExpression>,
Box<PlanExpression>,
Box<PlanExpression>,
Box<Self>,
Box<Self>,
Box<Self>,
),
Subject(Box<PlanExpression>),
Predicate(Box<PlanExpression>),
Object(Box<PlanExpression>),
IsTriple(Box<PlanExpression>),
BooleanCast(Box<PlanExpression>),
DoubleCast(Box<PlanExpression>),
FloatCast(Box<PlanExpression>),
DecimalCast(Box<PlanExpression>),
IntegerCast(Box<PlanExpression>),
DateCast(Box<PlanExpression>),
TimeCast(Box<PlanExpression>),
DateTimeCast(Box<PlanExpression>),
DurationCast(Box<PlanExpression>),
YearMonthDurationCast(Box<PlanExpression>),
DayTimeDurationCast(Box<PlanExpression>),
StringCast(Box<PlanExpression>),
Subject(Box<Self>),
Predicate(Box<Self>),
Object(Box<Self>),
IsTriple(Box<Self>),
BooleanCast(Box<Self>),
DoubleCast(Box<Self>),
FloatCast(Box<Self>),
DecimalCast(Box<Self>),
IntegerCast(Box<Self>),
DateCast(Box<Self>),
TimeCast(Box<Self>),
DateTimeCast(Box<Self>),
DurationCast(Box<Self>),
YearMonthDurationCast(Box<Self>),
DayTimeDurationCast(Box<Self>),
StringCast(Box<Self>),
}
impl PlanExpression {
@ -458,12 +458,12 @@ pub enum PlanAggregationFunction {
#[derive(Eq, PartialEq, Debug, Clone, Hash)]
pub enum PlanPropertyPath {
Path(EncodedTerm),
Reverse(Rc<PlanPropertyPath>),
Sequence(Rc<PlanPropertyPath>, Rc<PlanPropertyPath>),
Alternative(Rc<PlanPropertyPath>, Rc<PlanPropertyPath>),
ZeroOrMore(Rc<PlanPropertyPath>),
OneOrMore(Rc<PlanPropertyPath>),
ZeroOrOne(Rc<PlanPropertyPath>),
Reverse(Rc<Self>),
Sequence(Rc<Self>, Rc<Self>),
Alternative(Rc<Self>, Rc<Self>),
ZeroOrMore(Rc<Self>),
OneOrMore(Rc<Self>),
ZeroOrOne(Rc<Self>),
NegatedPropertySet(Rc<Vec<EncodedTerm>>),
}
@ -529,9 +529,9 @@ impl EncodedTuple {
}
}
pub fn combine_with(&self, other: &EncodedTuple) -> Option<Self> {
pub fn combine_with(&self, other: &Self) -> Option<Self> {
if self.inner.len() < other.inner.len() {
let mut result = other.inner.to_owned();
let mut result = other.inner.clone();
for (key, self_value) in self.inner.iter().enumerate() {
if let Some(self_value) = self_value {
match other.inner[key] {
@ -544,9 +544,9 @@ impl EncodedTuple {
}
}
}
Some(EncodedTuple { inner: result })
Some(Self { inner: result })
} else {
let mut result = self.inner.to_owned();
let mut result = self.inner.clone();
for (key, other_value) in other.inner.iter().enumerate() {
if let Some(other_value) = other_value {
match self.inner[key] {
@ -559,7 +559,7 @@ impl EncodedTuple {
}
}
}
Some(EncodedTuple { inner: result })
Some(Self { inner: result })
}
}
}

@ -10,7 +10,7 @@ use spargebra::term::*;
use std::collections::{BTreeSet, HashSet};
use std::rc::Rc;
pub(crate) struct PlanBuilder<'a> {
pub struct PlanBuilder<'a> {
dataset: &'a DatasetView,
}
@ -920,7 +920,7 @@ impl<'a> PlanBuilder<'a> {
separator,
} => Ok(PlanAggregation {
function: PlanAggregationFunction::GroupConcat {
separator: Rc::new(separator.clone().unwrap_or_else(|| " ".to_string())),
separator: Rc::new(separator.clone().unwrap_or_else(|| " ".to_owned())),
},
parameter: Some(self.build_for_expression(expr, variables, graph_name)?),
distinct: *distinct,
@ -1027,7 +1027,7 @@ impl<'a> PlanBuilder<'a> {
match from_value {
PatternValue::Constant(v) => PatternValue::Constant(v.clone()),
PatternValue::Variable(from_id) => {
PatternValue::Variable(self.convert_variable_id(*from_id, from, to))
PatternValue::Variable(Self::convert_variable_id(*from_id, from, to))
}
PatternValue::Triple(triple) => PatternValue::Triple(Box::new(TriplePatternValue {
subject: self.convert_pattern_value_id(&triple.subject, from, to),
@ -1037,12 +1037,7 @@ impl<'a> PlanBuilder<'a> {
}
}
fn convert_variable_id(
&self,
from_id: usize,
from: &[Variable],
to: &mut Vec<Variable>,
) -> usize {
fn convert_variable_id(from_id: usize, from: &[Variable], to: &mut Vec<Variable>) -> usize {
if let Some(to_id) = to.iter().enumerate().find_map(|(to_id, var)| {
if *var == from[from_id] {
Some(to_id)

@ -29,7 +29,7 @@ use std::collections::HashMap;
use std::io;
use std::rc::Rc;
pub(crate) struct SimpleUpdateEvaluator<'a> {
pub struct SimpleUpdateEvaluator<'a> {
storage: &'a Storage,
base_iri: Option<Rc<Iri<String>>>,
options: UpdateOptions,
@ -95,7 +95,7 @@ impl<'a> SimpleUpdateEvaluator<'a> {
fn eval_insert_data(&mut self, data: &[Quad]) -> Result<(), EvaluationError> {
let mut bnodes = HashMap::new();
for quad in data {
let quad = self.convert_quad(quad, &mut bnodes);
let quad = Self::convert_quad(quad, &mut bnodes);
self.storage.insert(quad.as_ref())?;
}
Ok(())
@ -103,7 +103,7 @@ impl<'a> SimpleUpdateEvaluator<'a> {
fn eval_delete_data(&mut self, data: &[GroundQuad]) -> Result<(), EvaluationError> {
for quad in data {
let quad = self.convert_ground_quad(quad);
let quad = Self::convert_ground_quad(quad);
self.storage.remove(quad.as_ref())?;
}
Ok(())
@ -116,7 +116,7 @@ impl<'a> SimpleUpdateEvaluator<'a> {
using: &QueryDataset,
algebra: &GraphPattern,
) -> Result<(), EvaluationError> {
let dataset = Rc::new(DatasetView::new(self.storage.clone(), using)?);
let dataset = Rc::new(DatasetView::new(self.storage.clone(), using));
let (plan, variables) = PlanBuilder::build(dataset.as_ref(), algebra)?;
let evaluator = SimpleEvaluator::new(
dataset.clone(),
@ -128,7 +128,7 @@ impl<'a> SimpleUpdateEvaluator<'a> {
let tuple = tuple?;
for quad in delete {
if let Some(quad) =
self.convert_ground_quad_pattern(quad, &variables, &tuple, &dataset)?
Self::convert_ground_quad_pattern(quad, &variables, &tuple, &dataset)?
{
self.storage.remove(quad.as_ref())?;
// Hack to make sure the triple terms are still available for an insert
@ -139,7 +139,7 @@ impl<'a> SimpleUpdateEvaluator<'a> {
}
for quad in insert {
if let Some(quad) =
self.convert_quad_pattern(quad, &variables, &tuple, &dataset, &mut bnodes)?
Self::convert_quad_pattern(quad, &variables, &tuple, &dataset, &mut bnodes)?
{
self.storage.insert(quad.as_ref())?;
}
@ -254,61 +254,56 @@ impl<'a> SimpleUpdateEvaluator<'a> {
}
}
fn convert_quad(&self, quad: &Quad, bnodes: &mut HashMap<BlankNode, OxBlankNode>) -> OxQuad {
fn convert_quad(quad: &Quad, bnodes: &mut HashMap<BlankNode, OxBlankNode>) -> OxQuad {
OxQuad {
subject: match &quad.subject {
Subject::NamedNode(subject) => self.convert_named_node(subject).into(),
Subject::BlankNode(subject) => self.convert_blank_node(subject, bnodes).into(),
Subject::Triple(subject) => self.convert_triple(subject, bnodes).into(),
Subject::NamedNode(subject) => Self::convert_named_node(subject).into(),
Subject::BlankNode(subject) => Self::convert_blank_node(subject, bnodes).into(),
Subject::Triple(subject) => Self::convert_triple(subject, bnodes).into(),
},
predicate: self.convert_named_node(&quad.predicate),
predicate: Self::convert_named_node(&quad.predicate),
object: match &quad.object {
Term::NamedNode(object) => self.convert_named_node(object).into(),
Term::BlankNode(object) => self.convert_blank_node(object, bnodes).into(),
Term::Literal(object) => self.convert_literal(object).into(),
Term::Triple(subject) => self.convert_triple(subject, bnodes).into(),
Term::NamedNode(object) => Self::convert_named_node(object).into(),
Term::BlankNode(object) => Self::convert_blank_node(object, bnodes).into(),
Term::Literal(object) => Self::convert_literal(object).into(),
Term::Triple(subject) => Self::convert_triple(subject, bnodes).into(),
},
graph_name: match &quad.graph_name {
GraphName::NamedNode(graph_name) => self.convert_named_node(graph_name).into(),
GraphName::NamedNode(graph_name) => Self::convert_named_node(graph_name).into(),
GraphName::DefaultGraph => OxGraphName::DefaultGraph,
},
}
}
fn convert_triple(
&self,
triple: &Triple,
bnodes: &mut HashMap<BlankNode, OxBlankNode>,
) -> OxTriple {
fn convert_triple(triple: &Triple, bnodes: &mut HashMap<BlankNode, OxBlankNode>) -> OxTriple {
OxTriple {
subject: match &triple.subject {
Subject::NamedNode(subject) => self.convert_named_node(subject).into(),
Subject::BlankNode(subject) => self.convert_blank_node(subject, bnodes).into(),
Subject::Triple(subject) => self.convert_triple(subject, bnodes).into(),
Subject::NamedNode(subject) => Self::convert_named_node(subject).into(),
Subject::BlankNode(subject) => Self::convert_blank_node(subject, bnodes).into(),
Subject::Triple(subject) => Self::convert_triple(subject, bnodes).into(),
},
predicate: self.convert_named_node(&triple.predicate),
predicate: Self::convert_named_node(&triple.predicate),
object: match &triple.object {
Term::NamedNode(object) => self.convert_named_node(object).into(),
Term::BlankNode(object) => self.convert_blank_node(object, bnodes).into(),
Term::Literal(object) => self.convert_literal(object).into(),
Term::Triple(subject) => self.convert_triple(subject, bnodes).into(),
Term::NamedNode(object) => Self::convert_named_node(object).into(),
Term::BlankNode(object) => Self::convert_blank_node(object, bnodes).into(),
Term::Literal(object) => Self::convert_literal(object).into(),
Term::Triple(subject) => Self::convert_triple(subject, bnodes).into(),
},
}
}
fn convert_named_node(&self, node: &NamedNode) -> OxNamedNode {
fn convert_named_node(node: &NamedNode) -> OxNamedNode {
OxNamedNode::new_unchecked(&node.iri)
}
fn convert_blank_node(
&self,
node: &BlankNode,
bnodes: &mut HashMap<BlankNode, OxBlankNode>,
) -> OxBlankNode {
bnodes.entry(node.clone()).or_default().clone()
}
fn convert_literal(&self, literal: &Literal) -> OxLiteral {
fn convert_literal(literal: &Literal) -> OxLiteral {
match literal {
Literal::Simple { value } => OxLiteral::new_simple_literal(value),
Literal::LanguageTaggedString { value, language } => {
@ -320,42 +315,41 @@ impl<'a> SimpleUpdateEvaluator<'a> {
}
}
fn convert_ground_quad(&self, quad: &GroundQuad) -> OxQuad {
fn convert_ground_quad(quad: &GroundQuad) -> OxQuad {
OxQuad {
subject: match &quad.subject {
GroundSubject::NamedNode(subject) => self.convert_named_node(subject).into(),
GroundSubject::Triple(subject) => self.convert_ground_triple(subject).into(),
GroundSubject::NamedNode(subject) => Self::convert_named_node(subject).into(),
GroundSubject::Triple(subject) => Self::convert_ground_triple(subject).into(),
},
predicate: self.convert_named_node(&quad.predicate),
predicate: Self::convert_named_node(&quad.predicate),
object: match &quad.object {
GroundTerm::NamedNode(object) => self.convert_named_node(object).into(),
GroundTerm::Literal(object) => self.convert_literal(object).into(),
GroundTerm::Triple(subject) => self.convert_ground_triple(subject).into(),
GroundTerm::NamedNode(object) => Self::convert_named_node(object).into(),
GroundTerm::Literal(object) => Self::convert_literal(object).into(),
GroundTerm::Triple(subject) => Self::convert_ground_triple(subject).into(),
},
graph_name: match &quad.graph_name {
GraphName::NamedNode(graph_name) => self.convert_named_node(graph_name).into(),
GraphName::NamedNode(graph_name) => Self::convert_named_node(graph_name).into(),
GraphName::DefaultGraph => OxGraphName::DefaultGraph,
},
}
}
fn convert_ground_triple(&self, triple: &GroundTriple) -> OxTriple {
fn convert_ground_triple(triple: &GroundTriple) -> OxTriple {
OxTriple {
subject: match &triple.subject {
GroundSubject::NamedNode(subject) => self.convert_named_node(subject).into(),
GroundSubject::Triple(subject) => self.convert_ground_triple(subject).into(),
GroundSubject::NamedNode(subject) => Self::convert_named_node(subject).into(),
GroundSubject::Triple(subject) => Self::convert_ground_triple(subject).into(),
},
predicate: self.convert_named_node(&triple.predicate),
predicate: Self::convert_named_node(&triple.predicate),
object: match &triple.object {
GroundTerm::NamedNode(object) => self.convert_named_node(object).into(),
GroundTerm::Literal(object) => self.convert_literal(object).into(),
GroundTerm::Triple(subject) => self.convert_ground_triple(subject).into(),
GroundTerm::NamedNode(object) => Self::convert_named_node(object).into(),
GroundTerm::Literal(object) => Self::convert_literal(object).into(),
GroundTerm::Triple(subject) => Self::convert_ground_triple(subject).into(),
},
}
}
fn convert_quad_pattern(
&self,
quad: &QuadPattern,
variables: &[Variable],
values: &EncodedTuple,
@ -363,7 +357,7 @@ impl<'a> SimpleUpdateEvaluator<'a> {
bnodes: &mut HashMap<BlankNode, OxBlankNode>,
) -> Result<Option<OxQuad>, EvaluationError> {
Ok(Some(OxQuad {
subject: match self.convert_term_or_var(
subject: match Self::convert_term_or_var(
&quad.subject,
variables,
values,
@ -376,21 +370,21 @@ impl<'a> SimpleUpdateEvaluator<'a> {
Some(OxTerm::Literal(_)) | None => return Ok(None),
},
predicate: if let Some(predicate) =
self.convert_named_node_or_var(&quad.predicate, variables, values, dataset)?
Self::convert_named_node_or_var(&quad.predicate, variables, values, dataset)?
{
predicate
} else {
return Ok(None);
},
object: if let Some(object) =
self.convert_term_or_var(&quad.object, variables, values, dataset, bnodes)?
Self::convert_term_or_var(&quad.object, variables, values, dataset, bnodes)?
{
object
} else {
return Ok(None);
},
graph_name: if let Some(graph_name) =
self.convert_graph_name_or_var(&quad.graph_name, variables, values, dataset)?
Self::convert_graph_name_or_var(&quad.graph_name, variables, values, dataset)?
{
graph_name
} else {
@ -400,7 +394,6 @@ impl<'a> SimpleUpdateEvaluator<'a> {
}
fn convert_term_or_var(
&self,
term: &TermPattern,
variables: &[Variable],
values: &EncodedTuple,
@ -408,47 +401,43 @@ impl<'a> SimpleUpdateEvaluator<'a> {
bnodes: &mut HashMap<BlankNode, OxBlankNode>,
) -> Result<Option<OxTerm>, EvaluationError> {
Ok(match term {
TermPattern::NamedNode(term) => Some(self.convert_named_node(term).into()),
TermPattern::BlankNode(bnode) => Some(self.convert_blank_node(bnode, bnodes).into()),
TermPattern::Literal(term) => Some(self.convert_literal(term).into()),
TermPattern::Triple(triple) => self
.convert_triple_pattern(triple, variables, values, dataset, bnodes)?
.map(|t| t.into()),
TermPattern::Variable(v) => self
.lookup_variable(v, variables, values)
TermPattern::NamedNode(term) => Some(Self::convert_named_node(term).into()),
TermPattern::BlankNode(bnode) => Some(Self::convert_blank_node(bnode, bnodes).into()),
TermPattern::Literal(term) => Some(Self::convert_literal(term).into()),
TermPattern::Triple(triple) => {
Self::convert_triple_pattern(triple, variables, values, dataset, bnodes)?
.map(|t| t.into())
}
TermPattern::Variable(v) => Self::lookup_variable(v, variables, values)
.map(|node| dataset.decode_term(&node))
.transpose()?,
})
}
fn convert_named_node_or_var(
&self,
term: &NamedNodePattern,
variables: &[Variable],
values: &EncodedTuple,
dataset: &DatasetView,
) -> Result<Option<OxNamedNode>, EvaluationError> {
Ok(match term {
NamedNodePattern::NamedNode(term) => Some(self.convert_named_node(term)),
NamedNodePattern::Variable(v) => self
.lookup_variable(v, variables, values)
NamedNodePattern::NamedNode(term) => Some(Self::convert_named_node(term)),
NamedNodePattern::Variable(v) => Self::lookup_variable(v, variables, values)
.map(|node| dataset.decode_named_node(&node))
.transpose()?,
})
}
fn convert_graph_name_or_var(
&self,
term: &GraphNamePattern,
variables: &[Variable],
values: &EncodedTuple,
dataset: &DatasetView,
) -> Result<Option<OxGraphName>, EvaluationError> {
match term {
GraphNamePattern::NamedNode(term) => Ok(Some(self.convert_named_node(term).into())),
GraphNamePattern::NamedNode(term) => Ok(Some(Self::convert_named_node(term).into())),
GraphNamePattern::DefaultGraph => Ok(Some(OxGraphName::DefaultGraph)),
GraphNamePattern::Variable(v) => self
.lookup_variable(v, variables, values)
GraphNamePattern::Variable(v) => Self::lookup_variable(v, variables, values)
.map(|node| {
Ok(if node == EncodedTerm::DefaultGraph {
OxGraphName::DefaultGraph
@ -461,7 +450,6 @@ impl<'a> SimpleUpdateEvaluator<'a> {
}
fn convert_triple_pattern(
&self,
triple: &TriplePattern,
variables: &[Variable],
values: &EncodedTuple,
@ -469,7 +457,7 @@ impl<'a> SimpleUpdateEvaluator<'a> {
bnodes: &mut HashMap<BlankNode, OxBlankNode>,
) -> Result<Option<OxTriple>, EvaluationError> {
Ok(Some(OxTriple {
subject: match self.convert_term_or_var(
subject: match Self::convert_term_or_var(
&triple.subject,
variables,
values,
@ -482,14 +470,14 @@ impl<'a> SimpleUpdateEvaluator<'a> {
Some(OxTerm::Literal(_)) | None => return Ok(None),
},
predicate: if let Some(predicate) =
self.convert_named_node_or_var(&triple.predicate, variables, values, dataset)?
Self::convert_named_node_or_var(&triple.predicate, variables, values, dataset)?
{
predicate
} else {
return Ok(None);
},
object: if let Some(object) =
self.convert_term_or_var(&triple.object, variables, values, dataset, bnodes)?
Self::convert_term_or_var(&triple.object, variables, values, dataset, bnodes)?
{
object
} else {
@ -499,14 +487,13 @@ impl<'a> SimpleUpdateEvaluator<'a> {
}
fn convert_ground_quad_pattern(
&self,
quad: &GroundQuadPattern,
variables: &[Variable],
values: &EncodedTuple,
dataset: &DatasetView,
) -> Result<Option<OxQuad>, EvaluationError> {
Ok(Some(OxQuad {
subject: match self.convert_ground_term_or_var(
subject: match Self::convert_ground_term_or_var(
&quad.subject,
variables,
values,
@ -518,21 +505,21 @@ impl<'a> SimpleUpdateEvaluator<'a> {
Some(OxTerm::Literal(_)) | None => return Ok(None),
},
predicate: if let Some(predicate) =
self.convert_named_node_or_var(&quad.predicate, variables, values, dataset)?
Self::convert_named_node_or_var(&quad.predicate, variables, values, dataset)?
{
predicate
} else {
return Ok(None);
},
object: if let Some(object) =
self.convert_ground_term_or_var(&quad.object, variables, values, dataset)?
Self::convert_ground_term_or_var(&quad.object, variables, values, dataset)?
{
object
} else {
return Ok(None);
},
graph_name: if let Some(graph_name) =
self.convert_graph_name_or_var(&quad.graph_name, variables, values, dataset)?
Self::convert_graph_name_or_var(&quad.graph_name, variables, values, dataset)?
{
graph_name
} else {
@ -542,34 +529,32 @@ impl<'a> SimpleUpdateEvaluator<'a> {
}
fn convert_ground_term_or_var(
&self,
term: &GroundTermPattern,
variables: &[Variable],
values: &EncodedTuple,
dataset: &DatasetView,
) -> Result<Option<OxTerm>, EvaluationError> {
Ok(match term {
GroundTermPattern::NamedNode(term) => Some(self.convert_named_node(term).into()),
GroundTermPattern::Literal(term) => Some(self.convert_literal(term).into()),
GroundTermPattern::Triple(triple) => self
.convert_ground_triple_pattern(triple, variables, values, dataset)?
.map(|t| t.into()),
GroundTermPattern::Variable(v) => self
.lookup_variable(v, variables, values)
GroundTermPattern::NamedNode(term) => Some(Self::convert_named_node(term).into()),
GroundTermPattern::Literal(term) => Some(Self::convert_literal(term).into()),
GroundTermPattern::Triple(triple) => {
Self::convert_ground_triple_pattern(triple, variables, values, dataset)?
.map(|t| t.into())
}
GroundTermPattern::Variable(v) => Self::lookup_variable(v, variables, values)
.map(|node| dataset.decode_term(&node))
.transpose()?,
})
}
fn convert_ground_triple_pattern(
&self,
triple: &GroundTriplePattern,
variables: &[Variable],
values: &EncodedTuple,
dataset: &DatasetView,
) -> Result<Option<OxTriple>, EvaluationError> {
Ok(Some(OxTriple {
subject: match self.convert_ground_term_or_var(
subject: match Self::convert_ground_term_or_var(
&triple.subject,
variables,
values,
@ -581,14 +566,14 @@ impl<'a> SimpleUpdateEvaluator<'a> {
Some(OxTerm::Literal(_)) | None => return Ok(None),
},
predicate: if let Some(predicate) =
self.convert_named_node_or_var(&triple.predicate, variables, values, dataset)?
Self::convert_named_node_or_var(&triple.predicate, variables, values, dataset)?
{
predicate
} else {
return Ok(None);
},
object: if let Some(object) =
self.convert_ground_term_or_var(&triple.object, variables, values, dataset)?
Self::convert_ground_term_or_var(&triple.object, variables, values, dataset)?
{
object
} else {
@ -598,7 +583,6 @@ impl<'a> SimpleUpdateEvaluator<'a> {
}
fn lookup_variable(
&self,
v: &Variable,
variables: &[Variable],
values: &EncodedTuple,

@ -235,7 +235,7 @@ pub fn read_xml_results(source: impl BufRead + 'static) -> io::Result<QueryResul
State::Head => {
if event.name() == b"variable" {
let name = event.attributes()
.filter_map(|attr| attr.ok())
.filter_map(std::result::Result::ok)
.find(|attr| attr.key == b"name")
.ok_or_else(|| invalid_data_error("No name attribute found for the <variable> tag"))?;
variables.push(name.unescape_and_decode_value(&reader).map_err(map_xml_error)?);
@ -283,7 +283,7 @@ pub fn read_xml_results(source: impl BufRead + 'static) -> io::Result<QueryResul
State::Head => {
if event.name() == b"variable" {
let name = event.attributes()
.filter_map(|v| v.ok())
.filter_map(std::result::Result::ok)
.find(|attr| attr.key == b"name")
.ok_or_else(|| invalid_data_error("No name attribute found for the <variable> tag"))?;
variables.push(name.unescape_and_decode_value(&reader).map_err(map_xml_error)?);
@ -405,7 +405,7 @@ impl<R: BufRead> ResultsIterator<R> {
if event.name() == b"binding" {
match event
.attributes()
.filter_map(|v| v.ok())
.filter_map(std::result::Result::ok)
.find(|attr| attr.key == b"name")
{
Some(attr) => {
@ -614,7 +614,7 @@ impl<R: BufRead> ResultsIterator<R> {
);
}
}
_ => (),
State::End => (),
},
Event::Eof => return Ok(None),
_ => (),

@ -9,7 +9,7 @@ use crate::storage::StorageLike;
use std::io;
use std::io::{BufRead, Write};
pub(crate) fn load_graph<S: StorageLike>(
pub fn load_graph<S: StorageLike>(
store: &S,
reader: impl BufRead,
format: GraphFormat,
@ -49,7 +49,7 @@ pub fn dump_graph(
writer.finish()
}
pub(crate) fn load_dataset<S: StorageLike>(
pub fn load_dataset<S: StorageLike>(
store: &S,
reader: impl BufRead,
format: DatasetFormat,
@ -89,11 +89,10 @@ pub enum StoreOrParseError<S> {
Parse(io::Error),
}
impl From<StoreOrParseError<io::Error>> for io::Error {
fn from(error: StoreOrParseError<io::Error>) -> Self {
impl From<StoreOrParseError<Self>> for io::Error {
fn from(error: StoreOrParseError<Self>) -> Self {
match error {
StoreOrParseError::Store(error) => error,
StoreOrParseError::Parse(error) => error,
StoreOrParseError::Store(error) | StoreOrParseError::Parse(error) => error,
}
}
}

@ -23,9 +23,9 @@ use crate::storage::numeric_encoder::{EncodedQuad, EncodedTerm, StrHash, StrLook
use std::convert::TryInto;
mod binary_encoder;
pub(crate) mod io;
pub(crate) mod numeric_encoder;
pub(crate) mod small_string;
pub mod io;
pub mod numeric_encoder;
pub mod small_string;
/// Low level storage primitives
#[derive(Clone)]
@ -430,43 +430,42 @@ impl Storage {
}
fn spog_quads(&self, prefix: Vec<u8>) -> DecodingQuadIterator {
self.inner_quads(&self.spog, prefix, QuadEncoding::Spog)
Self::inner_quads(&self.spog, prefix, QuadEncoding::Spog)
}
fn posg_quads(&self, prefix: Vec<u8>) -> DecodingQuadIterator {
self.inner_quads(&self.posg, prefix, QuadEncoding::Posg)
Self::inner_quads(&self.posg, prefix, QuadEncoding::Posg)
}
fn ospg_quads(&self, prefix: Vec<u8>) -> DecodingQuadIterator {
self.inner_quads(&self.ospg, prefix, QuadEncoding::Ospg)
Self::inner_quads(&self.ospg, prefix, QuadEncoding::Ospg)
}
fn gspo_quads(&self, prefix: Vec<u8>) -> DecodingQuadIterator {
self.inner_quads(&self.gspo, prefix, QuadEncoding::Gspo)
Self::inner_quads(&self.gspo, prefix, QuadEncoding::Gspo)
}
fn gpos_quads(&self, prefix: Vec<u8>) -> DecodingQuadIterator {
self.inner_quads(&self.gpos, prefix, QuadEncoding::Gpos)
Self::inner_quads(&self.gpos, prefix, QuadEncoding::Gpos)
}
fn gosp_quads(&self, prefix: Vec<u8>) -> DecodingQuadIterator {
self.inner_quads(&self.gosp, prefix, QuadEncoding::Gosp)
Self::inner_quads(&self.gosp, prefix, QuadEncoding::Gosp)
}
fn dspo_quads(&self, prefix: Vec<u8>) -> DecodingQuadIterator {
self.inner_quads(&self.dspo, prefix, QuadEncoding::Dspo)
Self::inner_quads(&self.dspo, prefix, QuadEncoding::Dspo)
}
fn dpos_quads(&self, prefix: Vec<u8>) -> DecodingQuadIterator {
self.inner_quads(&self.dpos, prefix, QuadEncoding::Dpos)
Self::inner_quads(&self.dpos, prefix, QuadEncoding::Dpos)
}
fn dosp_quads(&self, prefix: Vec<u8>) -> DecodingQuadIterator {
self.inner_quads(&self.dosp, prefix, QuadEncoding::Dosp)
Self::inner_quads(&self.dosp, prefix, QuadEncoding::Dosp)
}
fn inner_quads(
&self,
tree: &Tree,
prefix: impl AsRef<[u8]>,
encoding: QuadEncoding,
@ -959,7 +958,7 @@ impl<T> From<Sled2TransactionError<T>> for TransactionError<T> {
}
}
impl<T: Into<std::io::Error>> From<TransactionError<T>> for std::io::Error {
impl<T: Into<Self>> From<TransactionError<T>> for std::io::Error {
fn from(e: TransactionError<T>) -> Self {
match e {
TransactionError::Abort(e) => e.into(),
@ -1005,8 +1004,8 @@ impl From<UnabortableTransactionError> for EvaluationError {
}
}
impl From<StoreOrParseError<UnabortableTransactionError>> for UnabortableTransactionError {
fn from(e: StoreOrParseError<UnabortableTransactionError>) -> Self {
impl From<StoreOrParseError<Self>> for UnabortableTransactionError {
fn from(e: StoreOrParseError<Self>) -> Self {
match e {
StoreOrParseError::Store(e) => e,
StoreOrParseError::Parse(e) => Self::Storage(e),
@ -1066,11 +1065,9 @@ impl<T> From<UnabortableTransactionError> for ConflictableTransactionError<T> {
impl<T> From<ConflictableTransactionError<T>> for Sled2ConflictableTransactionError<T> {
fn from(e: ConflictableTransactionError<T>) -> Self {
match e {
ConflictableTransactionError::Abort(e) => Sled2ConflictableTransactionError::Abort(e),
ConflictableTransactionError::Conflict => Sled2ConflictableTransactionError::Conflict,
ConflictableTransactionError::Storage(e) => {
Sled2ConflictableTransactionError::Storage(e.into())
}
ConflictableTransactionError::Abort(e) => Self::Abort(e),
ConflictableTransactionError::Conflict => Self::Conflict,
ConflictableTransactionError::Storage(e) => Self::Storage(e.into()),
}
}
}
@ -1163,7 +1160,7 @@ impl<'a> TermEncoder for StorageTransaction<'a> {
}
}
pub(crate) trait StorageLike: StrLookup {
pub trait StorageLike: StrLookup {
fn insert(&self, quad: QuadRef<'_>) -> Result<bool, Self::Error>;
fn remove(&self, quad: QuadRef<'_>) -> Result<bool, Self::Error>;

@ -465,20 +465,20 @@ impl From<LiteralRef<'_>> for EncodedTerm {
literal.language().map(|language| {
if let Ok(value) = SmallString::try_from(value) {
if let Ok(language) = SmallString::try_from(language) {
EncodedTerm::SmallSmallLangStringLiteral { value, language }
Self::SmallSmallLangStringLiteral { value, language }
} else {
EncodedTerm::SmallBigLangStringLiteral {
Self::SmallBigLangStringLiteral {
value,
language_id: StrHash::new(language),
}
}
} else if let Ok(language) = SmallString::try_from(language) {
EncodedTerm::BigSmallLangStringLiteral {
Self::BigSmallLangStringLiteral {
value_id: StrHash::new(value),
language,
}
} else {
EncodedTerm::BigBigLangStringLiteral {
Self::BigBigLangStringLiteral {
value_id: StrHash::new(value),
language_id: StrHash::new(language),
}
@ -489,9 +489,9 @@ impl From<LiteralRef<'_>> for EncodedTerm {
"http://www.w3.org/2001/XMLSchema#string" => {
let value = value;
Some(if let Ok(value) = SmallString::try_from(value) {
EncodedTerm::SmallStringLiteral(value)
Self::SmallStringLiteral(value)
} else {
EncodedTerm::BigStringLiteral {
Self::BigStringLiteral {
value_id: StrHash::new(value),
}
})
@ -534,12 +534,12 @@ impl From<LiteralRef<'_>> for EncodedTerm {
Some(term) => term,
None => {
if let Ok(value) = SmallString::try_from(value) {
EncodedTerm::SmallTypedLiteral {
Self::SmallTypedLiteral {
value,
datatype_id: StrHash::new(datatype),
}
} else {
EncodedTerm::BigTypedLiteral {
Self::BigTypedLiteral {
value_id: StrHash::new(value),
datatype_id: StrHash::new(datatype),
}
@ -584,14 +584,14 @@ impl From<GraphNameRef<'_>> for EncodedTerm {
match name {
GraphNameRef::NamedNode(named_node) => named_node.into(),
GraphNameRef::BlankNode(blank_node) => blank_node.into(),
GraphNameRef::DefaultGraph => EncodedTerm::DefaultGraph,
GraphNameRef::DefaultGraph => Self::DefaultGraph,
}
}
}
impl From<TripleRef<'_>> for EncodedTerm {
fn from(triple: TripleRef<'_>) -> Self {
EncodedTerm::Triple(Rc::new(triple.into()))
Self::Triple(Rc::new(triple.into()))
}
}
@ -614,7 +614,7 @@ impl EncodedTriple {
impl From<TripleRef<'_>> for EncodedTriple {
fn from(triple: TripleRef<'_>) -> Self {
EncodedTriple {
Self {
subject: triple.subject.into(),
predicate: triple.predicate.into(),
object: triple.object.into(),
@ -648,7 +648,7 @@ impl EncodedQuad {
impl From<QuadRef<'_>> for EncodedQuad {
fn from(quad: QuadRef<'_>) -> Self {
EncodedQuad {
Self {
subject: quad.subject.into(),
predicate: quad.predicate.into(),
object: quad.object.into(),
@ -723,15 +723,16 @@ pub fn insert_term_values<E, F: Fn(&StrHash, &str) -> Result<(), E> + Copy>(
(TermRef::BlankNode(node), EncodedTerm::BigBlankNode { id_id }) => {
insert_str(id_id, node.as_str())?;
}
(TermRef::Literal(literal), EncodedTerm::BigStringLiteral { value_id }) => {
insert_str(value_id, literal.value())?;
}
(TermRef::Literal(literal), EncodedTerm::SmallBigLangStringLiteral { language_id, .. }) => {
if let Some(language) = literal.language() {
insert_str(language_id, language)?;
}
}
(TermRef::Literal(literal), EncodedTerm::BigSmallLangStringLiteral { value_id, .. }) => {
(
TermRef::Literal(literal),
EncodedTerm::BigSmallLangStringLiteral { value_id, .. }
| EncodedTerm::BigStringLiteral { value_id },
) => {
insert_str(value_id, literal.value())?;
}
(
@ -784,15 +785,13 @@ pub fn remove_term_values<E, F: Fn(&StrHash) -> Result<(), E> + Copy>(
EncodedTerm::BigBlankNode { id_id } => {
remove_str(id_id)?;
}
EncodedTerm::BigStringLiteral { value_id } => {
EncodedTerm::BigStringLiteral { value_id }
| EncodedTerm::BigSmallLangStringLiteral { value_id, .. } => {
remove_str(value_id)?;
}
EncodedTerm::SmallBigLangStringLiteral { language_id, .. } => {
remove_str(language_id)?;
}
EncodedTerm::BigSmallLangStringLiteral { value_id, .. } => {
remove_str(value_id)?;
}
EncodedTerm::BigBigLangStringLiteral {
value_id,
language_id,
@ -1094,7 +1093,7 @@ impl<E: Error + 'static> Error for DecoderError<E> {
}
}
impl<E: Into<io::Error>> From<DecoderError<E>> for io::Error {
impl<E: Into<Self>> From<DecoderError<E>> for io::Error {
fn from(e: DecoderError<E>) -> Self {
match e {
DecoderError::Store(e) => e.into(),

@ -23,12 +23,12 @@ impl SmallString {
}
#[inline]
pub fn from_utf8(bytes: &[u8]) -> Result<SmallString, BadSmallStringError> {
pub fn from_utf8(bytes: &[u8]) -> Result<Self, BadSmallStringError> {
Self::from_str(str::from_utf8(bytes).map_err(BadSmallStringError::BadUtf8)?)
}
#[inline]
pub fn from_be_bytes(bytes: [u8; 16]) -> Result<SmallString, BadSmallStringError> {
pub fn from_be_bytes(bytes: [u8; 16]) -> Result<Self, BadSmallStringError> {
// We check that it is valid UTF-8
str::from_utf8(&bytes.as_ref()[..bytes[15].into()])
.map_err(BadSmallStringError::BadUtf8)?;
@ -105,7 +105,7 @@ impl fmt::Display for SmallString {
impl PartialEq for SmallString {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.as_str().eq(other.deref())
self.as_str().eq(&**other)
}
}

@ -230,7 +230,7 @@ impl Store {
) -> Result<(), EvaluationError> {
evaluate_update(
&self.storage,
update.try_into().map_err(|e| e.into())?,
update.try_into().map_err(std::convert::Into::into)?,
options,
)
}
@ -880,7 +880,7 @@ fn store() -> io::Result<()> {
Quad::new(
main_s.clone(),
main_p.clone(),
Literal::from(200000000),
Literal::from(200_000_000),
GraphName::DefaultGraph,
),
];
@ -895,7 +895,7 @@ fn store() -> io::Result<()> {
Quad::new(
main_s.clone(),
main_p.clone(),
Literal::from(200000000),
Literal::from(200_000_000),
GraphName::DefaultGraph,
),
named_quad.clone(),

@ -63,7 +63,7 @@ pub async fn main() -> Result<()> {
}?;
println!("Listening for requests at http://{}", &bind);
http_server(&bind, move |request| handle_request(request, store.clone())).await
http_server(bind, move |request| handle_request(request, store.clone())).await
}
async fn handle_request(request: Request, store: Store) -> Result<Response> {

@ -5,7 +5,7 @@ authors = ["Tpt <thomas@pellissier-tanon.fr>"]
license = "MIT OR Apache-2.0"
readme = "README.md"
keywords = ["SPARQL"]
repository = "https://github.com/oxigraph/oxigraph/tree/master/spargebra"
repository = "https://github.com/oxigraph/oxigraph/tree/v0.3/spargebra"
homepage = "https://oxigraph.org/"
description = """
A SPARQL parser

@ -9,12 +9,12 @@ use std::fmt;
#[derive(Eq, PartialEq, Debug, Clone, Hash)]
pub enum PropertyPathExpression {
NamedNode(NamedNode),
Reverse(Box<PropertyPathExpression>),
Sequence(Box<PropertyPathExpression>, Box<PropertyPathExpression>),
Alternative(Box<PropertyPathExpression>, Box<PropertyPathExpression>),
ZeroOrMore(Box<PropertyPathExpression>),
OneOrMore(Box<PropertyPathExpression>),
ZeroOrOne(Box<PropertyPathExpression>),
Reverse(Box<Self>),
Sequence(Box<Self>, Box<Self>),
Alternative(Box<Self>, Box<Self>),
ZeroOrMore(Box<Self>),
OneOrMore(Box<Self>),
ZeroOrOne(Box<Self>),
NegatedPropertySet(Vec<NamedNode>),
}
@ -75,7 +75,7 @@ impl<'a> fmt::Display for SparqlPropertyPath<'a> {
impl From<NamedNode> for PropertyPathExpression {
fn from(p: NamedNode) -> Self {
PropertyPathExpression::NamedNode(p)
Self::NamedNode(p)
}
}
@ -86,45 +86,45 @@ pub enum Expression {
Literal(Literal),
Variable(Variable),
/// [Logical-or](https://www.w3.org/TR/sparql11-query/#func-logical-or)
Or(Box<Expression>, Box<Expression>),
Or(Box<Self>, Box<Self>),
/// [Logical-and](https://www.w3.org/TR/sparql11-query/#func-logical-and)
And(Box<Expression>, Box<Expression>),
And(Box<Self>, Box<Self>),
/// [RDFterm-equal](https://www.w3.org/TR/sparql11-query/#func-RDFterm-equal) and all the XSD equalities
Equal(Box<Expression>, Box<Expression>),
Equal(Box<Self>, Box<Self>),
/// [sameTerm](https://www.w3.org/TR/sparql11-query/#func-sameTerm)
SameTerm(Box<Expression>, Box<Expression>),
SameTerm(Box<Self>, Box<Self>),
/// [op:numeric-greater-than](https://www.w3.org/TR/xpath-functions/#func-numeric-greater-than) and other XSD greater than operators
Greater(Box<Expression>, Box<Expression>),
GreaterOrEqual(Box<Expression>, Box<Expression>),
Greater(Box<Self>, Box<Self>),
GreaterOrEqual(Box<Self>, Box<Self>),
/// [op:numeric-less-than](https://www.w3.org/TR/xpath-functions/#func-numeric-less-than) and other XSD greater than operators
Less(Box<Expression>, Box<Expression>),
LessOrEqual(Box<Expression>, Box<Expression>),
Less(Box<Self>, Box<Self>),
LessOrEqual(Box<Self>, Box<Self>),
/// [IN](https://www.w3.org/TR/sparql11-query/#func-in)
In(Box<Expression>, Vec<Expression>),
In(Box<Self>, Vec<Self>),
/// [op:numeric-add](https://www.w3.org/TR/xpath-functions/#func-numeric-add) and other XSD additions
Add(Box<Expression>, Box<Expression>),
Add(Box<Self>, Box<Self>),
/// [op:numeric-subtract](https://www.w3.org/TR/xpath-functions/#func-numeric-subtract) and other XSD subtractions
Subtract(Box<Expression>, Box<Expression>),
Subtract(Box<Self>, Box<Self>),
/// [op:numeric-multiply](https://www.w3.org/TR/xpath-functions/#func-numeric-multiply) and other XSD multiplications
Multiply(Box<Expression>, Box<Expression>),
Multiply(Box<Self>, Box<Self>),
/// [op:numeric-divide](https://www.w3.org/TR/xpath-functions/#func-numeric-divide) and other XSD divides
Divide(Box<Expression>, Box<Expression>),
Divide(Box<Self>, Box<Self>),
/// [op:numeric-unary-plus](https://www.w3.org/TR/xpath-functions/#func-numeric-unary-plus) and other XSD unary plus
UnaryPlus(Box<Expression>),
UnaryPlus(Box<Self>),
/// [op:numeric-unary-minus](https://www.w3.org/TR/xpath-functions/#func-numeric-unary-minus) and other XSD unary minus
UnaryMinus(Box<Expression>),
UnaryMinus(Box<Self>),
/// [fn:not](https://www.w3.org/TR/xpath-functions/#func-not)
Not(Box<Expression>),
Not(Box<Self>),
/// [EXISTS](https://www.w3.org/TR/sparql11-query/#func-filter-exists)
Exists(Box<GraphPattern>),
/// [BOUND](https://www.w3.org/TR/sparql11-query/#func-bound)
Bound(Variable),
/// [IF](https://www.w3.org/TR/sparql11-query/#func-if)
If(Box<Expression>, Box<Expression>, Box<Expression>),
If(Box<Self>, Box<Self>, Box<Self>),
/// [COALESCE](https://www.w3.org/TR/sparql11-query/#func-coalesce)
Coalesce(Vec<Expression>),
Coalesce(Vec<Self>),
/// A regular function call
FunctionCall(Function, Vec<Expression>),
FunctionCall(Function, Vec<Self>),
}
impl fmt::Display for Expression {
@ -178,19 +178,19 @@ impl fmt::Display for Expression {
impl From<NamedNode> for Expression {
fn from(p: NamedNode) -> Self {
Expression::NamedNode(p)
Self::NamedNode(p)
}
}
impl From<Literal> for Expression {
fn from(p: Literal) -> Self {
Expression::Literal(p)
Self::Literal(p)
}
}
impl From<Variable> for Expression {
fn from(v: Variable) -> Self {
Expression::Variable(v)
Self::Variable(v)
}
}
@ -450,41 +450,29 @@ pub enum GraphPattern {
object: TermPattern,
},
/// [Join](https://www.w3.org/TR/sparql11-query/#defn_algJoin)
Join {
left: Box<GraphPattern>,
right: Box<GraphPattern>,
},
Join { left: Box<Self>, right: Box<Self> },
/// [LeftJoin](https://www.w3.org/TR/sparql11-query/#defn_algLeftJoin)
LeftJoin {
left: Box<GraphPattern>,
right: Box<GraphPattern>,
left: Box<Self>,
right: Box<Self>,
expr: Option<Expression>,
},
/// [Filter](https://www.w3.org/TR/sparql11-query/#defn_algFilter)
Filter {
expr: Expression,
inner: Box<GraphPattern>,
},
Filter { expr: Expression, inner: Box<Self> },
/// [Union](https://www.w3.org/TR/sparql11-query/#defn_algUnion)
Union {
left: Box<GraphPattern>,
right: Box<GraphPattern>,
},
Union { left: Box<Self>, right: Box<Self> },
Graph {
graph_name: NamedNodePattern,
inner: Box<GraphPattern>,
inner: Box<Self>,
},
/// [Extend](https://www.w3.org/TR/sparql11-query/#defn_extend)
Extend {
inner: Box<GraphPattern>,
inner: Box<Self>,
var: Variable,
expr: Expression,
},
/// [Minus](https://www.w3.org/TR/sparql11-query/#defn_algMinus)
Minus {
left: Box<GraphPattern>,
right: Box<GraphPattern>,
},
Minus { left: Box<Self>, right: Box<Self> },
/// A table used to provide inline values
Table {
variables: Vec<Variable>,
@ -492,34 +480,34 @@ pub enum GraphPattern {
},
/// [OrderBy](https://www.w3.org/TR/sparql11-query/#defn_algOrdered)
OrderBy {
inner: Box<GraphPattern>,
inner: Box<Self>,
condition: Vec<OrderComparator>,
},
/// [Project](https://www.w3.org/TR/sparql11-query/#defn_algProjection)
Project {
inner: Box<GraphPattern>,
inner: Box<Self>,
projection: Vec<Variable>,
},
/// [Distinct](https://www.w3.org/TR/sparql11-query/#defn_algDistinct)
Distinct { inner: Box<GraphPattern> },
Distinct { inner: Box<Self> },
/// [Reduced](https://www.w3.org/TR/sparql11-query/#defn_algReduced)
Reduced { inner: Box<GraphPattern> },
Reduced { inner: Box<Self> },
/// [Slice](https://www.w3.org/TR/sparql11-query/#defn_algSlice)
Slice {
inner: Box<GraphPattern>,
inner: Box<Self>,
start: usize,
length: Option<usize>,
},
/// [Group](https://www.w3.org/TR/sparql11-federated-query/#aggregateAlgebra)
Group {
inner: Box<GraphPattern>,
inner: Box<Self>,
by: Vec<Variable>,
aggregates: Vec<(Variable, AggregationFunction)>,
},
/// [Service](https://www.w3.org/TR/sparql11-federated-query/#defn_evalService)
Service {
name: NamedNodePattern,
pattern: Box<GraphPattern>,
pattern: Box<Self>,
silent: bool,
},
}
@ -643,7 +631,7 @@ impl fmt::Display for GraphPattern {
impl Default for GraphPattern {
fn default() -> Self {
GraphPattern::Bgp(Vec::default())
Self::Bgp(Vec::default())
}
}
@ -685,7 +673,6 @@ impl GraphPattern {
left.add_visible_variables(vars);
right.add_visible_variables(vars);
}
GraphPattern::Filter { inner, .. } => inner.add_visible_variables(vars),
GraphPattern::Graph { graph_name, inner } => {
if let NamedNodePattern::Variable(ref g) = graph_name {
vars.insert(g);
@ -706,7 +693,8 @@ impl GraphPattern {
}
GraphPattern::Table { variables, .. } => vars.extend(variables),
GraphPattern::Project { projection, .. } => vars.extend(projection.iter()),
GraphPattern::OrderBy { inner, .. }
GraphPattern::Filter { inner, .. }
| GraphPattern::OrderBy { inner, .. }
| GraphPattern::Distinct { inner }
| GraphPattern::Reduced { inner }
| GraphPattern::Slice { inner, .. } => inner.add_visible_variables(vars),

@ -126,7 +126,7 @@ enum VariableOrPropertyPath {
impl From<Variable> for VariableOrPropertyPath {
fn from(var: Variable) -> Self {
VariableOrPropertyPath::Variable(var)
Self::Variable(var)
}
}
@ -141,7 +141,7 @@ impl From<NamedNodePattern> for VariableOrPropertyPath {
impl From<PropertyPathExpression> for VariableOrPropertyPath {
fn from(path: PropertyPathExpression) -> Self {
VariableOrPropertyPath::PropertyPath(path)
Self::PropertyPath(path)
}
}
@ -287,7 +287,7 @@ enum TripleOrPathPattern {
impl From<TriplePattern> for TripleOrPathPattern {
fn from(tp: TriplePattern) -> Self {
TripleOrPathPattern::Triple(tp)
Self::Triple(tp)
}
}
@ -306,7 +306,7 @@ impl From<AnnotatedTerm> for AnnotatedTermPath {
.map(|(p, o)| {
(
p.into(),
o.into_iter().map(AnnotatedTermPath::from).collect(),
o.into_iter().map(Self::from).collect(),
)
})
.collect(),

@ -537,7 +537,7 @@ impl TryFrom<GraphNamePattern> for GraphName {
fn try_from(pattern: GraphNamePattern) -> Result<Self, ()> {
match pattern {
GraphNamePattern::NamedNode(t) => Ok(t.into()),
GraphNamePattern::DefaultGraph => Ok(GraphName::DefaultGraph),
GraphNamePattern::DefaultGraph => Ok(Self::DefaultGraph),
GraphNamePattern::Variable(_) => Err(()),
}
}
@ -1099,7 +1099,7 @@ impl TryFrom<QuadPattern> for GroundQuadPattern {
#[inline]
fn try_from(pattern: QuadPattern) -> Result<Self, ()> {
Ok(GroundQuadPattern {
Ok(Self {
subject: pattern.subject.try_into()?,
predicate: pattern.predicate,
object: pattern.object.try_into()?,

@ -95,7 +95,7 @@ pub async fn main() -> Result<()> {
}
})
.collect::<Vec<_>>();
let slot = matches.value_of("slot").clone();
let slot = matches.value_of("slot");
let store = if let Some(file) = file {
Store::open(file)
@ -105,8 +105,8 @@ pub async fn main() -> Result<()> {
let repo = store.clone();
let mut loader = WikibaseLoader::new(
repo,
&mediawiki_api,
&mediawiki_base_url,
mediawiki_api,
mediawiki_base_url,
&namespaces,
slot.as_deref(),
Duration::new(10, 0),
@ -119,7 +119,7 @@ pub async fn main() -> Result<()> {
println!("Listening for requests at http://{}", &bind);
http_server(&bind, move |request| handle_request(request, store.clone())).await
http_server(bind, move |request| handle_request(request, store.clone())).await
}
async fn handle_request(request: Request, store: Store) -> Result<Response> {

Loading…
Cancel
Save