Upgrades formatting to 1.31

pull/10/head
Tpt 6 years ago
parent d537a54f0b
commit 0ba67d9614
  1. 283
      lib/src/sparql/algebra.rs
  2. 70
      lib/src/sparql/eval.rs
  3. 17
      lib/src/sparql/parser.rs
  4. 109
      lib/src/sparql/plan.rs
  5. 62
      lib/src/sparql/xml_results.rs
  6. 3
      lib/src/store/encoded.rs
  7. 12
      lib/src/store/numeric_encoder.rs
  8. 22
      lib/tests/rdf_test_cases.rs
  9. 22
      lib/tests/sparql_test_cases.rs
  10. 5
      python/src/lib.rs
  11. 15
      server/src/main.rs

@ -747,7 +747,8 @@ impl<'a> fmt::Display for SparqlExpression<'a> {
SparqlExpression(&*b), SparqlExpression(&*b),
SparqlExpression(cv) SparqlExpression(cv)
) )
}).unwrap_or_else(|| { })
.unwrap_or_else(|| {
write!( write!(
f, f,
"SUBSTR({}, {})", "SUBSTR({}, {})",
@ -1130,31 +1131,35 @@ impl<'a> fmt::Display for SparqlGraphPattern<'a> {
SparqlGraphPattern(&*a), SparqlGraphPattern(&*a),
SparqlGraphPattern(&*b) SparqlGraphPattern(&*b)
), ),
GraphPattern::Service(n, p, s) => if *s { GraphPattern::Service(n, p, s) => {
write!(f, "SERVICE SILENT {} {{ {} }}", n, SparqlGraphPattern(&*p)) if *s {
} else { write!(f, "SERVICE SILENT {} {{ {} }}", n, SparqlGraphPattern(&*p))
write!(f, "SERVICE {} {{ {} }}", n, SparqlGraphPattern(&*p)) } else {
}, write!(f, "SERVICE {} {{ {} }}", n, SparqlGraphPattern(&*p))
GraphPattern::Data(bs) => if bs.is_empty() {
Ok(())
} else {
write!(f, "VALUES ( ")?;
for var in bs.variables() {
write!(f, "{} ", var)?;
} }
write!(f, ") {{ ")?; }
for values in bs.values_iter() { GraphPattern::Data(bs) => {
write!(f, "( ")?; if bs.is_empty() {
for val in values { Ok(())
match val { } else {
Some(val) => write!(f, "{} ", val), write!(f, "VALUES ( ")?;
None => write!(f, "UNDEF "), for var in bs.variables() {
}?; write!(f, "{} ", var)?;
} }
write!(f, ") ")?; write!(f, ") {{ ")?;
for values in bs.values_iter() {
write!(f, "( ")?;
for val in values {
match val {
Some(val) => write!(f, "{} ", val),
None => write!(f, "UNDEF "),
}?;
}
write!(f, ") ")?;
}
write!(f, " }}")
} }
write!(f, " }}") }
},
GraphPattern::AggregateJoin(GroupPattern(group, p), agg) => write!( GraphPattern::AggregateJoin(GroupPattern(group, p), agg) => write!(
f, f,
"{{ SELECT {} WHERE {{ {} }} GROUP BY {} }}", "{{ SELECT {} WHERE {{ {} }} GROUP BY {} }}",
@ -1301,63 +1306,81 @@ pub enum Aggregation {
impl fmt::Display for Aggregation { impl fmt::Display for Aggregation {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match self {
Aggregation::Count(e, distinct) => if *distinct { Aggregation::Count(e, distinct) => {
e.as_ref() if *distinct {
.map(|ex| write!(f, "COUNT(DISTINCT {})", ex)) e.as_ref()
.unwrap_or_else(|| write!(f, "COUNT(DISTINCT *)")) .map(|ex| write!(f, "COUNT(DISTINCT {})", ex))
} else { .unwrap_or_else(|| write!(f, "COUNT(DISTINCT *)"))
e.as_ref() } else {
.map(|ex| write!(f, "COUNT({})", ex)) e.as_ref()
.unwrap_or_else(|| write!(f, "COUNT(*)")) .map(|ex| write!(f, "COUNT({})", ex))
}, .unwrap_or_else(|| write!(f, "COUNT(*)"))
Aggregation::Sum(e, distinct) => if *distinct { }
write!(f, "Aggregation(Distinct({}), Sum, {{}})", e) }
} else { Aggregation::Sum(e, distinct) => {
write!(f, "Aggregation({}, Sum, {{}})", e) if *distinct {
}, write!(f, "Aggregation(Distinct({}), Sum, {{}})", e)
Aggregation::Min(e, distinct) => if *distinct { } else {
write!(f, "Aggregation(Distinct({}), Min, {{}})", e) write!(f, "Aggregation({}, Sum, {{}})", e)
} else { }
write!(f, "Aggregation({}, Min, {{}})", e) }
}, Aggregation::Min(e, distinct) => {
Aggregation::Max(e, distinct) => if *distinct { if *distinct {
write!(f, "Aggregation(Distinct({}), Max, {{}})", e) write!(f, "Aggregation(Distinct({}), Min, {{}})", e)
} else { } else {
write!(f, "Aggregation({}, Max, {{}})", e) write!(f, "Aggregation({}, Min, {{}})", e)
}, }
Aggregation::Avg(e, distinct) => if *distinct { }
write!(f, "Aggregation(Distinct({}), Avg, {{}})", e) Aggregation::Max(e, distinct) => {
} else { if *distinct {
write!(f, "Aggregation({}, Avg, {{}})", e) write!(f, "Aggregation(Distinct({}), Max, {{}})", e)
}, } else {
Aggregation::Sample(e, distinct) => if *distinct { write!(f, "Aggregation({}, Max, {{}})", e)
write!(f, "Aggregation(Distinct({}), Sum, {{}})", e) }
} else { }
write!(f, "Aggregation({}, Sample, {{}})", e) Aggregation::Avg(e, distinct) => {
}, if *distinct {
Aggregation::GroupConcat(e, distinct, sep) => if *distinct { write!(f, "Aggregation(Distinct({}), Avg, {{}})", e)
sep.as_ref() } else {
.map(|s| { write!(f, "Aggregation({}, Avg, {{}})", e)
write!( }
}
Aggregation::Sample(e, distinct) => {
if *distinct {
write!(f, "Aggregation(Distinct({}), Sum, {{}})", e)
} else {
write!(f, "Aggregation({}, Sample, {{}})", e)
}
}
Aggregation::GroupConcat(e, distinct, sep) => {
if *distinct {
sep.as_ref()
.map(|s| {
write!(
f, f,
"Aggregation(Distinct({}), GroupConcat, {{\"separator\" → \"{}\"}})", "Aggregation(Distinct({}), GroupConcat, {{\"separator\" → \"{}\"}})",
e, e,
s.escape() s.escape()
) )
}) })
.unwrap_or_else(|| write!(f, "Aggregation(Distinct({}), GroupConcat, {{}})", e)) .unwrap_or_else(|| {
} else { write!(f, "Aggregation(Distinct({}), GroupConcat, {{}})", e)
sep.as_ref() })
.map(|s| { } else {
write!( sep.as_ref()
f, .map(|s| {
"Aggregation({}, GroupConcat, {{\"separator\" → \"{}\"}})", write!(
e, f,
s.escape() "Aggregation({}, GroupConcat, {{\"separator\" → \"{}\"}})",
) e,
}) s.escape()
.unwrap_or_else(|| write!(f, "Aggregation(Distinct({}), GroupConcat, {{}})", e)) )
}, })
.unwrap_or_else(|| {
write!(f, "Aggregation(Distinct({}), GroupConcat, {{}})", e)
})
}
}
} }
} }
} }
@ -1367,63 +1390,77 @@ struct SparqlAggregation<'a>(&'a Aggregation);
impl<'a> fmt::Display for SparqlAggregation<'a> { 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 let Some(e) = e { if *distinct {
write!(f, "COUNT(DISTINCT {})", SparqlExpression(e)) if let Some(e) = e {
write!(f, "COUNT(DISTINCT {})", SparqlExpression(e))
} else {
write!(f, "COUNT(DISTINCT *)")
}
} else if let Some(e) = e {
write!(f, "COUNT({})", SparqlExpression(e))
} else { } else {
write!(f, "COUNT(DISTINCT *)") write!(f, "COUNT(*)")
} }
} else if let Some(e) = e { }
write!(f, "COUNT({})", SparqlExpression(e)) Aggregation::Sum(e, distinct) => {
} else { if *distinct {
write!(f, "COUNT(*)") write!(f, "SUM(DISTINCT {})", SparqlExpression(e))
}, } else {
Aggregation::Sum(e, distinct) => if *distinct { write!(f, "SUM({})", SparqlExpression(e))
write!(f, "SUM(DISTINCT {})", SparqlExpression(e)) }
} else { }
write!(f, "SUM({})", SparqlExpression(e)) Aggregation::Min(e, distinct) => {
}, if *distinct {
Aggregation::Min(e, distinct) => if *distinct { write!(f, "MIN(DISTINCT {})", SparqlExpression(e))
write!(f, "MIN(DISTINCT {})", SparqlExpression(e)) } else {
} else { write!(f, "MIN({})", SparqlExpression(e))
write!(f, "MIN({})", SparqlExpression(e)) }
}, }
Aggregation::Max(e, distinct) => if *distinct { Aggregation::Max(e, distinct) => {
write!(f, "MAX(DISTINCT {})", SparqlExpression(e)) if *distinct {
} else { write!(f, "MAX(DISTINCT {})", SparqlExpression(e))
write!(f, "MAX({})", SparqlExpression(e)) } else {
}, write!(f, "MAX({})", SparqlExpression(e))
Aggregation::Avg(e, distinct) => if *distinct { }
write!(f, "AVG(DISTINCT {})", SparqlExpression(e)) }
} else { Aggregation::Avg(e, distinct) => {
write!(f, "AVG({})", SparqlExpression(e)) if *distinct {
}, write!(f, "AVG(DISTINCT {})", SparqlExpression(e))
Aggregation::Sample(e, distinct) => if *distinct { } else {
write!(f, "SAMPLE(DISTINCT {})", SparqlExpression(e)) write!(f, "AVG({})", SparqlExpression(e))
} else { }
write!(f, "SAMPLE({})", SparqlExpression(e)) }
}, Aggregation::Sample(e, distinct) => {
Aggregation::GroupConcat(e, distinct, sep) => if *distinct { if *distinct {
if let Some(sep) = sep { write!(f, "SAMPLE(DISTINCT {})", SparqlExpression(e))
} else {
write!(f, "SAMPLE({})", SparqlExpression(e))
}
}
Aggregation::GroupConcat(e, distinct, sep) => {
if *distinct {
if let Some(sep) = sep {
write!(
f,
"GROUP_CONCAT(DISTINCT {}; SEPARATOR = \"{}\")",
SparqlExpression(e),
sep.escape()
)
} else {
write!(f, "GROUP_CONCAT(DISTINCT {})", SparqlExpression(e))
}
} else if let Some(sep) = sep {
write!( write!(
f, f,
"GROUP_CONCAT(DISTINCT {}; SEPARATOR = \"{}\")", "GROUP_CONCAT({}; SEPARATOR = \"{}\")",
SparqlExpression(e), SparqlExpression(e),
sep.escape() sep.escape()
) )
} else { } else {
write!(f, "GROUP_CONCAT(DISTINCT {})", SparqlExpression(e)) write!(f, "GROUP_CONCAT({})", SparqlExpression(e))
} }
} else if let Some(sep) = sep { }
write!(
f,
"GROUP_CONCAT({}; SEPARATOR = \"{}\")",
SparqlExpression(e),
sep.escape()
)
} else {
write!(f, "GROUP_CONCAT({})", SparqlExpression(e))
},
} }
} }
} }

