1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
use crate::errors::YdbResult;
use crate::types::Value;
use std::collections::HashMap;
use std::str::FromStr;
use crate::YdbError;
use ydb_grpc::ydb_proto::TypedValue;
/// Query object
#[derive(Clone)]
pub struct Query {
pub(crate) text: String,
pub(crate) parameters: HashMap<String, Value>,
pub(crate) keep_in_cache: bool,
}
impl Query {
/// Create query with query text
pub fn new<T: Into<String>>(query: T) -> Self {
Query {
text: query.into(),
parameters: HashMap::new(),
keep_in_cache: false,
}
}
/// Set query parameters
///
/// parameters is data, sent to YDB in binary form
///
/// Example with macros:
/// ```
/// # use ydb::{ydb_params, Query};
/// let query = Query::new("
/// DECLARE $val AS Int64;
///
/// SELECT $val AS res
/// ").with_params(ydb_params!("$val" => 123 as i64));
/// ```
///
/// Example full:
/// ```
/// # use std::collections::HashMap;
/// # use ydb::{Query, Value};
/// let mut params: HashMap::<String,Value> = HashMap::new();
/// params.insert("$val".to_string(), Value::from(123 as i64));
/// let query = Query::new("
/// DECLARE $val AS Int64;
///
/// SELECT $val AS res
/// ").with_params(params);
/// ```
pub fn with_params(mut self, params: HashMap<String, Value>) -> Self {
self.parameters = params;
self.keep_in_cache = !self.parameters.is_empty();
self
}
pub(crate) fn query_to_proto(&self) -> ydb_grpc::ydb_proto::table::Query {
ydb_grpc::ydb_proto::table::Query {
query: Some(ydb_grpc::ydb_proto::table::query::Query::YqlText(
self.text.clone(),
)),
}
}
pub(crate) fn params_to_proto(self) -> YdbResult<HashMap<String, TypedValue>> {
let mut params = HashMap::with_capacity(self.parameters.len());
for (name, val) in self.parameters.into_iter() {
params.insert(name, val.to_typed_value()?);
}
Ok(params)
}
}
impl From<&str> for Query {
fn from(s: &str) -> Self {
Query::new(s)
}
}
impl From<String> for Query {
fn from(s: String) -> Self {
Query::new(s)
}
}
impl FromStr for Query {
type Err = YdbError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Query::new(s))
}
}