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
use crate::TryConvert;
use either::Either;
use odbc_api::parameter::InputParameter;
use std::fmt::Debug;
pub trait StatementInput {
type Item: SqlValue;
fn to_value(self) -> Either<Vec<Self::Item>, ()>;
fn to_sql(&self) -> &str;
}
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
}
}
pub type EitherBoxParams = Either<Vec<Box<dyn InputParameter>>, ()>;
impl<T: StatementInput> TryConvert<EitherBoxParams> for T {
type Error = &'static str;
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("value not include empty tuple"))
.collect();
Ok(Either::Left(params?))
}
Either::Right(values) => Ok(Either::Right(values)),
}
}
}