@ -358,7 +358,8 @@ impl<S: EncodedQuadsStore> SimpleEvaluator<S> {
)? { )? {
Ordering::Greater | Ordering::Equal => true, Ordering::Greater | Ordering::Equal => true,
Ordering::Less => false, Ordering::Less => false,
}.into(), }
.into(),
), ),
PlanExpression::Lower(a, b) => Some( PlanExpression::Lower(a, b) => Some(
(self.partial_cmp_literals( (self.partial_cmp_literals(
@ -374,7 +375,8 @@ impl<S: EncodedQuadsStore> SimpleEvaluator<S> {
)? { )? {
Ordering::Less | Ordering::Equal => true, Ordering::Less | Ordering::Equal => true,
Ordering::Greater => false, Ordering::Greater => false,
}.into(), }
.into(),
), ),
PlanExpression::In(e, l) => { PlanExpression::In(e, l) => {
let needed = self.eval_expression(e, tuple)?; let needed = self.eval_expression(e, tuple)?;
@ -493,11 +495,13 @@ impl<S: EncodedQuadsStore> SimpleEvaluator<S> {
} }
None None
} }
PlanExpression::If(a, b, c) => if self.to_bool(self.eval_expression(a, tuple)?)? { PlanExpression::If(a, b, c) => {
self.eval_expression(b, tuple) if self.to_bool(self.eval_expression(a, tuple)?)? {
} else { self.eval_expression(b, tuple)
self.eval_expression(c, tuple) } else {
}, self.eval_expression(c, tuple)
}
}
PlanExpression::StrLang(lexical_form, lang_tag) => { PlanExpression::StrLang(lexical_form, lang_tag) => {
Some(EncodedTerm::LangStringLiteral { Some(EncodedTerm::LangStringLiteral {
value_id: self value_id: self
@ -525,7 +529,8 @@ impl<S: EncodedQuadsStore> SimpleEvaluator<S> {
| EncodedTerm::IntegerLiteral(_) | EncodedTerm::IntegerLiteral(_)
| EncodedTerm::DecimalLiteral(_) => true, | EncodedTerm::DecimalLiteral(_) => true,
_ => false, _ => false,
}.into(), }
.into(),
), ),
PlanExpression::LangMatches(language_tag, language_range) => { PlanExpression::LangMatches(language_tag, language_range) => {
let language_tag = let language_tag =
@ -539,7 +544,8 @@ impl<S: EncodedQuadsStore> SimpleEvaluator<S> {
LanguageTag::from_str(&language_range) LanguageTag::from_str(&language_range)
.ok()? .ok()?
.matches(&LanguageTag::from_str(&language_tag).ok()?) .matches(&LanguageTag::from_str(&language_tag).ok()?)
}.into(), }
.into(),
) )
} }
PlanExpression::Regex(text, pattern, flags) => { PlanExpression::Regex(text, pattern, flags) => {
@ -634,7 +640,8 @@ impl<S: EncodedQuadsStore> SimpleEvaluator<S> {
Decimal::one() Decimal::one()
} else { } else {
Decimal::zero() Decimal::zero()
}.into(), }
.into(),
), ),
EncodedTerm::SimpleLiteral { value_id } EncodedTerm::SimpleLiteral { value_id }
| EncodedTerm::StringLiteral { value_id } => Some(EncodedTerm::DecimalLiteral( | EncodedTerm::StringLiteral { value_id } => Some(EncodedTerm::DecimalLiteral(
@ -802,7 +809,8 @@ impl<S: EncodedQuadsStore> SimpleEvaluator<S> {
Some(term) => Some(encoder.decode_term(term)?), Some(term) => Some(encoder.decode_term(term)?),
None => None, None => None,
}) })
}).collect() })
.collect()
})), })),
) )
} }
@ -826,11 +834,13 @@ impl<S: EncodedQuadsStore> SimpleEvaluator<S> {
self.eval_expression(expression, tuple_b), self.eval_expression(expression, tuple_b),
) { ) {
(Some(a), Some(b)) => match a { (Some(a), Some(b)) => match a {
EncodedTerm::BlankNode(a) => if let EncodedTerm::BlankNode(b) = b { EncodedTerm::BlankNode(a) => {
a.cmp(&b) if let EncodedTerm::BlankNode(b) = b {
} else { a.cmp(&b)
Ordering::Less } else {
}, Ordering::Less
}
}
EncodedTerm::NamedNode { iri_id: a } => match b { EncodedTerm::NamedNode { iri_id: a } => match b {
EncodedTerm::NamedNode { iri_id: b } => { EncodedTerm::NamedNode { iri_id: b } => {
self.compare_str_ids(a, b).unwrap_or(Ordering::Equal) self.compare_str_ids(a, b).unwrap_or(Ordering::Equal)
@ -970,9 +980,11 @@ fn combine_tuples(a: &[Option<EncodedTerm>], b: &[Option<EncodedTerm>]) -> Optio
for (key, a_value) in a.into_iter().enumerate() { for (key, a_value) in a.into_iter().enumerate() {
if let Some(a_value) = a_value { if let Some(a_value) = a_value {
match b[key] { match b[key] {
Some(ref b_value) => if a_value != b_value { Some(ref b_value) => {
return None; if a_value != b_value {
}, return None;
}
}
None => result[key] = Some(*a_value), None => result[key] = Some(*a_value),
} }
} }
@ -983,9 +995,11 @@ fn combine_tuples(a: &[Option<EncodedTerm>], b: &[Option<EncodedTerm>]) -> Optio
for (key, b_value) in b.into_iter().enumerate() { for (key, b_value) in b.into_iter().enumerate() {
if let Some(b_value) = b_value { if let Some(b_value) = b_value {
match a[key] { match a[key] {
Some(ref a_value) => if a_value != b_value { Some(ref a_value) => {
return None; if a_value != b_value {
}, return None;
}
}
None => result[key] = Some(*b_value), None => result[key] = Some(*b_value),
} }
} }
@ -1128,11 +1142,13 @@ impl<'a> Iterator for HashDeduplicateIterator<'a> {
fn next(&mut self) -> Option<Result<EncodedTuple>> { fn next(&mut self) -> Option<Result<EncodedTuple>> {
match self.iter.next()? { match self.iter.next()? {
Ok(tuple) => if self.already_seen.insert(tuple.clone()) { Ok(tuple) => {
Some(Ok(tuple)) if self.already_seen.insert(tuple.clone()) {
} else { Some(Ok(tuple))
self.next() } else {
}, self.next()
}
}
Err(error) => Some(Err(error)), Err(error) => Some(Err(error)),
} }
} }

@ -179,7 +179,8 @@ mod grammar {
iter.fold(None, |a, b| match a { iter.fold(None, |a, b| match a {
Some(av) => Some(combine(av, b)), Some(av) => Some(combine(av, b)),
None => Some(b), None => Some(b),
}).ok_or("The iterator should not be empty") })
.ok_or("The iterator should not be empty")
} }
enum SelectionOption { enum SelectionOption {
@ -253,12 +254,14 @@ mod grammar {
for sel_item in sel_items { for sel_item in sel_items {
match sel_item { match sel_item {
SelectionMember::Variable(v) => pv.push(v), SelectionMember::Variable(v) => pv.push(v),
SelectionMember::Expression(e, v) => if pv.contains(&v) { SelectionMember::Expression(e, v) => {
//TODO: fail if pv.contains(&v) {
} else { //TODO: fail
p = GraphPattern::Extend(Box::new(p), v.clone(), e); } else {
pv.push(v); p = GraphPattern::Extend(Box::new(p), v.clone(), e);
}, pv.push(v);
}
}
} }
} }
} }

@ -483,7 +483,8 @@ impl<'a, S: EncodedQuadsStore> PlanBuilder<'a, S> {
OrderComparator::Desc(e) => { OrderComparator::Desc(e) => {
Ok(Comparator::Desc(self.build_for_expression(e, variables)?)) Ok(Comparator::Desc(self.build_for_expression(e, variables)?))
} }
}).collect(); })
.collect();
PlanNode::Sort { PlanNode::Sort {
child: Box::new(self.build_for_graph_pattern(l, input, variables, graph_name)?), child: Box::new(self.build_for_graph_pattern(l, input, variables, graph_name)?),
by: by?, by: by?,
@ -662,43 +663,45 @@ impl<'a, S: EncodedQuadsStore> PlanBuilder<'a, S> {
None => None, None => None,
}, },
), ),
Expression::CustomFunctionCall(name, parameters) => if *name == *xsd::BOOLEAN { Expression::CustomFunctionCall(name, parameters) => {
self.build_cast( if *name == *xsd::BOOLEAN {
parameters, self.build_cast(
PlanExpression::BooleanCast, parameters,
variables, PlanExpression::BooleanCast,
"boolean", variables,
)? "boolean",
} else if *name == *xsd::DOUBLE { )?
self.build_cast(parameters, PlanExpression::DoubleCast, variables, "double")? } else if *name == *xsd::DOUBLE {
} else if *name == *xsd::FLOAT { self.build_cast(parameters, PlanExpression::DoubleCast, variables, "double")?
self.build_cast(parameters, PlanExpression::FloatCast, variables, "float")? } else if *name == *xsd::FLOAT {
} else if *name == *xsd::DECIMAL { self.build_cast(parameters, PlanExpression::FloatCast, variables, "float")?
self.build_cast( } else if *name == *xsd::DECIMAL {
parameters, self.build_cast(
PlanExpression::DecimalCast, parameters,
variables, PlanExpression::DecimalCast,
"decimal", variables,
)? "decimal",
} else if *name == *xsd::INTEGER { )?
self.build_cast( } else if *name == *xsd::INTEGER {
parameters, self.build_cast(
PlanExpression::IntegerCast, parameters,
variables, PlanExpression::IntegerCast,
"integer", variables,
)? "integer",
} else if *name == *xsd::DATE_TIME { )?
self.build_cast( } else if *name == *xsd::DATE_TIME {
parameters, self.build_cast(
PlanExpression::DateTimeCast, parameters,
variables, PlanExpression::DateTimeCast,
"dateTime", variables,
)? "dateTime",
} else if *name == *xsd::STRING { )?
self.build_cast(parameters, PlanExpression::StringCast, variables, "string")? } else if *name == *xsd::STRING {
} else { self.build_cast(parameters, PlanExpression::StringCast, variables, "string")?
Err(format_err!("Not supported custom function {}", expression))? } else {
}, Err(format_err!("Not supported custom function {}", expression))?
}
}
_ => unimplemented!(), _ => unimplemented!(),
}) })
} }
@ -780,7 +783,8 @@ impl<'a, S: EncodedQuadsStore> PlanBuilder<'a, S> {
} }
} }
Ok(result) Ok(result)
}).collect() })
.collect()
} }
fn build_for_graph_template( fn build_for_graph_template(
@ -809,7 +813,8 @@ impl<'a, S: EncodedQuadsStore> PlanBuilder<'a, S> {
&mut bnodes, &mut bnodes,
)?, )?,
}) })
}).collect() })
.collect()
} }
fn template_value_from_term_or_variable( fn template_value_from_term_or_variable(
@ -822,11 +827,13 @@ impl<'a, S: EncodedQuadsStore> PlanBuilder<'a, S> {
TermOrVariable::Term(term) => { TermOrVariable::Term(term) => {
TripleTemplateValue::Constant(self.store.encoder().encode_term(term)?) TripleTemplateValue::Constant(self.store.encoder().encode_term(term)?)
} }
TermOrVariable::Variable(variable) => if variable.has_name() { TermOrVariable::Variable(variable) => {
TripleTemplateValue::Variable(variable_key(variables, variable)) if variable.has_name() {
} else { TripleTemplateValue::Variable(variable_key(variables, variable))
TripleTemplateValue::BlankNode(variable_key(bnodes, variable)) } else {
}, TripleTemplateValue::BlankNode(variable_key(bnodes, variable))
}
}
}) })
} }
@ -840,11 +847,13 @@ impl<'a, S: EncodedQuadsStore> PlanBuilder<'a, S> {
NamedNodeOrVariable::NamedNode(term) => { NamedNodeOrVariable::NamedNode(term) => {
TripleTemplateValue::Constant(self.store.encoder().encode_named_node(term)?) TripleTemplateValue::Constant(self.store.encoder().encode_named_node(term)?)
} }
NamedNodeOrVariable::Variable(variable) => if variable.has_name() { NamedNodeOrVariable::Variable(variable) => {
TripleTemplateValue::Variable(variable_key(variables, variable)) if variable.has_name() {
} else { TripleTemplateValue::Variable(variable_key(variables, variable))
TripleTemplateValue::BlankNode(variable_key(bnodes, variable)) } else {
}, TripleTemplateValue::BlankNode(variable_key(bnodes, variable))
}
}
}) })
} }
} }

