Debian Codegraph @

third_party/rust/rust_decimal/src/mysql.rs

raw
1 use crate::Decimal;
2 use diesel::{
3 deserialize::{self, FromSql},
4 mysql::Mysql,
5 serialize::{self, IsNull, Output, ToSql},
6 sql_types::Numeric,
7 };
8 use std::io::Write;
9 use std::str::FromStr;
10
11 #[cfg(all(feature = "diesel1", not(feature = "diesel2")))]
12 impl ToSql<Numeric, Mysql> for Decimal {
13 fn to_sql<W: Write>(&self, out: &mut Output<W, Mysql>) -> serialize::Result {
14 write!(out, "{}", *self).map(|_| IsNull::No).map_err(|e| e.into())
15 }
16 }
17
18 #[cfg(feature = "diesel2")]
19 impl ToSql<Numeric, Mysql> for Decimal {
20 fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Mysql>) -> serialize::Result {
21 write!(out, "{}", *self).map(|_| IsNull::No).map_err(|e| e.into())
22 }
23 }
24
25 #[cfg(all(feature = "diesel1", not(feature = "diesel2")))]
26 impl FromSql<Numeric, Mysql> for Decimal {
27 fn from_sql(numeric: Option<&[u8]>) -> deserialize::Result<Self> {
28 // From what I can ascertain, MySQL simply reads from a string format for the Decimal type.
29 // Explicitly, it looks like it is length followed by the string. Regardless, we can leverage
30 // internal types.
31 let bytes = numeric.ok_or("Invalid decimal")?;
32 let s = std::str::from_utf8(bytes)?;
33 Decimal::from_str(s).map_err(|e| e.into())
34 }
35 }
36
37 #[cfg(feature = "diesel2")]
38 impl FromSql<Numeric, Mysql> for Decimal {
39 fn from_sql(numeric: diesel::mysql::MysqlValue) -> deserialize::Result<Self> {
40 // From what I can ascertain, MySQL simply reads from a string format for the Decimal type.
41 // Explicitly, it looks like it is length followed by the string. Regardless, we can leverage
42 // internal types.
43 let s = std::str::from_utf8(numeric.as_bytes())?;
44 Decimal::from_str(s).map_err(|e| e.into())
45 }
46 }
47
48 #[cfg(test)]
49 mod tests {
50 use super::*;
51 use diesel::deserialize::QueryableByName;
52 use diesel::prelude::*;
53 use diesel::row::NamedRow;
54 use diesel::sql_query;
55 use diesel::sql_types::Text;
56
57 struct Test {
58 value: Decimal,
59 }
60
61 struct NullableTest {
62 value: Option<Decimal>,
63 }
64
65 pub static TEST_DECIMALS: &[(u32, u32, &str, &str)] = &[
66 // precision, scale, sent, expected
67 (1, 0, "1", "1"),
68 (6, 2, "1", "1.00"),
69 (6, 2, "9999.99", "9999.99"),
70 (35, 6, "3950.123456", "3950.123456"),
71 (10, 2, "3950.123456", "3950.12"),
72 (35, 6, "3950", "3950.000000"),
73 (4, 0, "3950", "3950"),
74 (35, 6, "0.1", "0.100000"),
75 (35, 6, "0.01", "0.010000"),
76 (35, 6, "0.001", "0.001000"),
77 (35, 6, "0.0001", "0.000100"),
78 (35, 6, "0.00001", "0.000010"),
79 (35, 6, "0.000001", "0.000001"),
80 (35, 6, "1", "1.000000"),
81 (35, 6, "-100", "-100.000000"),
82 (35, 6, "-123.456", "-123.456000"),
83 (35, 6, "119996.25", "119996.250000"),
84 (35, 6, "1000000", "1000000.000000"),
85 (35, 6, "9999999.99999", "9999999.999990"),
86 (35, 6, "12340.56789", "12340.567890"),
87 ];
88
89 /// Gets the URL for connecting to MySQL for testing. Set the MYSQL_URL
90 /// environment variable to change from the default of "mysql://root@localhost/mysql".
91 fn get_mysql_url() -> String {
92 if let Ok(url) = std::env::var("MYSQL_URL") {
93 return url;
94 }
95 "mysql://[email protected]/mysql".to_string()
96 }
97
98 #[cfg(all(feature = "diesel1", not(feature = "diesel2")))]
99 mod diesel1 {
100 use super::*;
101
102 impl QueryableByName<Mysql> for Test {
103 fn build<R: NamedRow<Mysql>>(row: &R) -> deserialize::Result<Self> {
104 let value = row.get("value")?;
105 Ok(Test { value })
106 }
107 }
108
109 impl QueryableByName<Mysql> for NullableTest {
110 fn build<R: NamedRow<Mysql>>(row: &R) -> deserialize::Result<Self> {
111 let value = row.get("value")?;
112 Ok(NullableTest { value })
113 }
114 }
115
116 #[test]
117 fn test_null() {
118 let connection = diesel::MysqlConnection::establish(&get_mysql_url()).expect("Establish connection");
119
120 // Test NULL
121 let items: Vec<NullableTest> = sql_query("SELECT CAST(NULL AS DECIMAL) AS value")
122 .load(&connection)
123 .expect("Unable to query value");
124 let result = items.first().unwrap().value;
125 assert_eq!(None, result);
126 }
127
128 #[test]
129 fn read_numeric_type() {
130 let connection = diesel::MysqlConnection::establish(&get_mysql_url()).expect("Establish connection");
131 for &(precision, scale, sent, expected) in TEST_DECIMALS.iter() {
132 let items: Vec<Test> = sql_query(format!(
133 "SELECT CAST('{}' AS DECIMAL({}, {})) AS value",
134 sent, precision, scale
135 ))
136 .load(&connection)
137 .expect("Unable to query value");
138 assert_eq!(
139 expected,
140 items.first().unwrap().value.to_string(),
141 "DECIMAL({}, {}) sent: {}",
142 precision,
143 scale,
144 sent
145 );
146 }
147 }
148
149 #[test]
150 fn write_numeric_type() {
151 let connection = diesel::MysqlConnection::establish(&get_mysql_url()).expect("Establish connection");
152 for &(precision, scale, sent, expected) in TEST_DECIMALS.iter() {
153 let items: Vec<Test> =
154 sql_query(format!("SELECT CAST(? AS DECIMAL({}, {})) AS value", precision, scale))
155 .bind::<Text, _>(sent)
156 .load(&connection)
157 .expect("Unable to query value");
158 assert_eq!(
159 expected,
160 items.first().unwrap().value.to_string(),
161 "DECIMAL({}, {}) sent: {}",
162 precision,
163 scale,
164 sent
165 );
166 }
167 }
168 }
169
170 #[cfg(feature = "diesel2")]
171 mod diesel2 {
172 use super::*;
173
174 impl QueryableByName<Mysql> for Test {
175 fn build<'a>(row: &impl NamedRow<'a, Mysql>) -> deserialize::Result<Self> {
176 let value = NamedRow::get(row, "value")?;
177 Ok(Test { value })
178 }
179 }
180
181 impl QueryableByName<Mysql> for NullableTest {
182 fn build<'a>(row: &impl NamedRow<'a, Mysql>) -> deserialize::Result<Self> {
183 let value = NamedRow::get(row, "value")?;
184 Ok(NullableTest { value })
185 }
186 }
187
188 #[test]
189 fn test_null() {
190 let mut connection = diesel::MysqlConnection::establish(&get_mysql_url()).expect("Establish connection");
191
192 // Test NULL
193 let items: Vec<NullableTest> = sql_query("SELECT CAST(NULL AS DECIMAL) AS value")
194 .load(&mut connection)
195 .expect("Unable to query value");
196 let result = items.first().unwrap().value;
197 assert_eq!(None, result);
198 }
199
200 #[test]
201 fn read_numeric_type() {
202 let mut connection = diesel::MysqlConnection::establish(&get_mysql_url()).expect("Establish connection");
203 for &(precision, scale, sent, expected) in TEST_DECIMALS.iter() {
204 let items: Vec<Test> = sql_query(format!(
205 "SELECT CAST('{}' AS DECIMAL({}, {})) AS value",
206 sent, precision, scale
207 ))
208 .load(&mut connection)
209 .expect("Unable to query value");
210 assert_eq!(
211 expected,
212 items.first().unwrap().value.to_string(),
213 "DECIMAL({}, {}) sent: {}",
214 precision,
215 scale,
216 sent
217 );
218 }
219 }
220
221 #[test]
222 fn write_numeric_type() {
223 let mut connection = diesel::MysqlConnection::establish(&get_mysql_url()).expect("Establish connection");
224 for &(precision, scale, sent, expected) in TEST_DECIMALS.iter() {
225 let items: Vec<Test> =
226 sql_query(format!("SELECT CAST(? AS DECIMAL({}, {})) AS value", precision, scale))
227 .bind::<Text, _>(sent)
228 .load(&mut connection)
229 .expect("Unable to query value");
230 assert_eq!(
231 expected,
232 items.first().unwrap().value.to_string(),
233 "DECIMAL({}, {}) sent: {}",
234 precision,
235 scale,
236 sent
237 );
238 }
239 }
240 }
241 }