orientdb_client/sync/
statement.rs1use super::session::OSession;
2use crate::common::protocol::messages::request::Query;
3use crate::common::types::value::{IntoOValue, OValue};
4use crate::sync::types::resultset::ResultSet;
5#[cfg(feature = "sugar")]
6use crate::types::result::FromResult;
7use crate::OrientResult;
8use std::collections::HashMap;
9
10pub struct Statement<'a> {
11 session: &'a OSession,
12 stm: String,
13 params: HashMap<String, OValue>,
14 language: String,
15 page_size: i32,
16 mode: i8,
17 named: bool,
18}
19
20impl<'a> Statement<'a> {
21 pub(crate) fn new(session: &'a OSession, stm: String) -> Statement<'a> {
22 Statement {
23 session,
24 stm,
25 params: HashMap::new(),
26 named: true,
27 mode: 1,
28 language: String::from("sql"),
29 page_size: 150,
30 }
31 }
32 pub(crate) fn mode(mut self, mode: i8) -> Self {
33 self.mode = mode;
34 self
35 }
36
37 pub(crate) fn language(mut self, language: String) -> Self {
38 self.language = language;
39 self
40 }
41
42 pub fn positional(mut self, params: &[&dyn IntoOValue]) -> Self {
43 let mut p = HashMap::new();
44 for (i, elem) in params.iter().enumerate() {
45 p.insert(i.to_string(), elem.into_ovalue());
46 }
47 self.params = p;
48 self.named = false;
49 self
50 }
51 pub fn named(mut self, params: &[(&str, &dyn IntoOValue)]) -> Self {
52 self.params = params
53 .iter()
54 .map(|&(k, ref v)| (String::from(k), v.into_ovalue()))
55 .collect();
56
57 self.named = true;
58 self
59 }
60
61 pub fn page_size(mut self, page_size: i32) -> Self {
62 self.page_size = page_size;
63 self
64 }
65 pub fn run(self) -> OrientResult<impl ResultSet> {
66 self.session.run(self.into())
67 }
68
69 #[cfg(feature = "sugar")]
70 pub fn fetch_one<T>(self) -> OrientResult<Option<T>>
71 where
72 T: FromResult,
73 {
74 match self
75 .session
76 .run(self.into())?
77 .map(|r| r.and_then(T::from_result))
78 .next()
79 {
80 Some(s) => Ok(Some(s?)),
81 None => Ok(None),
82 }
83 }
84
85 #[cfg(feature = "sugar")]
86 pub fn fetch<T>(self) -> OrientResult<Vec<T>>
87 where
88 T: FromResult,
89 {
90 self.session
91 .run(self.into())?
92 .map(|r| r.and_then(T::from_result))
93 .collect()
94 }
95
96 #[cfg(feature = "sugar")]
97 pub fn iter<T>(self) -> OrientResult<impl std::iter::Iterator<Item = OrientResult<T>>>
98 where
99 T: FromResult,
100 {
101 Ok(self
102 .session
103 .run(self.into())?
104 .map(|r| r.and_then(T::from_result)))
105 }
106}
107
108impl<'a> From<Statement<'a>> for Query {
109 fn from(x: Statement) -> Query {
110 Query {
111 session_id: x.session.session_id,
112 token: x.session.token.clone(),
113 query: x.stm,
114 language: x.language,
115 named: x.named,
116 parameters: x.params,
117 page_size: x.page_size,
118 mode: x.mode,
119 }
120 }
121}