@ -285,37 +285,41 @@ impl<R: BufRead> Iterator for ResultsIterator<R> {
} }
match event { match event {
Event::Start(event) => match state { Event::Start(event) => match state {
State::Start => if event.name() == b"result" { State::Start => {
state = State::Result; if event.name() == b"result" {
} else { state = State::Result;
return Some(Err(format_err!( } else {
"Expecting <result>, found {}", return Some(Err(format_err!(
self.reader.decode(event.name()) "Expecting <result>, found {}",
))); self.reader.decode(event.name())
}, )));
State::Result => if event.name() == b"binding" { }
match event }
.attributes() State::Result => {
.filter_map(|attr| attr.ok()) if event.name() == b"binding" {
.find(|attr| attr.key == b"name") match event
{ .attributes()
Some(attr) => match attr.unescaped_value() { .filter_map(|attr| attr.ok())
Ok(var) => current_var = Some(var.to_vec()), .find(|attr| attr.key == b"name")
Err(error) => return Some(Err(error.into())), {
}, Some(attr) => match attr.unescaped_value() {
None => { Ok(var) => current_var = Some(var.to_vec()),
return Some(Err(format_err!( Err(error) => return Some(Err(error.into())),
"No name attribute found for the <binding> tag" },
))) None => {
return Some(Err(format_err!(
"No name attribute found for the <binding> tag"
)))
}
} }
state = State::Binding;
} else {
return Some(Err(format_err!(
"Expecting <binding>, found {}",
self.reader.decode(event.name())
)));
} }
state = State::Binding; }
} else {
return Some(Err(format_err!(
"Expecting <binding>, found {}",
self.reader.decode(event.name())
)));
},
State::Binding => { State::Binding => {
if term.is_some() { if term.is_some() {
return Some(Err(format_err!( return Some(Err(format_err!(

@ -845,7 +845,8 @@ impl<S: EncodedQuadsStore> Graph for StoreUnionGraph<S> {
encoder.encode_named_or_blank_node(triple.subject())?, encoder.encode_named_or_blank_node(triple.subject())?,
encoder.encode_named_node(triple.predicate())?, encoder.encode_named_node(triple.predicate())?,
encoder.encode_term(triple.object())?, encoder.encode_term(triple.object())?,
)?.any(|_| true)) )?
.any(|_| true))
} }
fn insert(&self, _triple: &Triple) -> Result<()> { fn insert(&self, _triple: &Triple) -> Result<()> {

@ -380,7 +380,8 @@ impl<R: Read> TermReader for R {
NaiveDateTime::from_timestamp_opt( NaiveDateTime::from_timestamp_opt(
self.read_i64::<LittleEndian>()?, self.read_i64::<LittleEndian>()?,
self.read_u32::<LittleEndian>()?, self.read_u32::<LittleEndian>()?,
).ok_or_else(|| format_err!("Invalid date time serialization"))?, )
.ok_or_else(|| format_err!("Invalid date time serialization"))?,
FixedOffset::east_opt(self.read_i32::<LittleEndian>()?) FixedOffset::east_opt(self.read_i32::<LittleEndian>()?)
.ok_or_else(|| format_err!("Invalid timezone offset"))?, .ok_or_else(|| format_err!("Invalid timezone offset"))?,
))), ))),
@ -388,7 +389,8 @@ impl<R: Read> TermReader for R {
NaiveDateTime::from_timestamp_opt( NaiveDateTime::from_timestamp_opt(
self.read_i64::<LittleEndian>()?, self.read_i64::<LittleEndian>()?,
self.read_u32::<LittleEndian>()?, self.read_u32::<LittleEndian>()?,
).ok_or_else(|| format_err!("Invalid date time serialization"))?, )
.ok_or_else(|| format_err!("Invalid date time serialization"))?,
)), )),
_ => Err(format_err!("the term buffer has an invalid type id")), _ => Err(format_err!("the term buffer has an invalid type id")),
} }
@ -644,14 +646,16 @@ impl<S: StringStore> Encoder<S> {
} => Ok(Literal::new_language_tagged_literal( } => Ok(Literal::new_language_tagged_literal(
self.string_store.get_str(value_id)?, self.string_store.get_str(value_id)?,
self.string_store.get_str(language_id)?, self.string_store.get_str(language_id)?,
).into()), )
.into()),
EncodedTerm::TypedLiteral { EncodedTerm::TypedLiteral {
value_id, value_id,
datatype_id, datatype_id,
} => Ok(Literal::new_typed_literal( } => Ok(Literal::new_typed_literal(
self.string_store.get_str(value_id)?, self.string_store.get_str(value_id)?,
NamedNode::from(self.string_store.get_url(datatype_id)?), NamedNode::from(self.string_store.get_url(datatype_id)?),
).into()), )
.into()),
EncodedTerm::StringLiteral { value_id } => { EncodedTerm::StringLiteral { value_id } => {
Ok(Literal::from(self.string_store.get_str(value_id)?).into()) Ok(Literal::from(self.string_store.get_str(value_id)?).into())
} }

