Skip to content

Commit

Permalink
Redo errors without dyn
Browse files Browse the repository at this point in the history
  • Loading branch information
magbak committed Aug 14, 2024
1 parent bf850de commit f00b17a
Show file tree
Hide file tree
Showing 13 changed files with 116 additions and 172 deletions.
9 changes: 4 additions & 5 deletions lib/chrontext/src/combiner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,24 @@ pub(crate) mod virtualized_queries;
use representation::query_context::Context;

use crate::preparing::TimeseriesQueryPrepper;
use crate::sparql_database::SparqlQueryable;
use crate::sparql_database::{SparqlQueryError, SparqlQueryable};
use query_processing::errors::QueryProcessingError;
use representation::solution_mapping::SolutionMappings;
use spargebra::algebra::Expression;
use spargebra::Query;
use std::collections::{HashMap, HashSet};
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::sync::Arc;
use thiserror::Error;
use virtualization::errors::VirtualizedDatabaseError;
use virtualization::errors::ChrontextError;
use virtualization::{Virtualization, VirtualizedDatabase};
use virtualized_query::pushdown_setting::PushdownSetting;
use virtualized_query::{BasicVirtualizedQuery, VirtualizedResultValidationError};

#[derive(Debug, Error)]
pub enum CombinerError {
VirtualizedDatabaseError(VirtualizedDatabaseError),
StaticQueryExecutionError(Box<dyn Error>),
VirtualizedDatabaseError(ChrontextError),
StaticQueryExecutionError(SparqlQueryError),
QueryProcessingError(#[from] QueryProcessingError),
InconsistentDatatype(String, String, String),
TimeseriesValidationError(VirtualizedResultValidationError),
Expand Down
8 changes: 4 additions & 4 deletions lib/chrontext/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ use representation::query_context::Context;
use representation::solution_mapping::SolutionMappings;
use representation::RDFNodeType;
use std::collections::{HashMap, HashSet};
use std::error::Error;
use std::sync::Arc;
use virtualization::{Virtualization, VirtualizedDatabase};
use virtualized_query::pushdown_setting::PushdownSetting;
Expand Down Expand Up @@ -79,7 +78,7 @@ impl Engine {
pub async fn query<'py>(
&self,
query: &str,
) -> Result<(DataFrame, HashMap<String, RDFNodeType>, Vec<Context>), Box<dyn Error>> {
) -> Result<(DataFrame, HashMap<String, RDFNodeType>, Vec<Context>), ChrontextError> {
enable_string_cache();
let parsed_query = parse_sparql_select_query(query)?;
debug!("Parsed query: {}", parsed_query.to_string());
Expand Down Expand Up @@ -115,14 +114,15 @@ impl Engine {
);
let solution_mappings = combiner
.combine_static_and_time_series_results(static_queries_map, &preprocessed_query)
.await?;
.await
.map_err(|x| ChrontextError::CombinerError(x))?;
let SolutionMappings {
mappings,
rdf_node_types,
} = solution_mappings;

Ok((
mappings.collect()?,
mappings.collect().unwrap(),
rdf_node_types,
combiner.virtualized_contexts,
))
Expand Down
33 changes: 10 additions & 23 deletions lib/chrontext/src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,30 +1,17 @@
use std::fmt::{Display, Formatter};
use crate::combiner::CombinerError;
use crate::splitter::QueryParseError;
use thiserror::Error;

#[derive(Debug, Error)]
pub enum ChrontextError {
FromJSONFileError(String),
#[error("Missing SPARQL database")]
NoSPARQLDatabaseDefined,
#[error("Error creating SPARQL database `{0}`")]
CreateSPARQLDatabaseError(String),
DeserializeFromJSONFileError(String),
#[error("No timeseries database defined")]
NoTimeseriesDatabaseDefined,
}

impl Display for ChrontextError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
ChrontextError::FromJSONFileError(s) => {
write!(f, "Error reading engine config from JSON: {}", s)
}
ChrontextError::NoSPARQLDatabaseDefined => write!(f, "Missing SPARQL database"),
ChrontextError::CreateSPARQLDatabaseError(s) => {
write!(f, "Error creating SPARQL database {}", s)
}
ChrontextError::DeserializeFromJSONFileError(s) => {
write!(f, "Error deserializing config from JSON file {}", s)
}
ChrontextError::NoTimeseriesDatabaseDefined => {
write!(f, "No timeseries database defined")
}
}
}
#[error(transparent)]
QueryParseError(#[from] QueryParseError),
#[error(transparent)]
CombinerError(#[from] CombinerError),
}
13 changes: 11 additions & 2 deletions lib/chrontext/src/sparql_database.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
pub mod sparql_embedded_oxigraph;
pub mod sparql_endpoint;

use crate::sparql_database::sparql_embedded_oxigraph::EmbeddedOxigraphError;
use crate::sparql_database::sparql_endpoint::SparqlEndpointQueryExecutionError;
use async_trait::async_trait;
use sparesults::QuerySolution;
use spargebra::Query;
use std::error::Error;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum SparqlQueryError {
#[error(transparent)]
EmbeddedOxigraphError(#[from] EmbeddedOxigraphError),
#[error(transparent)]
SparqlEndpointQueryExecutionError(#[from] SparqlEndpointQueryExecutionError),
}

#[async_trait]
pub trait SparqlQueryable: Send + Sync {
async fn execute(&self, query: &Query) -> Result<Vec<QuerySolution>, Box<dyn Error>>;
async fn execute(&self, query: &Query) -> Result<Vec<QuerySolution>, SparqlQueryError>;
}
46 changes: 20 additions & 26 deletions lib/chrontext/src/sparql_database/sparql_embedded_oxigraph.rs
Original file line number Diff line number Diff line change
@@ -1,46 +1,32 @@
use super::SparqlQueryable;
use super::{SparqlQueryError, SparqlQueryable};
use async_trait::async_trait;
use filesize::PathExt;
use oxigraph::io::{RdfFormat, RdfParser};
use oxigraph::sparql::QueryResults;
use oxigraph::store::Store;
use sparesults::QuerySolution;
use spargebra::Query;
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::fs::{read_to_string, File};
use std::io::BufReader;
use std::io::Write;
use std::path::Path;
use std::time::SystemTime;
use thiserror::Error;

const RDF_FILE_METADATA: &str = "rdf_file_data.txt";

#[derive(Debug)]
#[derive(Debug, Error)]
pub enum EmbeddedOxigraphError {
#[error("Error opening oxigraph storage path `{0}`")]
OpenStorageError(String),
#[error("Error reading NTriples file `{0}`")]
ReadNTriplesFileError(String),
#[error("Error reading loading NTriples file `{0}`")]
LoaderError(String),
#[error("Oxigraph metadata IO Error `{0}`")]
DBMetadataIOError(String),
}

impl Display for EmbeddedOxigraphError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
EmbeddedOxigraphError::OpenStorageError(o) => {
write!(f, "Error opening oxigraph storage path {}", o)
}
EmbeddedOxigraphError::ReadNTriplesFileError(s) => {
write!(f, "Error reading NTriples file {}", s)
}
EmbeddedOxigraphError::LoaderError(s) => {
write!(f, "Error reading loading NTriples file {}", s)
}
EmbeddedOxigraphError::DBMetadataIOError(s) => {
write!(f, "Oxigraph metadata IO Error {}", s)
}
}
}
#[error("Oxigraph evaluation error")]
EvaluationError(String),
}

#[derive(Debug)]
Expand All @@ -56,14 +42,22 @@ pub struct EmbeddedOxigraph {

#[async_trait]
impl SparqlQueryable for EmbeddedOxigraph {
async fn execute(&self, query: &Query) -> Result<Vec<QuerySolution>, Box<dyn Error>> {
async fn execute(&self, query: &Query) -> Result<Vec<QuerySolution>, SparqlQueryError> {
let oxiquery = oxigraph::sparql::Query::parse(query.to_string().as_str(), None).unwrap();
let res = self.store.query(oxiquery).map_err(|x| Box::new(x))?;
let res = self.store.query(oxiquery).map_err(|x| {
SparqlQueryError::EmbeddedOxigraphError(EmbeddedOxigraphError::EvaluationError(
x.to_string(),
))
})?;
match res {
QueryResults::Solutions(sols) => {
let mut output = vec![];
for s in sols {
output.push(s?);
output.push(s.map_err(|x| {
SparqlQueryError::EmbeddedOxigraphError(
EmbeddedOxigraphError::EvaluationError(x.to_string()),
)
})?);
}
Ok(output)
}
Expand Down
72 changes: 27 additions & 45 deletions lib/chrontext/src/sparql_database/sparql_endpoint.rs
Original file line number Diff line number Diff line change
@@ -1,52 +1,33 @@
use super::SparqlQueryable;
use super::{SparqlQueryError, SparqlQueryable};
use async_trait::async_trait;
use reqwest::header::{ACCEPT, USER_AGENT};
use reqwest::StatusCode;
use sparesults::{
FromReadQueryResultsReader, QueryResultsFormat, QueryResultsParseError, QueryResultsParser,
QuerySolution,
};
use spargebra::Query;
use std::error::Error;
use std::fmt::{Display, Formatter};
use thiserror::Error;

#[derive(Debug)]
pub enum QueryExecutionError {
#[derive(Debug, Error)]
pub enum SparqlEndpointQueryExecutionError {
#[error(transparent)]
RequestError(reqwest::Error),
BadStatusCode(StatusCode),
#[error("Bad status code `{0}`")]
BadStatusCode(String),
#[error("Results parse error `{0}`")]
ResultsParseError(QueryResultsParseError),
#[error("Solution parse error `{0}`")]
SolutionParseError(QueryResultsParseError),
#[error("Wrong result type, expected solutions")]
WrongResultType,
}

impl Display for QueryExecutionError {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
match &self {
QueryExecutionError::RequestError(reqerr) => std::fmt::Display::fmt(&reqerr, f),
QueryExecutionError::BadStatusCode(status_code) => {
std::fmt::Display::fmt(&status_code, f)
}
QueryExecutionError::ResultsParseError(parseerr) => {
std::fmt::Display::fmt(&parseerr, f)
}
QueryExecutionError::SolutionParseError(parseerr) => {
std::fmt::Display::fmt(&parseerr, f)
}
QueryExecutionError::WrongResultType => {
write!(f, "Wrong result type, expected solutions")
}
}
}
}

impl Error for QueryExecutionError {}

pub struct SparqlEndpoint {
pub endpoint: String,
}
#[async_trait]
impl SparqlQueryable for SparqlEndpoint {
async fn execute(&self, query: &Query) -> Result<Vec<QuerySolution>, Box<dyn Error>> {
async fn execute(&self, query: &Query) -> Result<Vec<QuerySolution>, SparqlQueryError> {
let client = reqwest::Client::new();
let response = client
.get(&self.endpoint)
Expand All @@ -59,9 +40,10 @@ impl SparqlQueryable for SparqlEndpoint {
match response {
Ok(proper_response) => {
if proper_response.status().as_u16() != 200 {
Err(Box::new(QueryExecutionError::BadStatusCode(
proper_response.status(),
)))
Err(SparqlEndpointQueryExecutionError::BadStatusCode(
proper_response.status().to_string(),
)
.into())
} else {
let text = proper_response.text().await.expect("Read text error");
let json_parser = QueryResultsParser::from_format(QueryResultsFormat::Json);
Expand All @@ -73,27 +55,27 @@ impl SparqlQueryable for SparqlEndpoint {
for s in solutions {
match s {
Ok(query_solution) => solns.push(query_solution),
Err(parse_error) => {
return Err(Box::new(
QueryExecutionError::SolutionParseError(
parse_error,
),
))
}
Err(parse_error) => return Err(
SparqlEndpointQueryExecutionError::SolutionParseError(
parse_error,
)
.into(),
),
}
}
Ok(solns)
} else {
Err(Box::new(QueryExecutionError::WrongResultType))
Err(SparqlEndpointQueryExecutionError::WrongResultType.into())
}
}
Err(parse_error) => Err(Box::new(QueryExecutionError::ResultsParseError(
parse_error,
))),
Err(parse_error) => Err(
SparqlEndpointQueryExecutionError::ResultsParseError(parse_error)
.into(),
),
}
}
}
Err(error) => Err(Box::new(QueryExecutionError::RequestError(error))),
Err(error) => Err(SparqlEndpointQueryExecutionError::RequestError(error).into()),
}
}
}
Loading

0 comments on commit f00b17a

Please sign in to comment.