-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathimpls.rs
More file actions
235 lines (213 loc) · 7.17 KB
/
impls.rs
File metadata and controls
235 lines (213 loc) · 7.17 KB
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
use postgres_protocol::{self as protocol, types};
use postgres_types::private::BytesMut;
use postgres_types::{FromSql, IsNull, Kind, ToSql, Type};
use std::error::Error;
use crate::{BoundSided, BoundType, Normalizable, Range, RangeBound};
impl<'a, T> FromSql<'a> for Range<T>
where
T: PartialOrd + Normalizable + FromSql<'a>,
{
fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<Range<T>, Box<dyn Error + Sync + Send>> {
let element_type = match *ty.kind() {
Kind::Range(ref ty) => ty,
_ => panic!("unexpected type {:?}", ty),
};
match types::range_from_sql(raw)? {
types::Range::Empty => Ok(Range::empty()),
types::Range::Nonempty(lower, upper) => {
let lower = bound_from_sql(lower, element_type)?;
let upper = bound_from_sql(upper, element_type)?;
Ok(Range::new(lower, upper))
}
}
}
fn accepts(ty: &Type) -> bool {
match *ty.kind() {
Kind::Range(ref inner) => <T as FromSql>::accepts(inner),
_ => false,
}
}
}
fn bound_from_sql<'a, T, S>(
bound: types::RangeBound<Option<&'a [u8]>>,
ty: &Type,
) -> Result<Option<RangeBound<S, T>>, Box<dyn Error + Sync + Send>>
where
T: PartialOrd + Normalizable + FromSql<'a>,
S: BoundSided,
{
match bound {
types::RangeBound::Exclusive(value) => {
let value = match value {
Some(value) => T::from_sql(ty, value)?,
None => T::from_sql_null(ty)?,
};
Ok(Some(RangeBound::new(value, BoundType::Exclusive)))
}
types::RangeBound::Inclusive(value) => {
let value = match value {
Some(value) => T::from_sql(ty, value)?,
None => T::from_sql_null(ty)?,
};
Ok(Some(RangeBound::new(value, BoundType::Inclusive)))
}
types::RangeBound::Unbounded => Ok(None),
}
}
impl<T> ToSql for Range<T>
where
T: PartialOrd + Normalizable + ToSql,
{
fn to_sql(
&self,
ty: &Type,
buf: &mut BytesMut,
) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
let element_type = match *ty.kind() {
Kind::Range(ref ty) => ty,
_ => panic!("unexpected type {:?}", ty),
};
if self.is_empty() {
types::empty_range_to_sql(buf);
} else {
types::range_to_sql(
|buf| bound_to_sql(self.lower(), element_type, buf),
|buf| bound_to_sql(self.upper(), element_type, buf),
buf,
)?;
}
Ok(IsNull::No)
}
fn accepts(ty: &Type) -> bool {
match *ty.kind() {
Kind::Range(ref inner) => <T as ToSql>::accepts(inner),
_ => false,
}
}
to_sql_checked!();
}
fn bound_to_sql<S, T>(
bound: Option<&RangeBound<S, T>>,
ty: &Type,
buf: &mut BytesMut,
) -> Result<types::RangeBound<protocol::IsNull>, Box<dyn Error + Sync + Send>>
where
S: BoundSided,
T: ToSql,
{
match bound {
Some(bound) => {
let null = match bound.value.to_sql(ty, buf)? {
IsNull::Yes => protocol::IsNull::Yes,
IsNull::No => protocol::IsNull::No,
};
match bound.type_ {
BoundType::Exclusive => Ok(types::RangeBound::Exclusive(null)),
BoundType::Inclusive => Ok(types::RangeBound::Inclusive(null)),
}
}
None => Ok(types::RangeBound::Unbounded),
}
}
#[cfg(test)]
mod test {
use std::fmt;
#[cfg(feature = "with-chrono-0_4")]
use chrono_04::{Duration, TimeZone, Utc};
use postgres::types::{FromSql, ToSql};
use postgres::{Client, NoTls};
#[cfg(feature = "with-rust_decimal-1")]
use rust_decimal_1::Decimal;
macro_rules! test_range {
($name:expr, $t:ty, $low:expr, $low_str:expr, $high:expr, $high_str:expr) => ({
let tests = &[(Some(range!('(',; ')')), "'(,)'".to_string()),
(Some(range!('[' $low,; ')')), format!("'[{},)'", $low_str)),
(Some(range!('(' $low,; ')')), format!("'({},)'", $low_str)),
(Some(range!('(', $high; ']')), format!("'(,{}]'", $high_str)),
(Some(range!('(', $high; ')')), format!("'(,{})'", $high_str)),
(Some(range!('[' $low, $high; ']')),
format!("'[{},{}]'", $low_str, $high_str)),
(Some(range!('[' $low, $high; ')')),
format!("'[{},{})'", $low_str, $high_str)),
(Some(range!('(' $low, $high; ']')),
format!("'({},{}]'", $low_str, $high_str)),
(Some(range!('(' $low, $high; ')')),
format!("'({},{})'", $low_str, $high_str)),
(Some(range!(empty)), "'empty'".to_string()),
(None, "NULL".to_string())];
test_type($name, tests);
})
}
fn test_type<T, S>(sql_type: &str, checks: &[(T, S)])
where
for<'a> T: Sync + PartialEq + FromSql<'a> + ToSql,
S: fmt::Display,
{
let mut conn = Client::connect("postgres://postgres@localhost", NoTls).unwrap();
for &(ref val, ref repr) in checks {
let stmt = conn
.prepare(&*format!("SELECT {}::{}", *repr, sql_type))
.unwrap();
let result = conn
.query(&stmt, &[])
.unwrap()
.iter()
.next()
.unwrap()
.get(0);
assert!(val == &result);
let stmt = conn.prepare(&*format!("SELECT $1::{}", sql_type)).unwrap();
let result = conn
.query(&stmt, &[val])
.unwrap()
.iter()
.next()
.unwrap()
.get(0);
assert!(val == &result);
}
}
#[test]
fn test_int4range_params() {
test_range!("INT4RANGE", i32, 100i32, "100", 200i32, "200")
}
#[test]
fn test_int8range_params() {
test_range!("INT8RANGE", i64, 100i64, "100", 200i64, "200")
}
#[test]
#[cfg(feature = "with-rust_decimal-1")]
fn test_numrange_params() {
let low = Decimal::new(202, 2);
let high = Decimal::new(202, 1);
test_range!("NUMRANGE", Decimal, low, "2.02", high, "20.2");
}
#[test]
#[cfg(feature = "with-chrono-0_4")]
fn test_tsrange_params() {
let low = Utc.timestamp_opt(0, 0).unwrap();
let high = low + Duration::days(10);
test_range!(
"TSRANGE",
NaiveDateTime,
low.naive_utc(),
"1970-01-01",
high.naive_utc(),
"1970-01-11"
);
}
#[test]
#[cfg(feature = "with-chrono-0_4")]
fn test_tstzrange_params() {
let low = Utc.timestamp_opt(0, 0).unwrap();
let high = low + Duration::days(10);
test_range!(
"TSTZRANGE",
DateTime<Utc>,
low,
"1970-01-01",
high,
"1970-01-11"
);
}
}