@ -96,10 +96,11 @@ fn turtle_w3c_testsuite() {
.map(|r| client.load_turtle(r)) .map(|r| client.load_turtle(r))
.unwrap_or_else(|| Ok(MemoryGraph::default())); .unwrap_or_else(|| Ok(MemoryGraph::default()));
assert!( assert!(
action_graph.is_err() || !action_graph action_graph.is_err()
.unwrap() || !action_graph
.is_isomorphic(&result_graph.unwrap()) .unwrap()
.unwrap(), .is_isomorphic(&result_graph.unwrap())
.unwrap(),
"Failure on {}", "Failure on {}",
test test
); );
@ -210,12 +211,13 @@ impl RDFClient {
fn get(&self, url: &Url) -> Result<Response> { fn get(&self, url: &Url) -> Result<Response> {
match self.client.get(url.clone()).send() { match self.client.get(url.clone()).send() {
Ok(response) => Ok(response), Ok(response) => Ok(response),
Err(error) => if error.description() == "parsed HTTP message from remote is incomplete" Err(error) => {
{ if error.description() == "parsed HTTP message from remote is incomplete" {
self.get(url) self.get(url)
} else { } else {
Err(format_err!("HTTP request error: {}", error.description())) Err(format_err!("HTTP request error: {}", error.description()))
}, }
}
} }
} }
} }

