| 1 |
use crate::postgres::common::*; |
| 2 |
use crate::Decimal; |
| 3 |
use byteorder::{BigEndian, ReadBytesExt}; |
| 4 |
use bytes::{BufMut, BytesMut}; |
| 5 |
use postgres::types::{to_sql_checked, FromSql, IsNull, ToSql, Type}; |
| 6 |
use std::io::Cursor; |
| 7 |
|
| 8 |
impl<'a> FromSql<'a> for Decimal { |
| 9 |
// Decimals are represented as follows: |
| 10 |
// Header: |
| 11 |
// u16 numGroups |
| 12 |
// i16 weightFirstGroup (10000^weight) |
| 13 |
// u16 sign (0x0000 = positive, 0x4000 = negative, 0xC000 = NaN) |
| 14 |
// i16 dscale. Number of digits (in base 10) to print after decimal separator |
| 15 |
// |
| 16 |
// Pseudo code : |
| 17 |
// const Decimals [ |
| 18 |
// 0.0000000000000000000000000001, |
| 19 |
// 0.000000000000000000000001, |
| 20 |
// 0.00000000000000000001, |
| 21 |
// 0.0000000000000001, |
| 22 |
// 0.000000000001, |
| 23 |
// 0.00000001, |
| 24 |
// 0.0001, |
| 25 |
// 1, |
| 26 |
// 10000, |
| 27 |
// 100000000, |
| 28 |
// 1000000000000, |
| 29 |
// 10000000000000000, |
| 30 |
// 100000000000000000000, |
| 31 |
// 1000000000000000000000000, |
| 32 |
// 10000000000000000000000000000 |
| 33 |
// ] |
| 34 |
// overflow = false |
| 35 |
// result = 0 |
| 36 |
// for i = 0, weight = weightFirstGroup + 7; i < numGroups; i++, weight-- |
| 37 |
// group = read.u16 |
| 38 |
// if weight < 0 or weight > MaxNum |
| 39 |
// overflow = true |
| 40 |
// else |
| 41 |
// result += Decimals[weight] * group |
| 42 |
// sign == 0x4000 ? -result : result |
| 43 |
|
| 44 |
// So if we were to take the number: 3950.123456 |
| 45 |
// |
| 46 |
// Stored on Disk: |
| 47 |
// 00 03 00 00 00 00 00 06 0F 6E 04 D2 15 E0 |
| 48 |
// |
| 49 |
// Number of groups: 00 03 |
| 50 |
// Weight of first group: 00 00 |
| 51 |
// Sign: 00 00 |
| 52 |
// DScale: 00 06 |
| 53 |
// |
| 54 |
// 0F 6E = 3950 |
| 55 |
// result = result + 3950 * 1; |
| 56 |
// 04 D2 = 1234 |
| 57 |
// result = result + 1234 * 0.0001; |
| 58 |
// 15 E0 = 5600 |
| 59 |
// result = result + 5600 * 0.00000001; |
| 60 |
// |
| 61 |
|
| 62 |
fn from_sql(_: &Type, raw: &[u8]) -> Result<Decimal, Box<dyn std::error::Error + 'static + Sync + Send>> { |
| 63 |
let mut raw = Cursor::new(raw); |
| 64 |
let num_groups = raw.read_u16::<BigEndian>()?; |
| 65 |
let weight = raw.read_i16::<BigEndian>()?; // 10000^weight |
| 66 |
// Sign: 0x0000 = positive, 0x4000 = negative, 0xC000 = NaN |
| 67 |
let sign = raw.read_u16::<BigEndian>()?; |
| 68 |
// Number of digits (in base 10) to print after decimal separator |
| 69 |
let scale = raw.read_u16::<BigEndian>()?; |
| 70 |
|
| 71 |
// Read all of the groups |
| 72 |
let mut groups = Vec::new(); |
| 73 |
for _ in 0..num_groups as usize { |
| 74 |
groups.push(raw.read_u16::<BigEndian>()?); |
| 75 |
} |
| 76 |
|
| 77 |
Ok(Self::from_postgres(PostgresDecimal { |
| 78 |
neg: sign == 0x4000, |
| 79 |
weight, |
| 80 |
scale, |
| 81 |
digits: groups.into_iter(), |
| 82 |
})) |
| 83 |
} |
| 84 |
|
| 85 |
fn accepts(ty: &Type) -> bool { |
| 86 |
matches!(*ty, Type::NUMERIC) |
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
impl ToSql for Decimal { |
| 91 |
fn to_sql( |
| 92 |
&self, |
| 93 |
_: &Type, |
| 94 |
out: &mut BytesMut, |
| 95 |
) -> Result<IsNull, Box<dyn std::error::Error + 'static + Sync + Send>> { |
| 96 |
let PostgresDecimal { |
| 97 |
neg, |
| 98 |
weight, |
| 99 |
scale, |
| 100 |
digits, |
| 101 |
} = self.to_postgres(); |
| 102 |
|
| 103 |
let num_digits = digits.len(); |
| 104 |
|
| 105 |
// Reserve bytes |
| 106 |
out.reserve(8 + num_digits * 2); |
| 107 |
|
| 108 |
// Number of groups |
| 109 |
out.put_u16(num_digits.try_into().unwrap()); |
| 110 |
// Weight of first group |
| 111 |
out.put_i16(weight); |
| 112 |
// Sign |
| 113 |
out.put_u16(if neg { 0x4000 } else { 0x0000 }); |
| 114 |
// DScale |
| 115 |
out.put_u16(scale); |
| 116 |
// Now process the number |
| 117 |
for digit in digits[0..num_digits].iter() { |
| 118 |
out.put_i16(*digit); |
| 119 |
} |
| 120 |
|
| 121 |
Ok(IsNull::No) |
| 122 |
} |
| 123 |
|
| 124 |
fn accepts(ty: &Type) -> bool { |
| 125 |
matches!(*ty, Type::NUMERIC) |
| 126 |
} |
| 127 |
|
| 128 |
to_sql_checked!(); |
| 129 |
} |
| 130 |
|
| 131 |
#[cfg(test)] |
| 132 |
mod test { |
| 133 |
use super::*; |
| 134 |
use ::postgres::{Client, NoTls}; |
| 135 |
use core::str::FromStr; |
| 136 |
|
| 137 |
/// Gets the URL for connecting to PostgreSQL for testing. Set the POSTGRES_URL |
| 138 |
/// environment variable to change from the default of "postgres://postgres@localhost". |
| 139 |
fn get_postgres_url() -> String { |
| 140 |
if let Ok(url) = std::env::var("POSTGRES_URL") { |
| 141 |
return url; |
| 142 |
} |
| 143 |
"postgres://postgres@localhost".to_string() |
| 144 |
} |
| 145 |
|
| 146 |
pub static TEST_DECIMALS: &[(u32, u32, &str, &str)] = &[ |
| 147 |
// precision, scale, sent, expected |
| 148 |
(35, 6, "3950.123456", "3950.123456"), |
| 149 |
(35, 2, "3950.123456", "3950.12"), |
| 150 |
(35, 2, "3950.1256", "3950.13"), |
| 151 |
(10, 2, "3950.123456", "3950.12"), |
| 152 |
(35, 6, "3950", "3950.000000"), |
| 153 |
(4, 0, "3950", "3950"), |
| 154 |
(35, 6, "0.1", "0.100000"), |
| 155 |
(35, 6, "0.01", "0.010000"), |
| 156 |
(35, 6, "0.001", "0.001000"), |
| 157 |
(35, 6, "0.0001", "0.000100"), |
| 158 |
(35, 6, "0.00001", "0.000010"), |
| 159 |
(35, 6, "0.000001", "0.000001"), |
| 160 |
(35, 6, "1", "1.000000"), |
| 161 |
(35, 6, "-100", "-100.000000"), |
| 162 |
(35, 6, "-123.456", "-123.456000"), |
| 163 |
(35, 6, "119996.25", "119996.250000"), |
| 164 |
(35, 6, "1000000", "1000000.000000"), |
| 165 |
(35, 6, "9999999.99999", "9999999.999990"), |
| 166 |
(35, 6, "12340.56789", "12340.567890"), |
| 167 |
// Scale is only 28 since that is the maximum we can represent. |
| 168 |
(65, 30, "1.2", "1.2000000000000000000000000000"), |
| 169 |
// Pi - rounded at scale 28 |
| 170 |
( |
| 171 |
65, |
| 172 |
30, |
| 173 |
"3.141592653589793238462643383279", |
| 174 |
"3.1415926535897932384626433833", |
| 175 |
), |
| 176 |
( |
| 177 |
65, |
| 178 |
34, |
| 179 |
"3.1415926535897932384626433832795028", |
| 180 |
"3.1415926535897932384626433833", |
| 181 |
), |
| 182 |
// Unrounded number |
| 183 |
( |
| 184 |
65, |
| 185 |
34, |
| 186 |
"1.234567890123456789012345678950000", |
| 187 |
"1.2345678901234567890123456790", |
| 188 |
), |
| 189 |
( |
| 190 |
65, |
| 191 |
34, // No rounding due to 49999 after significant digits |
| 192 |
"1.234567890123456789012345678949999", |
| 193 |
"1.2345678901234567890123456789", |
| 194 |
), |
| 195 |
// 0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF (96 bit) |
| 196 |
(35, 0, "79228162514264337593543950335", "79228162514264337593543950335"), |
| 197 |
// 0x0FFF_FFFF_FFFF_FFFF_FFFF_FFFF (95 bit) |
| 198 |
(35, 1, "4951760157141521099596496895", "4951760157141521099596496895.0"), |
| 199 |
// 0x1000_0000_0000_0000_0000_0000 |
| 200 |
(35, 1, "4951760157141521099596496896", "4951760157141521099596496896.0"), |
| 201 |
(35, 6, "18446744073709551615", "18446744073709551615.000000"), |
| 202 |
(35, 6, "-18446744073709551615", "-18446744073709551615.000000"), |
| 203 |
(35, 6, "0.10001", "0.100010"), |
| 204 |
(35, 6, "0.12345", "0.123450"), |
| 205 |
]; |
| 206 |
|
| 207 |
#[test] |
| 208 |
fn test_null() { |
| 209 |
let mut client = match Client::connect(&get_postgres_url(), NoTls) { |
| 210 |
Ok(x) => x, |
| 211 |
Err(err) => panic!("{:#?}", err), |
| 212 |
}; |
| 213 |
|
| 214 |
// Test NULL |
| 215 |
let result: Option<Decimal> = match client.query("SELECT NULL::numeric", &[]) { |
| 216 |
Ok(x) => x.iter().next().unwrap().get(0), |
| 217 |
Err(err) => panic!("{:#?}", err), |
| 218 |
}; |
| 219 |
assert_eq!(None, result); |
| 220 |
} |
| 221 |
|
| 222 |
#[tokio::test] |
| 223 |
#[cfg(feature = "tokio-pg")] |
| 224 |
async fn async_test_null() { |
| 225 |
use futures::future::FutureExt; |
| 226 |
use tokio_postgres::connect; |
| 227 |
|
| 228 |
let (client, connection) = connect(&get_postgres_url(), NoTls).await.unwrap(); |
| 229 |
let connection = connection.map(|e| e.unwrap()); |
| 230 |
tokio::spawn(connection); |
| 231 |
|
| 232 |
let statement = client.prepare(&"SELECT NULL::numeric").await.unwrap(); |
| 233 |
let rows = client.query(&statement, &[]).await.unwrap(); |
| 234 |
let result: Option<Decimal> = rows.iter().next().unwrap().get(0); |
| 235 |
|
| 236 |
assert_eq!(None, result); |
| 237 |
} |
| 238 |
|
| 239 |
#[test] |
| 240 |
fn read_very_small_numeric_type() { |
| 241 |
let mut client = match Client::connect(&get_postgres_url(), NoTls) { |
| 242 |
Ok(x) => x, |
| 243 |
Err(err) => panic!("{:#?}", err), |
| 244 |
}; |
| 245 |
let result: Decimal = match client.query("SELECT 1e-130::NUMERIC(130, 0)", &[]) { |
| 246 |
Ok(x) => x.iter().next().unwrap().get(0), |
| 247 |
Err(err) => panic!("error - {:#?}", err), |
| 248 |
}; |
| 249 |
// We compare this to zero since it is so small that it is effectively zero |
| 250 |
assert_eq!(Decimal::ZERO, result); |
| 251 |
} |
| 252 |
|
| 253 |
#[test] |
| 254 |
fn read_numeric_type() { |
| 255 |
let mut client = match Client::connect(&get_postgres_url(), NoTls) { |
| 256 |
Ok(x) => x, |
| 257 |
Err(err) => panic!("{:#?}", err), |
| 258 |
}; |
| 259 |
for &(precision, scale, sent, expected) in TEST_DECIMALS.iter() { |
| 260 |
let result: Decimal = |
| 261 |
match client.query(&*format!("SELECT {}::NUMERIC({}, {})", sent, precision, scale), &[]) { |
| 262 |
Ok(x) => x.iter().next().unwrap().get(0), |
| 263 |
Err(err) => panic!("SELECT {}::NUMERIC({}, {}), error - {:#?}", sent, precision, scale, err), |
| 264 |
}; |
| 265 |
assert_eq!( |
| 266 |
expected, |
| 267 |
result.to_string(), |
| 268 |
"NUMERIC({}, {}) sent: {}", |
| 269 |
precision, |
| 270 |
scale, |
| 271 |
sent |
| 272 |
); |
| 273 |
} |
| 274 |
} |
| 275 |
|
| 276 |
#[tokio::test] |
| 277 |
#[cfg(feature = "tokio-pg")] |
| 278 |
async fn async_read_numeric_type() { |
| 279 |
use futures::future::FutureExt; |
| 280 |
use tokio_postgres::connect; |
| 281 |
|
| 282 |
let (client, connection) = connect(&get_postgres_url(), NoTls).await.unwrap(); |
| 283 |
let connection = connection.map(|e| e.unwrap()); |
| 284 |
tokio::spawn(connection); |
| 285 |
for &(precision, scale, sent, expected) in TEST_DECIMALS.iter() { |
| 286 |
let statement = client |
| 287 |
.prepare(&*format!("SELECT {}::NUMERIC({}, {})", sent, precision, scale)) |
| 288 |
.await |
| 289 |
.unwrap(); |
| 290 |
let rows = client.query(&statement, &[]).await.unwrap(); |
| 291 |
let result: Decimal = rows.iter().next().unwrap().get(0); |
| 292 |
|
| 293 |
assert_eq!(expected, result.to_string(), "NUMERIC({}, {})", precision, scale); |
| 294 |
} |
| 295 |
} |
| 296 |
|
| 297 |
#[test] |
| 298 |
fn write_numeric_type() { |
| 299 |
let mut client = match Client::connect(&get_postgres_url(), NoTls) { |
| 300 |
Ok(x) => x, |
| 301 |
Err(err) => panic!("{:#?}", err), |
| 302 |
}; |
| 303 |
for &(precision, scale, sent, expected) in TEST_DECIMALS.iter() { |
| 304 |
let number = Decimal::from_str(sent).unwrap(); |
| 305 |
let result: Decimal = |
| 306 |
match client.query(&*format!("SELECT $1::NUMERIC({}, {})", precision, scale), &[&number]) { |
| 307 |
Ok(x) => x.iter().next().unwrap().get(0), |
| 308 |
Err(err) => panic!("{:#?}", err), |
| 309 |
}; |
| 310 |
assert_eq!(expected, result.to_string(), "NUMERIC({}, {})", precision, scale); |
| 311 |
} |
| 312 |
} |
| 313 |
|
| 314 |
#[tokio::test] |
| 315 |
#[cfg(feature = "tokio-pg")] |
| 316 |
async fn async_write_numeric_type() { |
| 317 |
use futures::future::FutureExt; |
| 318 |
use tokio_postgres::connect; |
| 319 |
|
| 320 |
let (client, connection) = connect(&get_postgres_url(), NoTls).await.unwrap(); |
| 321 |
let connection = connection.map(|e| e.unwrap()); |
| 322 |
tokio::spawn(connection); |
| 323 |
|
| 324 |
for &(precision, scale, sent, expected) in TEST_DECIMALS.iter() { |
| 325 |
let statement = client |
| 326 |
.prepare(&*format!("SELECT $1::NUMERIC({}, {})", precision, scale)) |
| 327 |
.await |
| 328 |
.unwrap(); |
| 329 |
let number = Decimal::from_str(sent).unwrap(); |
| 330 |
let rows = client.query(&statement, &[&number]).await.unwrap(); |
| 331 |
let result: Decimal = rows.iter().next().unwrap().get(0); |
| 332 |
|
| 333 |
assert_eq!(expected, result.to_string(), "NUMERIC({}, {})", precision, scale); |
| 334 |
} |
| 335 |
} |
| 336 |
|
| 337 |
#[test] |
| 338 |
fn numeric_overflow() { |
| 339 |
let tests = [(4, 4, "3950.1234")]; |
| 340 |
let mut client = match Client::connect(&get_postgres_url(), NoTls) { |
| 341 |
Ok(x) => x, |
| 342 |
Err(err) => panic!("{:#?}", err), |
| 343 |
}; |
| 344 |
for &(precision, scale, sent) in tests.iter() { |
| 345 |
match client.query(&*format!("SELECT {}::NUMERIC({}, {})", sent, precision, scale), &[]) { |
| 346 |
Ok(_) => panic!( |
| 347 |
"Expected numeric overflow for {}::NUMERIC({}, {})", |
| 348 |
sent, precision, scale |
| 349 |
), |
| 350 |
Err(err) => { |
| 351 |
assert_eq!("22003", err.code().unwrap().code(), "Unexpected error code"); |
| 352 |
} |
| 353 |
}; |
| 354 |
} |
| 355 |
} |
| 356 |
|
| 357 |
#[tokio::test] |
| 358 |
#[cfg(feature = "tokio-pg")] |
| 359 |
async fn async_numeric_overflow() { |
| 360 |
use futures::future::FutureExt; |
| 361 |
use tokio_postgres::connect; |
| 362 |
|
| 363 |
let tests = [(4, 4, "3950.1234")]; |
| 364 |
let (client, connection) = connect(&get_postgres_url(), NoTls).await.unwrap(); |
| 365 |
let connection = connection.map(|e| e.unwrap()); |
| 366 |
tokio::spawn(connection); |
| 367 |
|
| 368 |
for &(precision, scale, sent) in tests.iter() { |
| 369 |
let statement = client |
| 370 |
.prepare(&*format!("SELECT {}::NUMERIC({}, {})", sent, precision, scale)) |
| 371 |
.await |
| 372 |
.unwrap(); |
| 373 |
|
| 374 |
match client.query(&statement, &[]).await { |
| 375 |
Ok(_) => panic!( |
| 376 |
"Expected numeric overflow for {}::NUMERIC({}, {})", |
| 377 |
sent, precision, scale |
| 378 |
), |
| 379 |
Err(err) => assert_eq!("22003", err.code().unwrap().code(), "Unexpected error code"), |
| 380 |
} |
| 381 |
} |
| 382 |
} |
| 383 |
} |