Skip to content

Commit 72766ff

Browse files
committed
perf(cognitarium): use resolved variables to construct atoms
1 parent 61ff078 commit 72766ff

File tree

2 files changed

+87
-72
lines changed

2 files changed

+87
-72
lines changed

contracts/okp4-cognitarium/src/contract.rs

+23-27
Original file line numberDiff line numberDiff line change
@@ -145,12 +145,12 @@ pub fn query(deps: Deps<'_>, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
145145
pub mod query {
146146
use super::*;
147147
use crate::msg::{
148-
ConstructQuery, ConstructResponse, DescribeQuery, DescribeResponse, HasVariables, Node,
149-
SelectQuery, SelectResponse, SimpleWhereCondition, StoreResponse, TripleConstructTemplate,
148+
ConstructQuery, ConstructResponse, DescribeQuery, DescribeResponse, Node, SelectQuery,
149+
SelectResponse, SimpleWhereCondition, StoreResponse, TripleConstructTemplate,
150150
TriplePattern, VarOrNamedNode, VarOrNode, VarOrNodeOrLiteral, WhereCondition,
151151
};
152152
use crate::querier::{PlanBuilder, QueryEngine};
153-
use crate::rdf::PrefixMap;
153+
use crate::rdf::{Atom, PrefixMap};
154154
use crate::state::HasCachedNamespaces;
155155
use okp4_rdf::normalize::IdentifierIssuer;
156156
use okp4_rdf::serde::TripleWriter;
@@ -228,18 +228,16 @@ pub mod query {
228228
let plan = plan_builder.build_plan(&r#where)?;
229229

230230
let atoms = QueryEngine::new(deps.storage)
231-
.select(plan, select.as_select_item())
232-
.and_then(|res| {
233-
res.solutions.resolve_atoms(
234-
deps.storage,
235-
&prefix_map,
236-
select
237-
.into_iter()
238-
.map(|p| (p.subject, p.predicate, p.object))
239-
.collect(),
240-
plan_builder.cached_namespaces(),
241-
)
242-
})?;
231+
.construct_atoms(
232+
plan,
233+
&prefix_map,
234+
select
235+
.into_iter()
236+
.map(|t| (t.subject, t.predicate, t.object))
237+
.collect(),
238+
plan_builder.cached_namespaces(),
239+
)?
240+
.collect::<StdResult<Vec<Atom>>>()?;
243241

244242
let out: Vec<u8> = Vec::default();
245243
let mut writer = TripleWriter::new(&(&format).into(), out);
@@ -317,18 +315,16 @@ pub mod query {
317315
let plan = plan_builder.build_plan(&r#where)?;
318316

319317
let atoms = QueryEngine::new(deps.storage)
320-
.select(plan, construct.as_select_item())
321-
.and_then(|res| {
322-
res.solutions.resolve_atoms(
323-
deps.storage,
324-
&prefix_map,
325-
construct
326-
.into_iter()
327-
.map(|t| (t.subject, t.predicate, t.object))
328-
.collect(),
329-
plan_builder.cached_namespaces(),
330-
)
331-
})?;
318+
.construct_atoms(
319+
plan,
320+
&prefix_map,
321+
construct
322+
.into_iter()
323+
.map(|t| (t.subject, t.predicate, t.object))
324+
.collect(),
325+
plan_builder.cached_namespaces(),
326+
)?
327+
.collect::<StdResult<Vec<Atom>>>()?;
332328

333329
let out: Vec<u8> = Vec::default();
334330
let mut writer = TripleWriter::new(&(&format).into(), out);

contracts/okp4-cognitarium/src/querier/engine.rs

+64-45
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,27 @@ impl<'a> QueryEngine<'a> {
5454
})
5555
}
5656

57+
pub fn construct_atoms(
58+
&'a self,
59+
plan: QueryPlan,
60+
prefixes: &HashMap<String, String>,
61+
templates: Vec<(VarOrNode, VarOrNamedNode, VarOrNodeOrLiteral)>,
62+
ns_cache: Vec<Namespace>,
63+
) -> StdResult<ResolvedAtomIterator<'_>> {
64+
let templates = templates
65+
.into_iter()
66+
.map(|t| AtomTemplate::try_new(&plan, prefixes, t))
67+
.collect::<StdResult<Vec<AtomTemplate>>>()?;
68+
69+
ResolvedAtomIterator::try_new(
70+
self.storage,
71+
ns_cache.into(),
72+
IdentifierIssuer::new("b", 0u128),
73+
self.eval_plan(plan),
74+
templates,
75+
)
76+
}
77+
5778
pub fn eval_plan(&'a self, plan: QueryPlan) -> ResolvedVariablesIterator<'_> {
5879
return self.eval_node(plan.entrypoint)(ResolvedVariables::with_capacity(
5980
plan.variables.len(),
@@ -451,20 +472,6 @@ impl<'a> SolutionsIterator<'a> {
451472
ResolvedTripleIterator::try_new(&mut ns_resolver, storage, self, prefixes, templates)?;
452473
triples_iter.collect()
453474
}
454-
455-
pub fn resolve_atoms(
456-
self,
457-
storage: &dyn Storage,
458-
prefixes: &HashMap<String, String>,
459-
templates: Vec<(VarOrNode, VarOrNamedNode, VarOrNodeOrLiteral)>,
460-
ns_cache: Vec<Namespace>,
461-
) -> StdResult<Vec<Atom>> {
462-
let mut ns_resolver = ns_cache.into();
463-
464-
let atoms_iter =
465-
ResolvedAtomIterator::try_new(&mut ns_resolver, storage, self, prefixes, templates)?;
466-
atoms_iter.collect()
467-
}
468475
}
469476

470477
impl<'a> Iterator for SolutionsIterator<'a> {
@@ -684,31 +691,28 @@ impl TripleTemplate {
684691
}
685692

686693
pub struct ResolvedAtomIterator<'a> {
687-
ns_resolver: &'a mut NamespaceResolver,
688-
id_issuer: IdentifierIssuer,
689694
storage: &'a dyn Storage,
690-
iter: SolutionsIterator<'a>,
695+
ns_resolver: NamespaceResolver,
696+
id_issuer: IdentifierIssuer,
697+
upstream_iter: ResolvedVariablesIterator<'a>,
691698
templates: Vec<AtomTemplate>,
692699
buffer: VecDeque<StdResult<Atom>>,
693700
}
694701

695702
impl<'a> ResolvedAtomIterator<'a> {
696703
pub fn try_new(
697-
ns_resolver: &'a mut NamespaceResolver,
698704
storage: &'a dyn Storage,
699-
solutions: SolutionsIterator<'a>,
700-
prefixes: &HashMap<String, String>,
701-
templates: Vec<(VarOrNode, VarOrNamedNode, VarOrNodeOrLiteral)>,
705+
ns_resolver: NamespaceResolver,
706+
id_issuer: IdentifierIssuer,
707+
upstream_iter: ResolvedVariablesIterator<'a>,
708+
templates: Vec<AtomTemplate>,
702709
) -> StdResult<Self> {
703710
Ok(Self {
704-
ns_resolver,
705-
id_issuer: IdentifierIssuer::new("b", 0u128),
706711
storage,
707-
iter: solutions,
708-
templates: templates
709-
.into_iter()
710-
.map(|t| AtomTemplate::try_new(prefixes, t))
711-
.collect::<StdResult<Vec<AtomTemplate>>>()?,
712+
ns_resolver,
713+
id_issuer,
714+
upstream_iter,
715+
templates,
712716
buffer: VecDeque::new(),
713717
})
714718
}
@@ -723,7 +727,7 @@ impl<'a> Iterator for ResolvedAtomIterator<'a> {
723727
return Some(val);
724728
}
725729

726-
let upstream_res = match self.iter.next() {
730+
let upstream_res = match self.upstream_iter.next() {
727731
None => None?,
728732
Some(res) => res,
729733
};
@@ -734,7 +738,12 @@ impl<'a> Iterator for ResolvedAtomIterator<'a> {
734738
}
735739
Ok(vars) => {
736740
for res in self.templates.iter().map(|template| {
737-
template.resolve(self.ns_resolver, &mut self.id_issuer, self.storage, &vars)
741+
template.resolve(
742+
self.storage,
743+
&mut self.ns_resolver,
744+
&mut self.id_issuer,
745+
&vars,
746+
)
738747
}) {
739748
match res {
740749
Ok(Some(atom)) => self.buffer.push_back(Ok(atom)),
@@ -748,28 +757,38 @@ impl<'a> Iterator for ResolvedAtomIterator<'a> {
748757
}
749758
}
750759

751-
struct AtomTemplate {
752-
subject: Either<rdf::Subject, String>,
753-
property: Either<rdf::Property, String>,
754-
value: Either<rdf::Value, String>,
760+
pub struct AtomTemplate {
761+
subject: Either<rdf::Subject, usize>,
762+
property: Either<rdf::Property, usize>,
763+
value: Either<rdf::Value, usize>,
755764
}
756765

757766
impl AtomTemplate {
758767
pub fn try_new(
768+
plan: &QueryPlan,
759769
prefixes: &HashMap<String, String>,
760770
(s_tpl, p_tpl, o_tpl): (VarOrNode, VarOrNamedNode, VarOrNodeOrLiteral),
761771
) -> StdResult<AtomTemplate> {
762772
Ok(Self {
763773
subject: match s_tpl {
764-
VarOrNode::Variable(key) => Right(key),
774+
VarOrNode::Variable(key) => Right(plan.get_var_index(key.as_str()).ok_or(
775+
StdError::generic_err("Selected variable not found in query"),
776+
)?),
765777
VarOrNode::Node(n) => Left((n, prefixes).try_into()?),
766778
},
767779
property: match p_tpl {
768-
VarOrNamedNode::Variable(key) => Right(key),
780+
VarOrNamedNode::Variable(key) => Right(plan.get_var_index(key.as_str()).ok_or(
781+
StdError::generic_err("Selected variable not found in query"),
782+
)?),
769783
VarOrNamedNode::NamedNode(iri) => Left((iri, prefixes).try_into()?),
770784
},
771785
value: match o_tpl {
772-
VarOrNodeOrLiteral::Variable(key) => Right(key),
786+
VarOrNodeOrLiteral::Variable(key) => Right(
787+
plan.get_var_index(key.as_str())
788+
.ok_or(StdError::generic_err(
789+
"Selected variable not found in query",
790+
))?,
791+
),
773792
VarOrNodeOrLiteral::Node(n) => Left((n, prefixes).try_into()?),
774793
VarOrNodeOrLiteral::Literal(l) => Left((l, prefixes).try_into()?),
775794
},
@@ -778,10 +797,10 @@ impl AtomTemplate {
778797

779798
pub fn resolve(
780799
&self,
800+
storage: &dyn Storage,
781801
ns_resolver: &mut NamespaceResolver,
782802
id_issuer: &mut IdentifierIssuer,
783-
storage: &dyn Storage,
784-
vars: &BTreeMap<String, ResolvedVariable>,
803+
vars: &ResolvedVariables,
785804
) -> StdResult<Option<Atom>> {
786805
let resolve_ns_fn = &mut |ns_key| {
787806
let res = ns_resolver.resolve_from_key(storage, ns_key);
@@ -815,7 +834,7 @@ impl AtomTemplate {
815834
&self,
816835
resolve_ns_fn: &mut F,
817836
id_issuer: &mut IdentifierIssuer,
818-
vars: &BTreeMap<String, ResolvedVariable>,
837+
vars: &ResolvedVariables,
819838
) -> StdResult<Option<rdf::Subject>>
820839
where
821840
F: FnMut(u128) -> StdResult<String>,
@@ -839,7 +858,7 @@ impl AtomTemplate {
839858
fn resolve_atom_property<F>(
840859
&self,
841860
resolve_ns_fn: &mut F,
842-
vars: &BTreeMap<String, ResolvedVariable>,
861+
vars: &ResolvedVariables,
843862
) -> StdResult<Option<rdf::Property>>
844863
where
845864
F: FnMut(u128) -> StdResult<String>,
@@ -857,7 +876,7 @@ impl AtomTemplate {
857876
&self,
858877
resolve_ns_fn: &mut F,
859878
id_issuer: &mut IdentifierIssuer,
860-
vars: &BTreeMap<String, ResolvedVariable>,
879+
vars: &ResolvedVariables,
861880
) -> StdResult<Option<rdf::Value>>
862881
where
863882
F: FnMut(u128) -> StdResult<String>,
@@ -888,9 +907,9 @@ impl AtomTemplate {
888907
}
889908

890909
fn resolve_atom_term<A, T, F, M>(
891-
term: &Either<A, String>,
910+
term: &Either<A, usize>,
892911
from_var: F,
893-
vars: &BTreeMap<String, ResolvedVariable>,
912+
vars: &ResolvedVariables,
894913
mapping_fn: &mut M,
895914
term_name: &str,
896915
) -> StdResult<Option<A>>
@@ -902,7 +921,7 @@ impl AtomTemplate {
902921
match term {
903922
Left(v) => Ok(Some(v.clone())),
904923
Right(key) => {
905-
let var = vars.get(key).ok_or_else(|| {
924+
let var = vars.get(*key).as_ref().ok_or_else(|| {
906925
StdError::generic_err(format!("Unbound {:?} variable: {:?}", term_name, key))
907926
})?;
908927

0 commit comments

Comments
 (0)