@ -37,7 +37,8 @@ fn sparql_w3c_syntax_testsuite() {
.unwrap(); .unwrap();
let manifest_11_url = Url::parse( let manifest_11_url = Url::parse(
"http://www.w3.org/2009/sparql/docs/tests/data-sparql11/syntax-query/manifest.ttl", "http://www.w3.org/2009/sparql/docs/tests/data-sparql11/syntax-query/manifest.ttl",
).unwrap(); )
.unwrap();
let test_blacklist = vec![ let test_blacklist = vec![
NamedNode::from_str("http://www.w3.org/2001/sw/DataAccess/tests/data-r2/syntax-sparql2/manifest#syntax-form-construct02").unwrap(), NamedNode::from_str("http://www.w3.org/2001/sw/DataAccess/tests/data-r2/syntax-sparql2/manifest#syntax-form-construct02").unwrap(),
//TODO: Deserialization of the serialization failing: //TODO: Deserialization of the serialization failing:
@ -308,12 +309,13 @@ impl RDFClient {
fn get(&self, url: &Url) -> Result<Response> { fn get(&self, url: &Url) -> Result<Response> {
match self.client.get(url.clone()).send() { match self.client.get(url.clone()).send() {
Ok(response) => Ok(response), Ok(response) => Ok(response),
Err(error) => if error.description() == "parsed HTTP message from remote is incomplete" Err(error) => {
{ if error.description() == "parsed HTTP message from remote is incomplete" {
self.get(url) self.get(url)
} else { } else {
Err(format_err!("HTTP request error: {}", error.description())) Err(format_err!("HTTP request error: {}", error.description()))
}, }
}
} }
} }
} }
@ -328,7 +330,8 @@ mod rs {
.unwrap(); .unwrap();
pub static ref RESULT_VARIABLE: NamedNode = NamedNode::from_str( pub static ref RESULT_VARIABLE: NamedNode = NamedNode::from_str(
"http://www.w3.org/2001/sw/DataAccess/tests/result-set#resultVariable" "http://www.w3.org/2001/sw/DataAccess/tests/result-set#resultVariable"
).unwrap(); )
.unwrap();
pub static ref SOLUTION: NamedNode = pub static ref SOLUTION: NamedNode =
NamedNode::from_str("http://www.w3.org/2001/sw/DataAccess/tests/result-set#solution") NamedNode::from_str("http://www.w3.org/2001/sw/DataAccess/tests/result-set#solution")
.unwrap(); .unwrap();
@ -583,7 +586,8 @@ impl<'a> Iterator for TestManifest<'a> {
.filter_map(|g| match g { .filter_map(|g| match g {
Ok(Term::NamedNode(q)) => Some(q.into()), Ok(Term::NamedNode(q)) => Some(q.into()),
_ => None, _ => None,
}).collect(); })
.collect();
(query, data, graph_data) (query, data, graph_data)
} }
Some(_) => return Some(Err(format_err!("invalid action"))), Some(_) => return Some(Err(format_err!("invalid action"))),

@ -1,7 +1,4 @@
#![cfg_attr( #![cfg_attr(feature = "cargo-clippy", allow(zero_ptr, transmute_ptr_to_ptr))]
feature = "cargo-clippy",
allow(zero_ptr, transmute_ptr_to_ptr)
)]
#[macro_use] #[macro_use]
extern crate cpython; extern crate cpython;

