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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
use crate::error::OdbcHelperError;
use crate::TryConvert;
use either::Either;
use odbc_api::parameter::InputParameter;
use std::fmt::Debug;
pub(crate) type EitherBoxParams = Either<Vec<Box<dyn InputParameter>>, ()>;
pub trait StatementInput {
type Item: SqlValue;
fn to_value(self) -> Either<Vec<Self::Item>, ()>;
fn to_sql(&self) -> &str;
fn values(self) -> Result<EitherBoxParams, OdbcHelperError>
where
Self: Sized,
{
let params: EitherBoxParams = self.try_convert()?;
Ok(params)
}
}
pub trait SqlValue {
fn to_value(self) -> Either<Box<dyn InputParameter>, ()>;
}
#[derive(Debug)]
pub struct Statement<T: Debug> {
pub sql: String,
pub values: Vec<T>,
}
impl<T> Statement<T>
where
T: SqlValue + Debug,
{
pub fn new<S: Into<String>>(sql: S, values: Vec<T>) -> Self {
Statement {
sql: sql.into(),
values,
}
}
}
impl SqlValue for &str {
fn to_value(self) -> Either<Box<dyn InputParameter>, ()> {
Either::Right(())
}
}
impl SqlValue for String {
fn to_value(self) -> Either<Box<dyn InputParameter>, ()> {
Either::Right(())
}
}
impl<T> StatementInput for Statement<T>
where
T: SqlValue + Debug,
{
type Item = T;
fn to_value(self) -> Either<Vec<T>, ()> {
Either::Left(self.values)
}
fn to_sql(&self) -> &str {
&self.sql
}
}
impl StatementInput for &str {
type Item = Self;
fn to_value(self) -> Either<Vec<Self::Item>, ()> {
Either::Right(())
}
fn to_sql(&self) -> &str {
self
}
}
impl StatementInput for String {
type Item = Self;
fn to_value(self) -> Either<Vec<Self::Item>, ()> {
Either::Right(())
}
fn to_sql(&self) -> &str {
self
}
}
impl<T: StatementInput> TryConvert<EitherBoxParams> for T {
type Error = OdbcHelperError;
fn try_convert(self) -> Result<EitherBoxParams, Self::Error> {
match self.to_value() {
Either::Left(values) => {
let params: Result<Vec<_>, Self::Error> = values
.into_iter()
.map(|v| v.to_value())
.map(|x| {
x.left().ok_or_else(|| {
OdbcHelperError::SqlParamsError("value not include empty tuple".into())
})
})
.collect();
Ok(Either::Left(params?))
}
Either::Right(values) => Ok(Either::Right(values)),
}
}
}