Applies more clippy lints

pull/10/head
Tpt 6 years ago
parent fa270a220c
commit 071b3934b7
  1. 3
      clippy.toml
  2. 33
      lib/src/lib.rs
  3. 2
      lib/src/model/blank_node.rs
  4. 30
      lib/src/model/literal.rs
  5. 2
      lib/src/model/named_node.rs
  6. 16
      lib/src/rio/ntriples/mod.rs
  7. 16
      lib/src/rio/turtle/mod.rs
  8. 275
      lib/src/sparql/algebra.rs
  9. 19
      lib/src/sparql/eval.rs
  10. 4
      lib/src/sparql/mod.rs
  11. 22
      lib/src/sparql/parser.rs
  12. 46
      lib/src/sparql/plan.rs
  13. 64
      lib/src/sparql/sparql_grammar.rustpeg
  14. 13
      lib/src/sparql/xml_results.rs
  15. 8
      lib/src/store/encoded.rs
  16. 18
      lib/src/store/memory.rs
  17. 2
      lib/src/store/mod.rs
  18. 28
      lib/src/store/numeric_encoder.rs
  19. 28
      lib/src/store/rocksdb.rs
  20. 4
      lib/src/utils.rs
  21. 17
      python/src/lib.rs

@ -0,0 +1,3 @@
cyclomatic-complexity-threshold = 50
too-many-arguments-threshold = 10
type-complexity-threshold = 500

@ -1,3 +1,36 @@
#![cfg_attr(
feature = "cargo-clippy",
warn(
cast_possible_truncation,
cast_possible_wrap,
cast_precision_loss,
cast_sign_loss,
default_trait_access,
empty_enum,
enum_glob_use,
expl_impl_clone_on_copy,
explicit_into_iter_loop,
filter_map,
if_not_else,
inline_always,
invalid_upcast_comparisons,
items_after_statements,
linkedlist,
//TODO match_same_arms,
maybe_infinite_iter,
mut_mut,
needless_continue,
option_map_unwrap_or,
//TODO option_map_unwrap_or_else,
pub_enum_variant_names,
replace_consts,
result_map_unwrap_or_else,
//TODO single_match_else,
string_add_assign,
unicode_not_nfc
)
)]
extern crate byteorder; extern crate byteorder;
#[macro_use] #[macro_use]
extern crate error_chain; extern crate error_chain;

@ -32,7 +32,7 @@ impl fmt::Display for BlankNode {
impl Default for BlankNode { impl Default for BlankNode {
/// Builds a new RDF [blank node](https://www.w3.org/TR/rdf11-concepts/#dfn-blank-node) with a unique id /// Builds a new RDF [blank node](https://www.w3.org/TR/rdf11-concepts/#dfn-blank-node) with a unique id
fn default() -> Self { fn default() -> Self {
BlankNode { id: Uuid::new_v4() } Self { id: Uuid::new_v4() }
} }
} }

@ -107,16 +107,15 @@ impl Literal {
/// The literal [lexical form](https://www.w3.org/TR/rdf11-concepts/#dfn-lexical-form) /// The literal [lexical form](https://www.w3.org/TR/rdf11-concepts/#dfn-lexical-form)
pub fn value(&self) -> Cow<String> { pub fn value(&self) -> Cow<String> {
match self.0 { match self.0 {
LiteralContent::SimpleLiteral(ref value) | LiteralContent::String(ref value) => { LiteralContent::SimpleLiteral(ref value)
Cow::Borrowed(value) | LiteralContent::String(ref value)
} | LiteralContent::LanguageTaggedString { ref value, .. }
LiteralContent::LanguageTaggedString { ref value, .. } => Cow::Borrowed(value), | LiteralContent::TypedLiteral { ref value, .. } => Cow::Borrowed(value),
LiteralContent::Boolean(value) => Cow::Owned(value.to_string()), LiteralContent::Boolean(value) => Cow::Owned(value.to_string()),
LiteralContent::Float(value) => Cow::Owned(value.to_string()), LiteralContent::Float(value) => Cow::Owned(value.to_string()),
LiteralContent::Double(value) => Cow::Owned(value.to_string()), LiteralContent::Double(value) => Cow::Owned(value.to_string()),
LiteralContent::Integer(value) => Cow::Owned(value.to_string()), LiteralContent::Integer(value) => Cow::Owned(value.to_string()),
LiteralContent::Decimal(value) => Cow::Owned(value.to_string()), LiteralContent::Decimal(value) => Cow::Owned(value.to_string()),
LiteralContent::TypedLiteral { ref value, .. } => Cow::Borrowed(value),
} }
} }
@ -152,8 +151,7 @@ impl Literal {
/// or have been created by `Literal::new_simple_literal`. /// or have been created by `Literal::new_simple_literal`.
pub fn is_plain(&self) -> bool { pub fn is_plain(&self) -> bool {
match self.0 { match self.0 {
LiteralContent::SimpleLiteral(_) => true, LiteralContent::SimpleLiteral(_) | LiteralContent::LanguageTaggedString { .. } => true,
LiteralContent::LanguageTaggedString { .. } => true,
_ => false, _ => false,
} }
} }
@ -201,8 +199,7 @@ impl Literal {
/// Checks if the literal has the datatype [xsd:decimal](http://www.w3.org/2001/XMLSchema#decimal) or one of its sub datatype and is valid /// Checks if the literal has the datatype [xsd:decimal](http://www.w3.org/2001/XMLSchema#decimal) or one of its sub datatype and is valid
pub fn is_decimal(&self) -> bool { pub fn is_decimal(&self) -> bool {
match self.0 { match self.0 {
LiteralContent::Integer(_) => true, LiteralContent::Integer(_) | LiteralContent::Decimal(_) => true,
LiteralContent::Decimal(_) => true,
_ => false, _ => false,
} }
} }
@ -213,13 +210,12 @@ impl Literal {
LiteralContent::SimpleLiteral(ref value) | LiteralContent::String(ref value) => { LiteralContent::SimpleLiteral(ref value) | LiteralContent::String(ref value) => {
Some(!value.is_empty()) Some(!value.is_empty())
} }
LiteralContent::LanguageTaggedString { .. } => None,
LiteralContent::Boolean(value) => Some(value), LiteralContent::Boolean(value) => Some(value),
LiteralContent::Float(value) => Some(!value.is_zero()), LiteralContent::Float(value) => Some(!value.is_zero()),
LiteralContent::Double(value) => Some(!value.is_zero()), LiteralContent::Double(value) => Some(!value.is_zero()),
LiteralContent::Integer(value) => Some(!value.is_zero()), LiteralContent::Integer(value) => Some(!value.is_zero()),
LiteralContent::Decimal(value) => Some(!value.is_zero()), LiteralContent::Decimal(value) => Some(!value.is_zero()),
LiteralContent::TypedLiteral { .. } => None, _ => None,
} }
} }
@ -326,37 +322,37 @@ impl From<i128> for Literal {
impl From<i64> for Literal { impl From<i64> for Literal {
fn from(value: i64) -> Self { fn from(value: i64) -> Self {
Literal(LiteralContent::Integer(value as i128)) Literal(LiteralContent::Integer(value.into()))
} }
} }
impl From<i32> for Literal { impl From<i32> for Literal {
fn from(value: i32) -> Self { fn from(value: i32) -> Self {
Literal(LiteralContent::Integer(value as i128)) Literal(LiteralContent::Integer(value.into()))
} }
} }
impl From<i16> for Literal { impl From<i16> for Literal {
fn from(value: i16) -> Self { fn from(value: i16) -> Self {
Literal(LiteralContent::Integer(value as i128)) Literal(LiteralContent::Integer(value.into()))
} }
} }
impl From<u64> for Literal { impl From<u64> for Literal {
fn from(value: u64) -> Self { fn from(value: u64) -> Self {
Literal(LiteralContent::Integer(value as i128)) Literal(LiteralContent::Integer(value.into()))
} }
} }
impl From<u32> for Literal { impl From<u32> for Literal {
fn from(value: u32) -> Self { fn from(value: u32) -> Self {
Literal(LiteralContent::Integer(value as i128)) Literal(LiteralContent::Integer(value.into()))
} }
} }
impl From<u16> for Literal { impl From<u16> for Literal {
fn from(value: u16) -> Self { fn from(value: u16) -> Self {
Literal(LiteralContent::Integer(value as i128)) Literal(LiteralContent::Integer(value.into()))
} }
} }

@ -65,6 +65,6 @@ impl FromStr for NamedNode {
type Err = Error; type Err = Error;
fn from_str(s: &str) -> Result<Self> { fn from_str(s: &str) -> Result<Self> {
Ok(NamedNode::new(Url::parse(s)?)) Ok(Self::new(Url::parse(s)?))
} }
} }

@ -1,13 +1,15 @@
///Implements https://www.w3.org/TR/n-triples/ ///Implements https://www.w3.org/TR/n-triples/
mod grammar { mod grammar {
#![allow(unknown_lints)] #![cfg_attr(
#![allow( feature = "cargo-clippy",
suspicious_else_formatting, allow(
len_zero, suspicious_else_formatting,
single_match, len_zero,
unit_arg, single_match,
naive_bytecount unit_arg,
naive_bytecount
)
)] )]
use rio::utils::unescape_characters; use rio::utils::unescape_characters;

@ -1,13 +1,15 @@
/// Implements https://www.w3.org/TR/turtle/ /// Implements https://www.w3.org/TR/turtle/
mod grammar { mod grammar {
#![allow(unknown_lints)] #![cfg_attr(
#![allow( feature = "cargo-clippy",
suspicious_else_formatting, allow(
len_zero, suspicious_else_formatting,
single_match, len_zero,
unit_arg, single_match,
naive_bytecount unit_arg,
naive_bytecount
)
)] )]
use model::*; use model::*;