@ -79,18 +79,21 @@ pub fn main() -> Result<(), failure::Error> {
.long("bind") .long("bind")
.help("Specify a server socket to bind using the format $(HOST):$(PORT)") .help("Specify a server socket to bind using the format $(HOST):$(PORT)")
.takes_value(true), .takes_value(true),
).arg( )
.arg(
Arg::with_name("ntriples") Arg::with_name("ntriples")
.long("ntriples") .long("ntriples")
.help("Load a N-Triples file in the server at startup") .help("Load a N-Triples file in the server at startup")
.takes_value(true), .takes_value(true),
).arg( )
.arg(
Arg::with_name("file") Arg::with_name("file")
.long("file") .long("file")
.short("f") .short("f")
.help("File in which persist the dataset") .help("File in which persist the dataset")
.takes_value(true), .takes_value(true),
).get_matches(); )
.get_matches();
let file = matches.value_of("file").map(|v| v.to_string()); let file = matches.value_of("file").map(|v| v.to_string());
if let Some(file) = file { if let Some(file) = file {
@ -233,7 +236,8 @@ fn parse_urlencoded_query_request(query: &[u8]) -> Result<QueryRequest, failure:
.find(|(key, _)| key == "query") .find(|(key, _)| key == "query")
.map(|(_, value)| QueryRequest { .map(|(_, value)| QueryRequest {
query: value.to_string(), query: value.to_string(),
}).ok_or_else(|| format_err!("'query' parameter not found")) })
.ok_or_else(|| format_err!("'query' parameter not found"))
} }
fn evaluate_sparql_query<D: SparqlDataset + Send + Sync + RefUnwindSafe + 'static>( fn evaluate_sparql_query<D: SparqlDataset + Send + Sync + RefUnwindSafe + 'static>(
@ -309,7 +313,8 @@ mod tests {
"http://localhost/query", "http://localhost/query",
"SELECT * WHERE { ?s ?p ?o }", "SELECT * WHERE { ?s ?p ?o }",
Mime::from_str("application/sparql-query").unwrap(), Mime::from_str("application/sparql-query").unwrap(),
).perform() )
.perform()
.unwrap(); .unwrap();
assert_eq!(response.status(), StatusCode::OK); assert_eq!(response.status(), StatusCode::OK);
} }

Loading…
Cancel
Save