@ -181,7 +181,7 @@ impl StaticBindings {
impl Default for StaticBindings { impl Default for StaticBindings {
fn default() -> Self { fn default() -> Self {
StaticBindings { Self {
variables: Vec::default(), variables: Vec::default(),
values: Vec::default(), values: Vec::default(),
} }
@ -401,24 +401,24 @@ impl<'a> fmt::Display for SparqlTripleOrPathPattern<'a> {
#[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Clone, Hash)] #[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Clone, Hash)]
pub enum Expression { pub enum Expression {
ConstantExpression(TermOrVariable), Constant(TermOrVariable),
OrExpression(Box<Expression>, Box<Expression>), Or(Box<Expression>, Box<Expression>),
AndExpression(Box<Expression>, Box<Expression>), And(Box<Expression>, Box<Expression>),
EqualExpression(Box<Expression>, Box<Expression>), Equal(Box<Expression>, Box<Expression>),
NotEqualExpression(Box<Expression>, Box<Expression>), NotEqual(Box<Expression>, Box<Expression>),
GreaterExpression(Box<Expression>, Box<Expression>), Greater(Box<Expression>, Box<Expression>),
GreaterOrEqExpression(Box<Expression>, Box<Expression>), GreaterOrEq(Box<Expression>, Box<Expression>),
LowerExpression(Box<Expression>, Box<Expression>), Lower(Box<Expression>, Box<Expression>),
LowerOrEqExpression(Box<Expression>, Box<Expression>), LowerOrEq(Box<Expression>, Box<Expression>),
InExpression(Box<Expression>, Vec<Expression>), In(Box<Expression>, Vec<Expression>),
NotInExpression(Box<Expression>, Vec<Expression>), NotIn(Box<Expression>, Vec<Expression>),
AddExpression(Box<Expression>, Box<Expression>), Add(Box<Expression>, Box<Expression>),
SubExpression(Box<Expression>, Box<Expression>), Sub(Box<Expression>, Box<Expression>),
MulExpression(Box<Expression>, Box<Expression>), Mul(Box<Expression>, Box<Expression>),
DivExpression(Box<Expression>, Box<Expression>), Div(Box<Expression>, Box<Expression>),
UnaryPlusExpression(Box<Expression>), UnaryPlus(Box<Expression>),
UnaryMinusExpression(Box<Expression>), UnaryMinus(Box<Expression>),
UnaryNotExpression(Box<Expression>), UnaryNot(Box<Expression>),
StrFunctionCall(Box<Expression>), StrFunctionCall(Box<Expression>),
LangFunctionCall(Box<Expression>), LangFunctionCall(Box<Expression>),
LangMatchesFunctionCall(Box<Expression>, Box<Expression>), LangMatchesFunctionCall(Box<Expression>, Box<Expression>),
@ -480,16 +480,16 @@ pub enum Expression {
impl fmt::Display for Expression { impl fmt::Display for Expression {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match self {
Expression::ConstantExpression(t) => write!(f, "{}", t), Expression::Constant(t) => write!(f, "{}", t),
Expression::OrExpression(a, b) => write!(f, "({} || {})", a, b), Expression::Or(a, b) => write!(f, "({} || {})", a, b),
Expression::AndExpression(a, b) => write!(f, "({} && {})", a, b), Expression::And(a, b) => write!(f, "({} && {})", a, b),
Expression::EqualExpression(a, b) => write!(f, "({} = {})", a, b), Expression::Equal(a, b) => write!(f, "({} = {})", a, b),
Expression::NotEqualExpression(a, b) => write!(f, "({} != {})", a, b), Expression::NotEqual(a, b) => write!(f, "({} != {})", a, b),
Expression::GreaterExpression(a, b) => write!(f, "({} > {})", a, b), Expression::Greater(a, b) => write!(f, "({} > {})", a, b),
Expression::GreaterOrEqExpression(a, b) => write!(f, "({} >= {})", a, b), Expression::GreaterOrEq(a, b) => write!(f, "({} >= {})", a, b),
Expression::LowerExpression(a, b) => write!(f, "({} < {})", a, b), Expression::Lower(a, b) => write!(f, "({} < {})", a, b),
Expression::LowerOrEqExpression(a, b) => write!(f, "({} <= {})", a, b), Expression::LowerOrEq(a, b) => write!(f, "({} <= {})", a, b),
Expression::InExpression(a, b) => write!( Expression::In(a, b) => write!(
f, f,
"({} IN ({}))", "({} IN ({}))",
a, a,
@ -498,7 +498,7 @@ impl fmt::Display for Expression {
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(", ") .join(", ")
), ),
Expression::NotInExpression(a, b) => write!( Expression::NotIn(a, b) => write!(
f, f,
"({} NOT IN ({}))", "({} NOT IN ({}))",
a, a,
@ -507,13 +507,13 @@ impl fmt::Display for Expression {
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(", ") .join(", ")
), ),
Expression::AddExpression(a, b) => write!(f, "{} + {}", a, b), Expression::Add(a, b) => write!(f, "{} + {}", a, b),
Expression::SubExpression(a, b) => write!(f, "{} - {}", a, b), Expression::Sub(a, b) => write!(f, "{} - {}", a, b),
Expression::MulExpression(a, b) => write!(f, "{} * {}", a, b), Expression::Mul(a, b) => write!(f, "{} * {}", a, b),
Expression::DivExpression(a, b) => write!(f, "{} / {}", a, b), Expression::Div(a, b) => write!(f, "{} / {}", a, b),
Expression::UnaryPlusExpression(e) => write!(f, "+{}", e), Expression::UnaryPlus(e) => write!(f, "+{}", e),
Expression::UnaryMinusExpression(e) => write!(f, "-{}", e), Expression::UnaryMinus(e) => write!(f, "-{}", e),
Expression::UnaryNotExpression(e) => write!(f, "!{}", e), Expression::UnaryNot(e) => write!(f, "!{}", e),
Expression::StrFunctionCall(e) => write!(f, "STR({})", e), Expression::StrFunctionCall(e) => write!(f, "STR({})", e),
Expression::LangFunctionCall(e) => write!(f, "LANG({})", e), Expression::LangFunctionCall(e) => write!(f, "LANG({})", e),
Expression::LangMatchesFunctionCall(a, b) => write!(f, "LANGMATCHES({}, {})", a, b), Expression::LangMatchesFunctionCall(a, b) => write!(f, "LANGMATCHES({}, {})", a, b),
@ -542,10 +542,14 @@ impl fmt::Display for Expression {
.map(|cv| write!(f, "SUBSTR({}, {}, {})", a, b, cv)) .map(|cv| write!(f, "SUBSTR({}, {}, {})", a, b, cv))
.unwrap_or_else(|| write!(f, "SUBSTR({}, {})", a, b)), .unwrap_or_else(|| write!(f, "SUBSTR({}, {})", a, b)),
Expression::StrLenFunctionCall(e) => write!(f, "STRLEN({})", e), Expression::StrLenFunctionCall(e) => write!(f, "STRLEN({})", e),
Expression::ReplaceFunctionCall(a, b, c, d) => d Expression::ReplaceFunctionCall(arg, pattern, replacement, flags) => match flags {
.as_ref() Some(flags) => write!(
.map(|dv| write!(f, "REPLACE({}, {}, {}, {})", a, b, c, dv)) f,
.unwrap_or_else(|| write!(f, "REPLACE({}, {}, {})", a, b, c)), "REPLACE({}, {}, {}, {})",
arg, pattern, replacement, flags
),
None => write!(f, "REPLACE({}, {}, {})", arg, pattern, replacement),
},
Expression::UCaseFunctionCall(e) => write!(f, "UCASE({})", e), Expression::UCaseFunctionCall(e) => write!(f, "UCASE({})", e),
Expression::LCaseFunctionCall(e) => write!(f, "LCASE({})", e), Expression::LCaseFunctionCall(e) => write!(f, "LCASE({})", e),
Expression::EncodeForURIFunctionCall(e) => write!(f, "ENCODE_FOR_URI({})", e), Expression::EncodeForURIFunctionCall(e) => write!(f, "ENCODE_FOR_URI({})", e),
@ -585,10 +589,10 @@ impl fmt::Display for Expression {
Expression::IsBlankFunctionCall(e) => write!(f, "isBLANK({})", e), Expression::IsBlankFunctionCall(e) => write!(f, "isBLANK({})", e),
Expression::IsLiteralFunctionCall(e) => write!(f, "isLITERAL({})", e), Expression::IsLiteralFunctionCall(e) => write!(f, "isLITERAL({})", e),
Expression::IsNumericFunctionCall(e) => write!(f, "isNUMERIC({})", e), Expression::IsNumericFunctionCall(e) => write!(f, "isNUMERIC({})", e),
Expression::RegexFunctionCall(a, b, c) => c Expression::RegexFunctionCall(text, pattern, flags) => match flags {
.as_ref() Some(flags) => write!(f, "REGEX({}, {}, {})", text, pattern, flags),
.map(|cv| write!(f, "REGEX({}, {}, {})", a, b, cv)) None => write!(f, "REGEX({}, {})", text, pattern),
.unwrap_or_else(|| write!(f, "REGEX({}, {})", a, b)), },
Expression::CustomFunctionCall(iri, args) => write!( Expression::CustomFunctionCall(iri, args) => write!(
f, f,
"{}({})", "{}({})",
@ -605,19 +609,19 @@ impl fmt::Display for Expression {
impl From<NamedNode> for Expression { impl From<NamedNode> for Expression {
fn from(p: NamedNode) -> Self { fn from(p: NamedNode) -> Self {
Expression::ConstantExpression(p.into()) Expression::Constant(p.into())
} }
} }
impl From<Literal> for Expression { impl From<Literal> for Expression {
fn from(p: Literal) -> Self { fn from(p: Literal) -> Self {
Expression::ConstantExpression(p.into()) Expression::Constant(p.into())
} }
} }
impl From<Variable> for Expression { impl From<Variable> for Expression {
fn from(v: Variable) -> Self { fn from(v: Variable) -> Self {
Expression::ConstantExpression(v.into()) Expression::Constant(v.into())
} }
} }
@ -626,47 +630,47 @@ struct SparqlExpression<'a>(&'a Expression);
impl<'a> fmt::Display for SparqlExpression<'a> { impl<'a> fmt::Display for SparqlExpression<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.0 { match self.0 {
Expression::ConstantExpression(t) => write!(f, "{}", t), Expression::Constant(t) => write!(f, "{}", t),
Expression::OrExpression(a, b) => write!( Expression::Or(a, b) => write!(
f, f,
"({} || {})", "({} || {})",
SparqlExpression(&*a), SparqlExpression(&*a),
SparqlExpression(&*b) SparqlExpression(&*b)
), ),
Expression::AndExpression(a, b) => write!( Expression::And(a, b) => write!(
f, f,
"({} && {})", "({} && {})",
SparqlExpression(&*a), SparqlExpression(&*a),
SparqlExpression(&*b) SparqlExpression(&*b)
), ),
Expression::EqualExpression(a, b) => { Expression::Equal(a, b) => {
write!(f, "({} = {})", SparqlExpression(&*a), SparqlExpression(&*b)) write!(f, "({} = {})", SparqlExpression(&*a), SparqlExpression(&*b))
} }
Expression::NotEqualExpression(a, b) => write!( Expression::NotEqual(a, b) => write!(
f, f,
"({} != {})", "({} != {})",
SparqlExpression(&*a), SparqlExpression(&*a),
SparqlExpression(&*b) SparqlExpression(&*b)
), ),
Expression::GreaterExpression(a, b) => { Expression::Greater(a, b) => {
write!(f, "({} > {})", SparqlExpression(&*a), SparqlExpression(&*b)) write!(f, "({} > {})", SparqlExpression(&*a), SparqlExpression(&*b))
} }
Expression::GreaterOrEqExpression(a, b) => write!( Expression::GreaterOrEq(a, b) => write!(
f, f,
"({} >= {})", "({} >= {})",
SparqlExpression(&*a), SparqlExpression(&*a),
SparqlExpression(&*b) SparqlExpression(&*b)
), ),
Expression::LowerExpression(a, b) => { Expression::Lower(a, b) => {
write!(f, "({} < {})", SparqlExpression(&*a), SparqlExpression(&*b)) write!(f, "({} < {})", SparqlExpression(&*a), SparqlExpression(&*b))
} }
Expression::LowerOrEqExpression(a, b) => write!( Expression::LowerOrEq(a, b) => write!(
f, f,
"({} <= {})", "({} <= {})",
SparqlExpression(&*a), SparqlExpression(&*a),
SparqlExpression(&*b) SparqlExpression(&*b)
), ),
Expression::InExpression(a, b) => write!( Expression::In(a, b) => write!(
f, f,
"({} IN ({}))", "({} IN ({}))",
a, a,
@ -675,7 +679,7 @@ impl<'a> fmt::Display for SparqlExpression<'a> {
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(", ") .join(", ")
), ),
Expression::NotInExpression(a, b) => write!( Expression::NotIn(a, b) => write!(
f, f,
"({} NOT IN ({}))", "({} NOT IN ({}))",
a, a,
@ -684,21 +688,21 @@ impl<'a> fmt::Display for SparqlExpression<'a> {
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(", ") .join(", ")
), ),
Expression::AddExpression(a, b) => { Expression::Add(a, b) => {
write!(f, "{} + {}", SparqlExpression(&*a), SparqlExpression(&*b)) write!(f, "{} + {}", SparqlExpression(&*a), SparqlExpression(&*b))
} }
Expression::SubExpression(a, b) => { Expression::Sub(a, b) => {
write!(f, "{} - {}", SparqlExpression(&*a), SparqlExpression(&*b)) write!(f, "{} - {}", SparqlExpression(&*a), SparqlExpression(&*b))
} }
Expression::MulExpression(a, b) => { Expression::Mul(a, b) => {
write!(f, "{} * {}", SparqlExpression(&*a), SparqlExpression(&*b)) write!(f, "{} * {}", SparqlExpression(&*a), SparqlExpression(&*b))
} }
Expression::DivExpression(a, b) => { Expression::Div(a, b) => {
write!(f, "{} / {}", SparqlExpression(&*a), SparqlExpression(&*b)) write!(f, "{} / {}", SparqlExpression(&*a), SparqlExpression(&*b))
} }
Expression::UnaryPlusExpression(e) => write!(f, "+{}", SparqlExpression(&*e)), Expression::UnaryPlus(e) => write!(f, "+{}", SparqlExpression(&*e)),
Expression::UnaryMinusExpression(e) => write!(f, "-{}", SparqlExpression(&*e)), Expression::UnaryMinus(e) => write!(f, "-{}", SparqlExpression(&*e)),
Expression::UnaryNotExpression(e) => match e.as_ref() { Expression::UnaryNot(e) => match e.as_ref() {
Expression::ExistsFunctionCall(p) => { Expression::ExistsFunctionCall(p) => {
write!(f, "NOT EXISTS {{ {} }}", SparqlGraphPattern(&*p)) write!(f, "NOT EXISTS {{ {} }}", SparqlGraphPattern(&*p))
} }
@ -751,26 +755,23 @@ impl<'a> fmt::Display for SparqlExpression<'a> {
) )
}), }),
Expression::StrLenFunctionCall(e) => write!(f, "STRLEN({})", SparqlExpression(&*e)), Expression::StrLenFunctionCall(e) => write!(f, "STRLEN({})", SparqlExpression(&*e)),
Expression::ReplaceFunctionCall(a, b, c, d) => d Expression::ReplaceFunctionCall(arg, pattern, replacement, flags) => match flags {
.as_ref() Some(flags) => write!(
.map(|dv| { f,
write!( "REPLACE({}, {}, {}, {})",
f, SparqlExpression(&*arg),
"REPLACE({}, {}, {}, {})", SparqlExpression(&*pattern),
SparqlExpression(&*a), SparqlExpression(&*replacement),
SparqlExpression(&*b), flags
SparqlExpression(&*c), ),
dv None => write!(
) f,
}).unwrap_or_else(|| { "REPLACE({}, {}, {})",
write!( SparqlExpression(&*arg),
f, SparqlExpression(&*pattern),
"REPLACE({}, {}, {})", SparqlExpression(&*replacement)
SparqlExpression(&*a), ),
SparqlExpression(&*b), },
SparqlExpression(&*c)
)
}),
Expression::UCaseFunctionCall(e) => write!(f, "UCASE({})", SparqlExpression(&*e)), Expression::UCaseFunctionCall(e) => write!(f, "UCASE({})", SparqlExpression(&*e)),
Expression::LCaseFunctionCall(e) => write!(f, "LCASE({})", SparqlExpression(&*e)), Expression::LCaseFunctionCall(e) => write!(f, "LCASE({})", SparqlExpression(&*e)),
Expression::EncodeForURIFunctionCall(e) => { Expression::EncodeForURIFunctionCall(e) => {
@ -862,24 +863,21 @@ impl<'a> fmt::Display for SparqlExpression<'a> {
Expression::IsNumericFunctionCall(e) => { Expression::IsNumericFunctionCall(e) => {
write!(f, "isNUMERIC({})", SparqlExpression(&*e)) write!(f, "isNUMERIC({})", SparqlExpression(&*e))
} }
Expression::RegexFunctionCall(a, b, c) => c Expression::RegexFunctionCall(text, pattern, flags) => match flags {
.as_ref() Some(flags) => write!(
.map(|cv| { f,
write!( "REGEX({}, {}, {})",
f, SparqlExpression(&*text),
"REGEX({}, {}, {})", SparqlExpression(&*pattern),
SparqlExpression(&*a), flags
SparqlExpression(&*b), ),
cv None => write!(
) f,
}).unwrap_or_else(|| { "REGEX({}, {})",
write!( SparqlExpression(&*text),
f, SparqlExpression(&*pattern)
"REGEX({}, {})", ),
SparqlExpression(&*a), },
SparqlExpression(&*b)
)
}),
Expression::CustomFunctionCall(iri, args) => write!( Expression::CustomFunctionCall(iri, args) => write!(
f, f,
"{}({})", "{}({})",
@ -1361,13 +1359,15 @@ impl<'a> fmt::Display for SparqlAggregation<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.0 { match self.0 {
Aggregation::Count(e, distinct) => if *distinct { Aggregation::Count(e, distinct) => if *distinct {
e.as_ref() if let Some(e) = e {
.map(|ex| write!(f, "COUNT(DISTINCT {})", SparqlExpression(ex))) write!(f, "COUNT(DISTINCT {})", SparqlExpression(e))
.unwrap_or_else(|| write!(f, "COUNT(DISTINCT *)")) } else {
write!(f, "COUNT(DISTINCT *)")
}
} else if let Some(e) = e {
write!(f, "COUNT({})", SparqlExpression(e))
} else { } else {
e.as_ref() write!(f, "COUNT(*)")
.map(|ex| write!(f, "COUNT({})", SparqlExpression(ex)))
.unwrap_or_else(|| write!(f, "COUNT(*)"))
}, },
Aggregation::Sum(e, distinct) => if *distinct { Aggregation::Sum(e, distinct) => if *distinct {
write!(f, "SUM(DISTINCT {})", SparqlExpression(e)) write!(f, "SUM(DISTINCT {})", SparqlExpression(e))
@ -1395,26 +1395,25 @@ impl<'a> fmt::Display for SparqlAggregation<'a> {
write!(f, "SAMPLE({})", SparqlExpression(e)) write!(f, "SAMPLE({})", SparqlExpression(e))
}, },
Aggregation::GroupConcat(e, distinct, sep) => if *distinct { Aggregation::GroupConcat(e, distinct, sep) => if *distinct {
sep.as_ref() if let Some(sep) = sep {
.map(|s| { write!(
write!( f,
f, "GROUP_CONCAT(DISTINCT {}; SEPARATOR = \"{}\")",
"GROUP_CONCAT(DISTINCT {}; SEPARATOR = \"{}\")", SparqlExpression(e),
SparqlExpression(e), sep.escape()
s.escape() )
) } else {
}) write!(f, "GROUP_CONCAT(DISTINCT {})", SparqlExpression(e))
.unwrap_or_else(|| write!(f, "GROUP_CONCAT(DISTINCT {})", SparqlExpression(e))) }
} else if let Some(sep) = sep {
write!(
f,
"GROUP_CONCAT({}; SEPARATOR = \"{}\")",
SparqlExpression(e),
sep.escape()
)
} else { } else {
sep.as_ref() write!(f, "GROUP_CONCAT({})", SparqlExpression(e))
.map(|s| {
write!(
f,
"GROUP_CONCAT({}; SEPARATOR = \"{}\")",
SparqlExpression(e),
s.escape()
)
}).unwrap_or_else(|| write!(f, "GROUP_CONCAT({})", SparqlExpression(e)))
}, },
} }
} }
@ -1477,7 +1476,7 @@ impl DatasetSpec {
impl Add for DatasetSpec { impl Add for DatasetSpec {
type Output = Self; type Output = Self;
fn add(mut self, rhs: DatasetSpec) -> Self { fn add(mut self, rhs: Self) -> Self {
self.default.extend_from_slice(&rhs.default); self.default.extend_from_slice(&rhs.default);
self.named.extend_from_slice(&rhs.named); self.named.extend_from_slice(&rhs.named);
self self
@ -1502,20 +1501,20 @@ lazy_static! {
#[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Clone, Hash)] #[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Clone, Hash)]
pub enum Query { pub enum Query {
SelectQuery { Select {
dataset: DatasetSpec, dataset: DatasetSpec,
algebra: GraphPattern, algebra: GraphPattern,
}, },
ConstructQuery { Construct {
construct: Vec<TriplePattern>, construct: Vec<TriplePattern>,
dataset: DatasetSpec, dataset: DatasetSpec,
algebra: GraphPattern, algebra: GraphPattern,
}, },
DescribeQuery { Describe {
dataset: DatasetSpec, dataset: DatasetSpec,
algebra: GraphPattern, algebra: GraphPattern,
}, },
AskQuery { Ask {
dataset: DatasetSpec, dataset: DatasetSpec,
algebra: GraphPattern, algebra: GraphPattern,
}, },
@ -1524,7 +1523,7 @@ pub enum Query {
impl fmt::Display for Query { impl fmt::Display for Query {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match self {
Query::SelectQuery { dataset, algebra } => write!( Query::Select { dataset, algebra } => write!(
f, f,
"{}", "{}",
SparqlGraphRootPattern { SparqlGraphRootPattern {
@ -1532,7 +1531,7 @@ impl fmt::Display for Query {
dataset: &dataset dataset: &dataset
} }
), ),
Query::ConstructQuery { Query::Construct {
construct, construct,
dataset, dataset,
algebra, algebra,
@ -1550,7 +1549,7 @@ impl fmt::Display for Query {
dataset: &EMPTY_DATASET dataset: &EMPTY_DATASET
} }
), ),
Query::DescribeQuery { dataset, algebra } => write!( Query::Describe { dataset, algebra } => write!(
f, f,
"DESCRIBE * {} WHERE {{ {} }}", "DESCRIBE * {} WHERE {{ {} }}",
dataset, dataset,
@ -1559,7 +1558,7 @@ impl fmt::Display for Query {
dataset: &EMPTY_DATASET dataset: &EMPTY_DATASET
} }
), ),
Query::AskQuery { dataset, algebra } => write!( Query::Ask { dataset, algebra } => write!(
f, f,
"ASK {} WHERE {{ {} }}", "ASK {} WHERE {{ {} }}",
dataset, dataset,

@ -8,8 +8,8 @@ use std::collections::HashSet;
use std::iter::once; use std::iter::once;
use std::iter::Iterator; use std::iter::Iterator;
use std::sync::Arc; use std::sync::Arc;
use store::encoded::EncodedQuadsStore;
use store::numeric_encoder::*; use store::numeric_encoder::*;
use store::store::EncodedQuadsStore;
use Result; use Result;
type EncodedTuplesIterator = Box<dyn Iterator<Item = Result<EncodedTuple>>>; type EncodedTuplesIterator = Box<dyn Iterator<Item = Result<EncodedTuple>>>;
@ -33,7 +33,7 @@ impl<S: EncodedQuadsStore> SimpleEvaluator<S> {
pub fn evaluate(&self, query: &Query) -> Result<QueryResult> { pub fn evaluate(&self, query: &Query) -> Result<QueryResult> {
match query { match query {
Query::SelectQuery { algebra, dataset } => { Query::Select { algebra, dataset } => {
let (plan, variables) = PlanBuilder::build(&*self.store, algebra)?; let (plan, variables) = PlanBuilder::build(&*self.store, algebra)?;
let iter = self.eval_plan(plan, vec![None; variables.len()]); let iter = self.eval_plan(plan, vec![None; variables.len()]);
Ok(QueryResult::Bindings(self.decode_bindings(iter, variables))) Ok(QueryResult::Bindings(self.decode_bindings(iter, variables)))
@ -300,10 +300,8 @@ impl<S: EncodedQuadsStore> SimpleEvaluator<S> {
PlanExpression::Bound(v) => Some((*v >= tuple.len() && tuple[*v].is_some()).into()), PlanExpression::Bound(v) => Some((*v >= tuple.len() && tuple[*v].is_some()).into()),
PlanExpression::IRI(e) => match self.eval_expression(e, tuple)? { PlanExpression::IRI(e) => match self.eval_expression(e, tuple)? {
EncodedTerm::NamedNode { iri_id } => Some(EncodedTerm::NamedNode { iri_id }), EncodedTerm::NamedNode { iri_id } => Some(EncodedTerm::NamedNode { iri_id }),
EncodedTerm::SimpleLiteral { value_id } => { EncodedTerm::SimpleLiteral { value_id }
Some(EncodedTerm::NamedNode { iri_id: value_id }) | EncodedTerm::StringLiteral { value_id } => {
}
EncodedTerm::StringLiteral { value_id } => {
Some(EncodedTerm::NamedNode { iri_id: value_id }) Some(EncodedTerm::NamedNode { iri_id: value_id })
} }
_ => None, _ => None,
@ -346,11 +344,10 @@ impl<S: EncodedQuadsStore> SimpleEvaluator<S> {
fn to_string_id(&self, term: EncodedTerm) -> Option<u64> { fn to_string_id(&self, term: EncodedTerm) -> Option<u64> {
match term { match term {
EncodedTerm::NamedNode { iri_id } => Some(iri_id), EncodedTerm::NamedNode { iri_id } => Some(iri_id),
EncodedTerm::SimpleLiteral { value_id } | EncodedTerm::StringLiteral { value_id } => { EncodedTerm::SimpleLiteral { value_id }
Some(value_id) | EncodedTerm::StringLiteral { value_id }
} | EncodedTerm::LangStringLiteral { value_id, .. }
EncodedTerm::LangStringLiteral { value_id, .. } => Some(value_id), | EncodedTerm::TypedLiteral { value_id, .. } => Some(value_id),
EncodedTerm::TypedLiteral { value_id, .. } => Some(value_id),
EncodedTerm::BooleanLiteral(value) => self EncodedTerm::BooleanLiteral(value) => self
.store .store
.insert_bytes(if value { b"true" } else { b"false" }) .insert_bytes(if value { b"true" } else { b"false" })

@ -6,8 +6,8 @@ use sparql::algebra::QueryResult;
use sparql::eval::SimpleEvaluator; use sparql::eval::SimpleEvaluator;
use sparql::parser::read_sparql_query; use sparql::parser::read_sparql_query;
use std::io::Read; use std::io::Read;
use store::store::EncodedQuadsStore; use store::encoded::EncodedQuadsStore;
use store::store::StoreDataset; use store::encoded::StoreDataset;
use Result; use Result;
pub mod algebra; pub mod algebra;

@ -1,14 +1,16 @@
mod grammar { mod grammar {
#![allow(unknown_lints)] #![cfg_attr(
#![allow( feature = "cargo-clippy",
suspicious_else_formatting, allow(
len_zero, suspicious_else_formatting,
single_match, len_zero,
unit_arg, single_match,
naive_bytecount, unit_arg,
cyclomatic_complexity, naive_bytecount,
many_single_char_names, cyclomatic_complexity,
type_complexity many_single_char_names,
type_complexity
)
)] )]
use model::*; use model::*;

@ -1,7 +1,7 @@
use model::vocab::xsd; use model::vocab::xsd;
use sparql::algebra::*; use sparql::algebra::*;
use store::encoded::EncodedQuadsStore;
use store::numeric_encoder::EncodedTerm; use store::numeric_encoder::EncodedTerm;
use store::store::EncodedQuadsStore;
use Result; use Result;
pub type EncodedTuple = Vec<Option<EncodedTerm>>; pub type EncodedTuple = Vec<Option<EncodedTerm>>;
@ -293,67 +293,67 @@ impl<'a, S: EncodedQuadsStore> PlanBuilder<'a, S> {
variables: &mut Vec<Variable>, variables: &mut Vec<Variable>,
) -> Result<PlanExpression> { ) -> Result<PlanExpression> {
Ok(match expression { Ok(match expression {
Expression::ConstantExpression(t) => match t { Expression::Constant(t) => match t {
TermOrVariable::Term(t) => { TermOrVariable::Term(t) => {
PlanExpression::Constant(self.store.encoder().encode_term(t)?) PlanExpression::Constant(self.store.encoder().encode_term(t)?)
} }
TermOrVariable::Variable(v) => PlanExpression::Variable(variable_key(variables, v)), TermOrVariable::Variable(v) => PlanExpression::Variable(variable_key(variables, v)),
}, },
Expression::OrExpression(a, b) => PlanExpression::Or( Expression::Or(a, b) => PlanExpression::Or(
Box::new(self.build_for_expression(a, variables)?), Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?), Box::new(self.build_for_expression(b, variables)?),
), ),
Expression::AndExpression(a, b) => PlanExpression::And( Expression::And(a, b) => PlanExpression::And(
Box::new(self.build_for_expression(a, variables)?), Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?), Box::new(self.build_for_expression(b, variables)?),
), ),
Expression::EqualExpression(a, b) => PlanExpression::Equal( Expression::Equal(a, b) => PlanExpression::Equal(
Box::new(self.build_for_expression(a, variables)?), Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?), Box::new(self.build_for_expression(b, variables)?),
), ),
Expression::NotEqualExpression(a, b) => PlanExpression::NotEqual( Expression::NotEqual(a, b) => PlanExpression::NotEqual(
Box::new(self.build_for_expression(a, variables)?), Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?), Box::new(self.build_for_expression(b, variables)?),
), ),
Expression::GreaterExpression(a, b) => PlanExpression::Greater( Expression::Greater(a, b) => PlanExpression::Greater(
Box::new(self.build_for_expression(a, variables)?), Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?), Box::new(self.build_for_expression(b, variables)?),
), ),
Expression::GreaterOrEqExpression(a, b) => PlanExpression::GreaterOrEq( Expression::GreaterOrEq(a, b) => PlanExpression::GreaterOrEq(
Box::new(self.build_for_expression(a, variables)?), Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?), Box::new(self.build_for_expression(b, variables)?),
), ),
Expression::LowerExpression(a, b) => PlanExpression::Lower( Expression::Lower(a, b) => PlanExpression::Lower(
Box::new(self.build_for_expression(a, variables)?), Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?), Box::new(self.build_for_expression(b, variables)?),
), ),
Expression::LowerOrEqExpression(a, b) => PlanExpression::LowerOrEq( Expression::LowerOrEq(a, b) => PlanExpression::LowerOrEq(
Box::new(self.build_for_expression(a, variables)?), Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?), Box::new(self.build_for_expression(b, variables)?),
), ),
Expression::AddExpression(a, b) => PlanExpression::Add( Expression::Add(a, b) => PlanExpression::Add(
Box::new(self.build_for_expression(a, variables)?), Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?), Box::new(self.build_for_expression(b, variables)?),
), ),
Expression::SubExpression(a, b) => PlanExpression::Sub( Expression::Sub(a, b) => PlanExpression::Sub(
Box::new(self.build_for_expression(a, variables)?), Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?), Box::new(self.build_for_expression(b, variables)?),
), ),
Expression::MulExpression(a, b) => PlanExpression::Mul( Expression::Mul(a, b) => PlanExpression::Mul(
Box::new(self.build_for_expression(a, variables)?), Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?), Box::new(self.build_for_expression(b, variables)?),
), ),
Expression::DivExpression(a, b) => PlanExpression::Div( Expression::Div(a, b) => PlanExpression::Div(
Box::new(self.build_for_expression(a, variables)?), Box::new(self.build_for_expression(a, variables)?),
Box::new(self.build_for_expression(b, variables)?), Box::new(self.build_for_expression(b, variables)?),
), ),
Expression::UnaryPlusExpression(e) => { Expression::UnaryPlus(e) => {
PlanExpression::UnaryPlus(Box::new(self.build_for_expression(e, variables)?)) PlanExpression::UnaryPlus(Box::new(self.build_for_expression(e, variables)?))
} }
Expression::UnaryMinusExpression(e) => { Expression::UnaryMinus(e) => {
PlanExpression::UnaryMinus(Box::new(self.build_for_expression(e, variables)?)) PlanExpression::UnaryMinus(Box::new(self.build_for_expression(e, variables)?))
} }
Expression::UnaryNotExpression(e) => { Expression::UnaryNot(e) => {
PlanExpression::UnaryNot(Box::new(self.build_for_expression(e, variables)?)) PlanExpression::UnaryNot(Box::new(self.build_for_expression(e, variables)?))
} }
Expression::StrFunctionCall(e) => { Expression::StrFunctionCall(e) => {
@ -393,11 +393,11 @@ impl<'a, S: EncodedQuadsStore> PlanBuilder<'a, S> {
Expression::IsNumericFunctionCall(e) => { Expression::IsNumericFunctionCall(e) => {
PlanExpression::IsNumeric(Box::new(self.build_for_expression(e, variables)?)) PlanExpression::IsNumeric(Box::new(self.build_for_expression(e, variables)?))
} }
Expression::RegexFunctionCall(a, b, c) => PlanExpression::Regex( Expression::RegexFunctionCall(text, pattern, flags) => PlanExpression::Regex(
Box::new(self.build_for_expression(a, variables)?), Box::new(self.build_for_expression(text, variables)?),
Box::new(self.build_for_expression(b, variables)?), Box::new(self.build_for_expression(pattern, variables)?),
match c { match flags {
Some(c) => Some(Box::new(self.build_for_expression(c, variables)?)), Some(flags) => Some(Box::new(self.build_for_expression(flags, variables)?)),
None => None, None => None,
}, },
), ),
@ -444,7 +444,7 @@ impl<'a, S: EncodedQuadsStore> PlanBuilder<'a, S> {
fn build_cast( fn build_cast(
&self, &self,
parameters: &Vec<Expression>, parameters: &[Expression],
constructor: impl Fn(Box<PlanExpression>) -> PlanExpression, constructor: impl Fn(Box<PlanExpression>) -> PlanExpression,
variables: &mut Vec<Variable>, variables: &mut Vec<Variable>,
name: &'static str, name: &'static str,

@ -38,7 +38,7 @@ PrefixDecl -> () = "PREFIX"i _ ns:PNAME_NS _ i:IRIREF {
//[7] //[7]
SelectQuery -> Query = s:SelectClause _ d:DatasetClauses _ w:WhereClause _ g:GroupClause? _ h:HavingClause? _ o:OrderClause? _ l:LimitOffsetClauses? _ v:ValuesClause { //TODO: Modifier SelectQuery -> Query = s:SelectClause _ d:DatasetClauses _ w:WhereClause _ g:GroupClause? _ h:HavingClause? _ o:OrderClause? _ l:LimitOffsetClauses? _ v:ValuesClause { //TODO: Modifier
Query::SelectQuery { Query::Select {
dataset: d, dataset: d,
algebra: build_select(s, w, g, h, o, l, v, state) algebra: build_select(s, w, g, h, o, l, v, state)
} }
@ -70,14 +70,14 @@ SelectClause_member -> SelectionMember =
//[10] //[10]
ConstructQuery -> Query = ConstructQuery -> Query =
"CONSTRUCT"i _ c:ConstructTemplate _ d:DatasetClauses _ w:WhereClause _ g:GroupClause? _ h:HavingClause? _ o:OrderClause? _ l:LimitOffsetClauses? _ v:ValuesClause { "CONSTRUCT"i _ c:ConstructTemplate _ d:DatasetClauses _ w:WhereClause _ g:GroupClause? _ h:HavingClause? _ o:OrderClause? _ l:LimitOffsetClauses? _ v:ValuesClause {
Query::ConstructQuery { Query::Construct {
construct: c, construct: c,
dataset: d, dataset: d,
algebra: build_select(Selection::default(), w, g, h, o, l, v, state) algebra: build_select(Selection::default(), w, g, h, o, l, v, state)
} }
} / } /
"CONSTRUCT"i _ d:DatasetClauses _ "WHERE"i _ '{' _ c:ConstructQuery_optional_triple_template _ '}' _ g:GroupClause? _ h:HavingClause? _ o:OrderClause? _ l:LimitOffsetClauses? _ v:ValuesClause { "CONSTRUCT"i _ d:DatasetClauses _ "WHERE"i _ '{' _ c:ConstructQuery_optional_triple_template _ '}' _ g:GroupClause? _ h:HavingClause? _ o:OrderClause? _ l:LimitOffsetClauses? _ v:ValuesClause {
Query::ConstructQuery { Query::Construct {
construct: c.clone(), construct: c.clone(),
dataset: d, dataset: d,
algebra: build_select( algebra: build_select(
@ -93,13 +93,13 @@ ConstructQuery_optional_triple_template -> Vec<TriplePattern> = TriplesTemplate
//[11] //[11]
DescribeQuery -> Query = DescribeQuery -> Query =
"DESCRIBE"i _ '*' _ d:DatasetClauses w:WhereClause? _ g:GroupClause? _ h:HavingClause? _ o:OrderClause? _ l:LimitOffsetClauses? _ v:ValuesClause { "DESCRIBE"i _ '*' _ d:DatasetClauses w:WhereClause? _ g:GroupClause? _ h:HavingClause? _ o:OrderClause? _ l:LimitOffsetClauses? _ v:ValuesClause {
Query::DescribeQuery { Query::Describe {
dataset: d, dataset: d,
algebra: build_select(Selection::default(), w.unwrap_or_else(GraphPattern::default), g, h, o, l, v, state) algebra: build_select(Selection::default(), w.unwrap_or_else(GraphPattern::default), g, h, o, l, v, state)
} }
} / } /
"DESCRIBE"i _ p:DescribeQuery_item+ _ d:DatasetClauses w:WhereClause? _ g:GroupClause? _ h:HavingClause? _ o:OrderClause? _ l:LimitOffsetClauses? _ v:ValuesClause { "DESCRIBE"i _ p:DescribeQuery_item+ _ d:DatasetClauses w:WhereClause? _ g:GroupClause? _ h:HavingClause? _ o:OrderClause? _ l:LimitOffsetClauses? _ v:ValuesClause {
Query::DescribeQuery { Query::Describe {
dataset: d, dataset: d,
algebra: build_select(Selection { algebra: build_select(Selection {
option: SelectionOption::Default, option: SelectionOption::Default,
@ -114,7 +114,7 @@ DescribeQuery_item -> NamedNodeOrVariable = i:VarOrIri _ { i }
//[12] //[12]
AskQuery -> Query = "ASK"i _ d:DatasetClauses w:WhereClause _ g:GroupClause? _ h:HavingClause? _ o:OrderClause? _ l:LimitOffsetClauses? _ v:ValuesClause { AskQuery -> Query = "ASK"i _ d:DatasetClauses w:WhereClause _ g:GroupClause? _ h:HavingClause? _ o:OrderClause? _ l:LimitOffsetClauses? _ v:ValuesClause {
Query::AskQuery { Query::Ask {
dataset: d, dataset: d,
algebra: build_select(Selection::default(), w, g, h, o, l, v, state) algebra: build_select(Selection::default(), w, g, h, o, l, v, state)
} }
@ -170,7 +170,7 @@ GroupCondition_as -> Variable = "AS"i _ v:Var _ { v }
//[21] //[21]
HavingClause -> Expression = "HAVING"i _ e:HavingCondition+ {? HavingClause -> Expression = "HAVING"i _ e:HavingCondition+ {?
not_empty_fold(e.into_iter(), |a, b| Expression::AndExpression(Box::new(a), Box::new(b))) not_empty_fold(e.into_iter(), |a, b| Expression::And(Box::new(a), Box::new(b)))
} }
//[22] //[22]
@ -226,7 +226,7 @@ GroupGraphPattern -> GraphPattern =
//[54] //[54]
GroupGraphPatternSub -> GraphPattern = a:TriplesBlock? _ b:GroupGraphPatternSub_item* { GroupGraphPatternSub -> GraphPattern = a:TriplesBlock? _ b:GroupGraphPatternSub_item* {
let mut p = a.map(|v| vec![PartialGraphPattern::Other(GraphPattern::BGP(v))]).unwrap_or_else(|| vec![]); let mut p = a.map_or_else(Vec::default, |v| vec![PartialGraphPattern::Other(GraphPattern::BGP(v))]);
for v in b { for v in b {
p.extend_from_slice(&v) p.extend_from_slice(&v)
} }
@ -249,7 +249,7 @@ GroupGraphPatternSub -> GraphPattern = a:TriplesBlock? _ b:GroupGraphPatternSub_
g = GraphPattern::Extend(Box::new(g), var, expr) g = GraphPattern::Extend(Box::new(g), var, expr)
} }
PartialGraphPattern::Filter(expr) => match filter { PartialGraphPattern::Filter(expr) => match filter {
Some(f) => { filter = Some(Expression::AndExpression(Box::new(f), Box::new(expr))) }, Some(f) => { filter = Some(Expression::And(Box::new(f), Box::new(expr))) },
None => { filter = Some(expr) } None => { filter = Some(expr) }
}, },
PartialGraphPattern::Other(e) => g = new_join(g, e), PartialGraphPattern::Other(e) => g = new_join(g, e),
@ -693,13 +693,13 @@ Expression -> Expression = e:ConditionalOrExpression {e}
//[111] //[111]
ConditionalOrExpression -> Expression = e:ConditionalOrExpression_item **<1,> ("||" _) {? ConditionalOrExpression -> Expression = e:ConditionalOrExpression_item **<1,> ("||" _) {?
not_empty_fold(e.into_iter(), |a, b| Expression::OrExpression(Box::new(a), Box::new(b))) not_empty_fold(e.into_iter(), |a, b| Expression::Or(Box::new(a), Box::new(b)))
} }
ConditionalOrExpression_item -> Expression = e:ConditionalAndExpression _ { e } ConditionalOrExpression_item -> Expression = e:ConditionalAndExpression _ { e }
//[112] //[112]
ConditionalAndExpression -> Expression = e:ConditionalAndExpression_item **<1,> ("&&" _) {? ConditionalAndExpression -> Expression = e:ConditionalAndExpression_item **<1,> ("&&" _) {?
not_empty_fold(e.into_iter(), |a, b| Expression::AndExpression(Box::new(a), Box::new(b))) not_empty_fold(e.into_iter(), |a, b| Expression::And(Box::new(a), Box::new(b)))
} }
ConditionalAndExpression_item -> Expression = e:ValueLogical _ { e } ConditionalAndExpression_item -> Expression = e:ValueLogical _ { e }
@ -708,14 +708,14 @@ ValueLogical -> Expression = RelationalExpression
//[114] //[114]
RelationalExpression -> Expression = RelationalExpression -> Expression =
a:NumericExpression _ "=" _ b:NumericExpression { Expression::EqualExpression(Box::new(a), Box::new(b)) } / a:NumericExpression _ "=" _ b:NumericExpression { Expression::Equal(Box::new(a), Box::new(b)) } /
a:NumericExpression _ "!=" _ b:NumericExpression { Expression::NotEqualExpression(Box::new(a), Box::new(b)) } / a:NumericExpression _ "!=" _ b:NumericExpression { Expression::NotEqual(Box::new(a), Box::new(b)) } /
a:NumericExpression _ ">" _ b:NumericExpression { Expression::GreaterExpression(Box::new(a), Box::new(b)) } / a:NumericExpression _ ">" _ b:NumericExpression { Expression::Greater(Box::new(a), Box::new(b)) } /
a:NumericExpression _ ">=" _ b:NumericExpression { Expression::GreaterOrEqExpression(Box::new(a), Box::new(b)) } / a:NumericExpression _ ">=" _ b:NumericExpression { Expression::GreaterOrEq(Box::new(a), Box::new(b)) } /
a:NumericExpression _ "<" _ b:NumericExpression { Expression::LowerExpression(Box::new(a), Box::new(b)) } / a:NumericExpression _ "<" _ b:NumericExpression { Expression::Lower(Box::new(a), Box::new(b)) } /
a:NumericExpression _ "<=" _ b:NumericExpression { Expression::LowerOrEqExpression(Box::new(a), Box::new(b)) } / a:NumericExpression _ "<=" _ b:NumericExpression { Expression::LowerOrEq(Box::new(a), Box::new(b)) } /
a:NumericExpression _ "IN"i _ b:ExpressionList { Expression::InExpression(Box::new(a), b) } / a:NumericExpression _ "IN"i _ b:ExpressionList { Expression::In(Box::new(a), b) } /
a:NumericExpression _ "NOT"i _ "IN"i _ b:ExpressionList { Expression::NotInExpression(Box::new(a), b) } / a:NumericExpression _ "NOT"i _ "IN"i _ b:ExpressionList { Expression::NotIn(Box::new(a), b) } /
NumericExpression NumericExpression
//[115] //[115]
@ -723,21 +723,21 @@ NumericExpression -> Expression = AdditiveExpression
//[116] //[116]
AdditiveExpression -> Expression = AdditiveExpression -> Expression =
a:MultiplicativeExpression _ '+' _ b:AdditiveExpression { Expression::AddExpression(Box::new(a), Box::new(b)) } / a:MultiplicativeExpression _ '+' _ b:AdditiveExpression { Expression::Add(Box::new(a), Box::new(b)) } /
a:MultiplicativeExpression _ '-' _ b:AdditiveExpression { Expression::SubExpression(Box::new(a), Box::new(b)) } / a:MultiplicativeExpression _ '-' _ b:AdditiveExpression { Expression::Sub(Box::new(a), Box::new(b)) } /
MultiplicativeExpression MultiplicativeExpression
//[117] //[117]
MultiplicativeExpression -> Expression = MultiplicativeExpression -> Expression =
a:UnaryExpression _ '*' _ b:MultiplicativeExpression { Expression::MulExpression(Box::new(a), Box::new(b)) } / a:UnaryExpression _ '*' _ b:MultiplicativeExpression { Expression::Mul(Box::new(a), Box::new(b)) } /
a:UnaryExpression _ '/' _ b:MultiplicativeExpression { Expression::DivExpression(Box::new(a), Box::new(b)) } / a:UnaryExpression _ '/' _ b:MultiplicativeExpression { Expression::Div(Box::new(a), Box::new(b)) } /
UnaryExpression UnaryExpression
//[118] //[118]
UnaryExpression -> Expression = UnaryExpression -> Expression =
'!' _ e:PrimaryExpression { Expression::UnaryNotExpression(Box::new(e)) } / '!' _ e:PrimaryExpression { Expression::UnaryNot(Box::new(e)) } /
'+' _ e:PrimaryExpression { Expression::UnaryPlusExpression(Box::new(e)) } / '+' _ e:PrimaryExpression { Expression::UnaryPlus(Box::new(e)) } /
'-' _ e:PrimaryExpression { Expression::UnaryMinusExpression(Box::new(e)) } / '-' _ e:PrimaryExpression { Expression::UnaryMinus(Box::new(e)) } /
PrimaryExpression PrimaryExpression
//[119] //[119]
@ -745,10 +745,10 @@ PrimaryExpression -> Expression =
BrackettedExpression / BrackettedExpression /
BuiltInCall / BuiltInCall /
iriOrFunction / iriOrFunction /
l:RDFLiteral { Expression::ConstantExpression(l.into()) } / l:RDFLiteral { Expression::Constant(l.into()) } /
l:NumericLiteral { Expression::ConstantExpression(l.into()) } / l:NumericLiteral { Expression::Constant(l.into()) } /
l:BooleanLiteral { Expression::ConstantExpression(l.into()) } / l:BooleanLiteral { Expression::Constant(l.into()) } /
v:Var { Expression::ConstantExpression(v.into()) } v:Var { Expression::Constant(v.into()) }
//[120] //[120]
BrackettedExpression -> Expression = '(' _ e:Expression _ ')' { e } BrackettedExpression -> Expression = '(' _ e:Expression _ ')' { e }
@ -829,7 +829,7 @@ StrReplaceExpression -> Expression =
ExistsFunc -> Expression = "EXISTS"i _ p:GroupGraphPattern { Expression::ExistsFunctionCall(Box::new(p)) } ExistsFunc -> Expression = "EXISTS"i _ p:GroupGraphPattern { Expression::ExistsFunctionCall(Box::new(p)) }
//[126] //[126]
NotExistsFunc -> Expression = "NOT"i _ "EXISTS"i _ p:GroupGraphPattern { Expression::UnaryNotExpression(Box::new(Expression::ExistsFunctionCall(Box::new(p)))) } NotExistsFunc -> Expression = "NOT"i _ "EXISTS"i _ p:GroupGraphPattern { Expression::UnaryNot(Box::new(Expression::ExistsFunctionCall(Box::new(p)))) }
//[127] //[127]
Aggregate -> Aggregation = Aggregate -> Aggregation =
@ -856,7 +856,7 @@ Aggregate -> Aggregation =
iriOrFunction -> Expression = i: iri _ a: ArgList? { iriOrFunction -> Expression = i: iri _ a: ArgList? {
match a { match a {
Some(a) => Expression::CustomFunctionCall(i, a), Some(a) => Expression::CustomFunctionCall(i, a),
None => Expression::ConstantExpression(i.into()) None => Expression::Constant(i.into())
} }
} }

@ -90,8 +90,7 @@ pub fn read_xml_results(source: impl BufRead + 'static) -> Result<QueryResult> {
State::Head => { State::Head => {
if event.name() == b"variable" { if event.name() == b"variable" {
let name = event.attributes() let name = event.attributes()
.filter(|attr| attr.is_ok()) .filter_map(|attr| attr.ok())
.map(|attr| attr.unwrap())
.find(|attr| attr.key == b"name") .find(|attr| attr.key == b"name")
.ok_or("No name attribute found for the <variable> tag"); .ok_or("No name attribute found for the <variable> tag");
variables.push(name?.unescape_and_decode_value(&reader)?); variables.push(name?.unescape_and_decode_value(&reader)?);
@ -128,11 +127,10 @@ pub fn read_xml_results(source: impl BufRead + 'static) -> Result<QueryResult> {
_ => Err(format!("Unexpected textual value found: {}", reader.decode(&value)).into()) _ => Err(format!("Unexpected textual value found: {}", reader.decode(&value)).into())
}; };
}, },
Event::End(_) => match state { Event::End(_) => if let State::Head = state {
State::Head => state = State::AfterHead, state = State::AfterHead;
_ => { } else {
return Err("Unexpected early file end. All results file should have a <head> and a <result> or <boolean> tag".into()); return Err("Unexpected early file end. All results file should have a <head> and a <result> or <boolean> tag".into());
}
}, },
Event::Eof => return Err("Unexpected early file end. All results file should have a <head> and a <result> or <boolean> tag".into()), Event::Eof => return Err("Unexpected early file end. All results file should have a <head> and a <result> or <boolean> tag".into()),
_ => (), _ => (),
@ -199,8 +197,7 @@ impl<R: BufRead> Iterator for ResultsIterator<R> {
State::Result => if event.name() == b"binding" { State::Result => if event.name() == b"binding" {
match event match event
.attributes() .attributes()
.filter(|attr| attr.is_ok()) .filter_map(|attr| attr.ok())
.map(|attr| attr.unwrap())
.find(|attr| attr.key == b"name") .find(|attr| attr.key == b"name")
{ {
Some(attr) => match attr.unescaped_value() { Some(attr) => match attr.unescaped_value() {

@ -368,7 +368,7 @@ impl<S: EncodedQuadsStore + Default> Default for StoreDataset<S> {
impl<S: EncodedQuadsStore + Default> FromIterator<Quad> for StoreDataset<S> { impl<S: EncodedQuadsStore + Default> FromIterator<Quad> for StoreDataset<S> {
fn from_iter<I: IntoIterator<Item = Quad>>(iter: I) -> Self { fn from_iter<I: IntoIterator<Item = Quad>>(iter: I) -> Self {
let dataset = StoreDataset::default(); let dataset = Self::default();
for quad in iter { for quad in iter {
dataset.insert(&quad).unwrap(); dataset.insert(&quad).unwrap();
} }
@ -378,7 +378,7 @@ impl<S: EncodedQuadsStore + Default> FromIterator<Quad> for StoreDataset<S> {
impl<'a, S: EncodedQuadsStore + Default> FromIterator<&'a Quad> for StoreDataset<S> { impl<'a, S: EncodedQuadsStore + Default> FromIterator<&'a Quad> for StoreDataset<S> {
fn from_iter<I: IntoIterator<Item = &'a Quad>>(iter: I) -> Self { fn from_iter<I: IntoIterator<Item = &'a Quad>>(iter: I) -> Self {
let dataset = StoreDataset::default(); let dataset = Self::default();
for quad in iter { for quad in iter {
dataset.insert(quad).unwrap(); dataset.insert(quad).unwrap();
} }
@ -709,7 +709,7 @@ impl<S: EncodedQuadsStore + Default> Default for StoreDefaultGraph<S> {
impl<S: EncodedQuadsStore + Default> FromIterator<Triple> for StoreDefaultGraph<S> { impl<S: EncodedQuadsStore + Default> FromIterator<Triple> for StoreDefaultGraph<S> {
fn from_iter<I: IntoIterator<Item = Triple>>(iter: I) -> Self { fn from_iter<I: IntoIterator<Item = Triple>>(iter: I) -> Self {
let graph = StoreDefaultGraph::default(); let graph = Self::default();
for triple in iter { for triple in iter {
graph.insert(&triple).unwrap(); graph.insert(&triple).unwrap();
} }
@ -719,7 +719,7 @@ impl<S: EncodedQuadsStore + Default> FromIterator<Triple> for StoreDefaultGraph<
impl<'a, S: EncodedQuadsStore + Default> FromIterator<&'a Triple> for StoreDefaultGraph<S> { impl<'a, S: EncodedQuadsStore + Default> FromIterator<&'a Triple> for StoreDefaultGraph<S> {
fn from_iter<I: IntoIterator<Item = &'a Triple>>(iter: I) -> Self { fn from_iter<I: IntoIterator<Item = &'a Triple>>(iter: I) -> Self {
let graph = StoreDefaultGraph::default(); let graph = Self::default();
for triple in iter { for triple in iter {
graph.insert(triple).unwrap(); graph.insert(triple).unwrap();
} }

@ -1,8 +1,8 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::collections::BTreeSet; use std::collections::BTreeSet;
use std::sync::RwLock; use std::sync::RwLock;
use store::encoded::*;
use store::numeric_encoder::*; use store::numeric_encoder::*;
use store::store::*;
use Result; use Result;
/// Memory based implementation of the `rudf::model::Dataset` trait. /// Memory based implementation of the `rudf::model::Dataset` trait.
@ -388,16 +388,12 @@ impl EncodedQuadsStore for MemoryStore {
.graph_indexes .graph_indexes
.read()? .read()?
.get(&quad.graph_name) .get(&quad.graph_name)
.map(|graph| { .map_or(false, |graph| {
graph graph.spo.get(&quad.subject).map_or(false, |po| {
.spo po.get(&quad.predicate)
.get(&quad.subject) .map_or(false, |o| o.contains(&quad.object))
.map(|po| { })
po.get(&quad.predicate) }))
.map(|o| o.contains(&quad.object))
.unwrap_or(false)
}).unwrap_or(false)
}).unwrap_or(false))
} }
fn insert(&self, quad: &EncodedQuad) -> Result<()> { fn insert(&self, quad: &EncodedQuad) -> Result<()> {

@ -1,10 +1,10 @@
//! Provides implementations of the `rudf::model::Graph` and `rudf::model::Dataset` traits. //! Provides implementations of the `rudf::model::Graph` and `rudf::model::Dataset` traits.
pub(crate) mod encoded;
pub mod isomorphism; pub mod isomorphism;
mod memory; mod memory;
pub(crate) mod numeric_encoder; pub(crate) mod numeric_encoder;
mod rocksdb; mod rocksdb;
pub(crate) mod store;
pub use store::memory::MemoryDataset; pub use store::memory::MemoryDataset;
pub use store::memory::MemoryGraph; pub use store::memory::MemoryGraph;

@ -128,20 +128,20 @@ impl EncodedTerm {
pub fn is_literal(&self) -> bool { pub fn is_literal(&self) -> bool {
match self { match self {
EncodedTerm::SimpleLiteral { .. } => true, EncodedTerm::SimpleLiteral { .. }
EncodedTerm::LangStringLiteral { .. } => true, | EncodedTerm::LangStringLiteral { .. }
EncodedTerm::TypedLiteral { .. } => true, | EncodedTerm::TypedLiteral { .. }
EncodedTerm::StringLiteral { .. } => true, | EncodedTerm::StringLiteral { .. }
EncodedTerm::BooleanLiteral(_) => true, | EncodedTerm::BooleanLiteral(_)
EncodedTerm::FloatLiteral(_) => true, | EncodedTerm::FloatLiteral(_)
EncodedTerm::DoubleLiteral(_) => true, | EncodedTerm::DoubleLiteral(_)
EncodedTerm::IntegerLiteral(_) => true, | EncodedTerm::IntegerLiteral(_)
EncodedTerm::DecimalLiteral(_) => true, | EncodedTerm::DecimalLiteral(_) => true,
_ => false, _ => false,
} }
} }
pub fn datatype(&self) -> Option<EncodedTerm> { pub fn datatype(&self) -> Option<Self> {
match self { match self {
EncodedTerm::SimpleLiteral { .. } | EncodedTerm::StringLiteral { .. } => { EncodedTerm::SimpleLiteral { .. } | EncodedTerm::StringLiteral { .. } => {
Some(ENCODED_XSD_STRING_NAMED_NODE) Some(ENCODED_XSD_STRING_NAMED_NODE)
@ -262,7 +262,7 @@ impl<R: Read> TermReader for R {
datatype_id: self.read_u64::<NetworkEndian>()?, datatype_id: self.read_u64::<NetworkEndian>()?,
value_id: self.read_u64::<NetworkEndian>()?, value_id: self.read_u64::<NetworkEndian>()?,
}), }),
TYPE_STRING_LITERAL => Ok(EncodedTerm::SimpleLiteral { TYPE_STRING_LITERAL => Ok(EncodedTerm::StringLiteral {
value_id: self.read_u64::<NetworkEndian>()?, value_id: self.read_u64::<NetworkEndian>()?,
}), }),
TYPE_BOOLEAN_LITERAL_TRUE => Ok(EncodedTerm::BooleanLiteral(true)), TYPE_BOOLEAN_LITERAL_TRUE => Ok(EncodedTerm::BooleanLiteral(true)),
@ -339,7 +339,7 @@ impl<R: Write> TermWriter for R {
EncodedTerm::DefaultGraph {} => {} EncodedTerm::DefaultGraph {} => {}
EncodedTerm::NamedNode { iri_id } => self.write_u64::<NetworkEndian>(iri_id)?, EncodedTerm::NamedNode { iri_id } => self.write_u64::<NetworkEndian>(iri_id)?,
EncodedTerm::BlankNode(id) => self.write_all(id.as_bytes())?, EncodedTerm::BlankNode(id) => self.write_all(id.as_bytes())?,
EncodedTerm::SimpleLiteral { value_id } => { EncodedTerm::SimpleLiteral { value_id } | EncodedTerm::StringLiteral { value_id } => {
self.write_u64::<NetworkEndian>(value_id)?; self.write_u64::<NetworkEndian>(value_id)?;
} }
EncodedTerm::LangStringLiteral { EncodedTerm::LangStringLiteral {
@ -356,10 +356,6 @@ impl<R: Write> TermWriter for R {
self.write_u64::<NetworkEndian>(datatype_id)?; self.write_u64::<NetworkEndian>(datatype_id)?;
self.write_u64::<NetworkEndian>(value_id)?; self.write_u64::<NetworkEndian>(value_id)?;
} }
EncodedTerm::StringLiteral { value_id } => {
self.write_u64::<NetworkEndian>(value_id)?;
}
EncodedTerm::BooleanLiteral(_) => {} EncodedTerm::BooleanLiteral(_) => {}
EncodedTerm::FloatLiteral(value) => self.write_f32::<NetworkEndian>(*value)?, EncodedTerm::FloatLiteral(value) => self.write_f32::<NetworkEndian>(*value)?,
EncodedTerm::DoubleLiteral(value) => self.write_f64::<NetworkEndian>(*value)?, EncodedTerm::DoubleLiteral(value) => self.write_f64::<NetworkEndian>(*value)?,

@ -10,9 +10,9 @@ use std::io::Cursor;
use std::path::Path; use std::path::Path;
use std::str; use std::str;
use std::sync::Mutex; use std::sync::Mutex;
use store::encoded::EncodedQuadsStore;
use store::encoded::StoreDataset;
use store::numeric_encoder::*; use store::numeric_encoder::*;
use store::store::EncodedQuadsStore;
use store::store::StoreDataset;
use Result; use Result;
/// `rudf::model::Dataset` trait implementation based on the [RocksDB](https://rocksdb.org/) key-value store /// `rudf::model::Dataset` trait implementation based on the [RocksDB](https://rocksdb.org/) key-value store
@ -83,17 +83,16 @@ impl BytesStore for RocksDbStore {
type BytesOutput = DBVector; type BytesOutput = DBVector;
fn insert_bytes(&self, value: &[u8]) -> Result<u64> { fn insert_bytes(&self, value: &[u8]) -> Result<u64> {
Ok(match self.db.get_cf(self.str2id_cf, value)? { Ok(if let Some(id) = self.db.get_cf(self.str2id_cf, value)? {
Some(id) => NetworkEndian::read_u64(&id), NetworkEndian::read_u64(&id)
None => { } else {
let id = self.str_id_counter.lock()?.get_and_increment(&self.db)? as u64; let id = self.str_id_counter.lock()?.get_and_increment(&self.db)? as u64;
let id_bytes = to_bytes(id); let id_bytes = to_bytes(id);
let mut batch = WriteBatch::default(); let mut batch = WriteBatch::default();
batch.put_cf(self.id2str_cf, &id_bytes, value)?; batch.put_cf(self.id2str_cf, &id_bytes, value)?;
batch.put_cf(self.str2id_cf, value, &id_bytes)?; batch.put_cf(self.str2id_cf, value, &id_bytes)?;
self.db.write(batch)?; self.db.write(batch)?;
id id
}
}) })
} }
@ -342,8 +341,7 @@ impl RocksDBCounter {
fn get_and_increment(&self, db: &DB) -> Result<u64> { fn get_and_increment(&self, db: &DB) -> Result<u64> {
let value = db let value = db
.get(self.name.as_bytes())? .get(self.name.as_bytes())?
.map(|b| NetworkEndian::read_u64(&b)) .map_or(0, |b| NetworkEndian::read_u64(&b));
.unwrap_or(0);
db.put(self.name.as_bytes(), &to_bytes(value + 1))?; db.put(self.name.as_bytes(), &to_bytes(value + 1))?;
Ok(value) Ok(value)
} }

@ -26,8 +26,8 @@ enum EscapeRdfState {
} }
impl EscapeRDF { impl EscapeRDF {
fn new(c: char) -> EscapeRDF { fn new(c: char) -> Self {
EscapeRDF { Self {
state: match c { state: match c {
'\t' => EscapeRdfState::Backslash('t'), '\t' => EscapeRdfState::Backslash('t'),
'\u{08}' => EscapeRdfState::Backslash('b'), '\u{08}' => EscapeRdfState::Backslash('b'),

@ -1,3 +1,8 @@
#![cfg_attr(
feature = "cargo-clippy",
allow(zero_ptr, transmute_ptr_to_ptr)
)]
#[macro_use] #[macro_use]
extern crate cpython; extern crate cpython;
extern crate rudf; extern crate rudf;
@ -24,11 +29,11 @@ py_module_initializer!(rudf, initrudf, PyInit_rudf, |py, m| {
Ok(()) Ok(())
}); });
fn new_value_error(py: Python, error: impl Error) -> PyErr { fn new_value_error(py: Python, error: &impl Error) -> PyErr {
PyErr::new::<ValueError, _>(py, error.description()) PyErr::new::<ValueError, _>(py, error.description())
} }
fn eq_compare<T: Eq + Ord>(a: T, b: T, op: CompareOp) -> bool { fn eq_compare<T: Eq + Ord>(a: &T, b: &T, op: &CompareOp) -> bool {
match op { match op {
CompareOp::Lt => a < b, CompareOp::Lt => a < b,
CompareOp::Le => a <= b, CompareOp::Le => a <= b,
@ -49,7 +54,7 @@ py_class!(class NamedNode |py| {
data inner: model::NamedNode; data inner: model::NamedNode;
def __new__(_cls, value: &str) -> PyResult<NamedNode> { def __new__(_cls, value: &str) -> PyResult<NamedNode> {
NamedNode::create_instance(py, model::NamedNode::from_str(value).map_err(|error| new_value_error(py, error))?) NamedNode::create_instance(py, model::NamedNode::from_str(value).map_err(|error| new_value_error(py, &error))?)
} }
def value(&self) -> PyResult<String> { def value(&self) -> PyResult<String> {
@ -61,7 +66,7 @@ py_class!(class NamedNode |py| {
} }
def __richcmp__(&self, other: &NamedNode, op: CompareOp) -> PyResult<bool> { def __richcmp__(&self, other: &NamedNode, op: CompareOp) -> PyResult<bool> {
Ok(eq_compare(self.inner(py), other.inner(py), op)) Ok(eq_compare(&self.inner(py), &other.inner(py), &op))
} }
def __hash__(&self) -> PyResult<u64> { def __hash__(&self) -> PyResult<u64> {
@ -81,7 +86,7 @@ py_class!(class BlankNode |py| {
} }
def __richcmp__(&self, other: &BlankNode, op: CompareOp) -> PyResult<bool> { def __richcmp__(&self, other: &BlankNode, op: CompareOp) -> PyResult<bool> {
Ok(eq_compare(self.inner(py), other.inner(py), op)) Ok(eq_compare(&self.inner(py), &other.inner(py), &op))
} }
def __hash__(&self) -> PyResult<u64> { def __hash__(&self) -> PyResult<u64> {
@ -119,7 +124,7 @@ py_class!(class Literal |py| {
} }
def __richcmp__(&self, other: &Literal, op: CompareOp) -> PyResult<bool> { def __richcmp__(&self, other: &Literal, op: CompareOp) -> PyResult<bool> {
Ok(eq_compare(self.inner(py), other.inner(py), op)) Ok(eq_compare(&self.inner(py), &other.inner(py), &op))
} }
def __hash__(&self) -> PyResult<u64> { def __hash__(&self) -> PyResult<u64> {

Loading…
Cancel
Save