-
Notifications
You must be signed in to change notification settings - Fork 216
/
row.rs
281 lines (257 loc) Β· 10.7 KB
/
row.rs
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
use crate::error::SqlError;
use chrono::{DateTime, Utc};
use datamodel::FieldArity;
use prisma_models::{PrismaValue, Record, TypeIdentifier};
use quaint::{
ast::{DatabaseValue, ParameterizedValue},
connector::ResultRow,
};
use rust_decimal::Decimal;
use std::{borrow::Borrow, io, str::FromStr};
use uuid::Uuid;
/// An allocated representation of a `Row` returned from the database.
#[derive(Debug, Clone, Default)]
pub struct SqlRow {
pub values: Vec<PrismaValue>,
}
impl From<SqlRow> for Record {
fn from(row: SqlRow) -> Record {
Record::new(row.values)
}
}
pub trait ToSqlRow {
/// Conversion from a database specific row to an allocated `SqlRow`. To
/// help deciding the right types, the provided `TypeIdentifier`s should map
/// to the returned columns in the right order.
fn to_sql_row<'b>(self, idents: &[(TypeIdentifier, FieldArity)]) -> crate::Result<SqlRow>;
}
impl ToSqlRow for ResultRow {
fn to_sql_row<'b>(self, idents: &[(TypeIdentifier, FieldArity)]) -> crate::Result<SqlRow> {
let mut row = SqlRow::default();
let row_width = idents.len();
row.values.reserve(row_width);
for (i, p_value) in self.into_iter().enumerate().take(row_width) {
let pv = match &idents[i] {
(type_identifier, FieldArity::List) => match p_value {
ParameterizedValue::Array(l) => l
.into_iter()
.map(|p_value| row_value_to_prisma_value(p_value, &type_identifier))
.collect::<crate::Result<Vec<_>>>()
.map(|vec| PrismaValue::List(vec)),
ParameterizedValue::Null => Ok(PrismaValue::List(Vec::new())),
_ => {
let error = io::Error::new(
io::ErrorKind::InvalidData,
format!("List field did not return an Array from database. Type identifier was {:?}. Value was {:?}.", &type_identifier, &p_value),
);
return Err(SqlError::ConversionError(error.into()));
}
},
(type_identifier, _) => row_value_to_prisma_value(p_value, &type_identifier),
}?;
row.values.push(pv);
}
Ok(row)
}
}
pub fn row_value_to_prisma_value(
p_value: ParameterizedValue,
type_identifier: &TypeIdentifier,
) -> Result<PrismaValue, SqlError> {
Ok(match type_identifier {
TypeIdentifier::Boolean => match p_value {
// ParameterizedValue::Array(vec) => PrismaValue::Boolean(b),
ParameterizedValue::Null => PrismaValue::Null,
ParameterizedValue::Integer(i) => PrismaValue::Boolean(i != 0),
ParameterizedValue::Boolean(b) => PrismaValue::Boolean(b),
_ => {
let error = io::Error::new(io::ErrorKind::InvalidData, "Bool value not stored as bool or int");
return Err(SqlError::ConversionError(error.into()));
}
},
TypeIdentifier::Enum(_) => match p_value {
ParameterizedValue::Null => PrismaValue::Null,
ParameterizedValue::Enum(cow) => PrismaValue::Enum(cow.into_owned()),
ParameterizedValue::Text(cow) => PrismaValue::Enum(cow.into_owned()),
_ => {
let error = io::Error::new(io::ErrorKind::InvalidData, "Enum value not stored as enum");
return Err(SqlError::ConversionError(error.into()));
}
},
TypeIdentifier::Json => match p_value {
ParameterizedValue::Null => PrismaValue::Null,
ParameterizedValue::Text(json) => PrismaValue::String(json.into()),
ParameterizedValue::Json(json) => PrismaValue::String(json.to_string()),
_ => {
let error = io::Error::new(io::ErrorKind::InvalidData, "Json value not stored as text or json");
return Err(SqlError::ConversionError(error.into()));
}
},
TypeIdentifier::UUID => match p_value {
ParameterizedValue::Null => PrismaValue::Null,
ParameterizedValue::Text(uuid) => PrismaValue::Uuid(Uuid::parse_str(&uuid)?),
ParameterizedValue::Uuid(uuid) => PrismaValue::Uuid(uuid),
_ => {
let error = io::Error::new(io::ErrorKind::InvalidData, "Uuid value not stored as text or uuid");
return Err(SqlError::ConversionError(error.into()));
}
},
TypeIdentifier::DateTime => match p_value {
ParameterizedValue::Null => PrismaValue::Null,
ParameterizedValue::DateTime(dt) => PrismaValue::DateTime(dt),
ParameterizedValue::Integer(ts) => {
let nsecs = ((ts % 1000) * 1_000_000) as u32;
let secs = (ts / 1000) as i64;
let naive = chrono::NaiveDateTime::from_timestamp(secs, nsecs);
let datetime: DateTime<Utc> = DateTime::from_utc(naive, Utc);
PrismaValue::DateTime(datetime)
}
ParameterizedValue::Text(dt_string) => {
let dt = DateTime::parse_from_rfc3339(dt_string.borrow())
.or_else(|_| DateTime::parse_from_rfc2822(dt_string.borrow()))
.map_err(|err| {
failure::format_err!("Could not parse stored DateTime string: {} ({})", dt_string, err)
})
.unwrap();
PrismaValue::DateTime(dt.with_timezone(&Utc))
}
_ => {
let error = io::Error::new(
io::ErrorKind::InvalidData,
"DateTime value not stored as datetime, int or text",
);
return Err(SqlError::ConversionError(error.into()));
}
},
TypeIdentifier::Float => match p_value {
ParameterizedValue::Null => PrismaValue::Null,
ParameterizedValue::Real(f) => PrismaValue::Float(f),
ParameterizedValue::Integer(i) => {
// Decimal::from_f64 is buggy. Issue: https://github.com/paupino/rust-decimal/issues/228
PrismaValue::Float(Decimal::from_str(&(i as f64).to_string()).expect("f64 was not a Decimal."))
}
ParameterizedValue::Text(_) | ParameterizedValue::Bytes(_) => PrismaValue::Float(
p_value
.as_str()
.expect("text/bytes as str")
.parse()
.map_err(|err: rust_decimal::Error| SqlError::ColumnReadFailure(err.into()))?,
),
_ => {
let error = io::Error::new(
io::ErrorKind::InvalidData,
"Float value not stored as float, int or text",
);
return Err(SqlError::ConversionError(error.into()));
}
},
TypeIdentifier::Int => match p_value {
ParameterizedValue::Integer(i) => PrismaValue::Int(i),
ParameterizedValue::Bytes(bytes) => PrismaValue::Int(interpret_bytes_as_i64(&bytes)),
ParameterizedValue::Text(txt) => PrismaValue::Int(
i64::from_str(dbg!(txt.trim_start_matches('\0')))
.map_err(|err| SqlError::ConversionError(err.into()))?,
),
other => PrismaValue::from(other),
},
TypeIdentifier::String => match p_value {
ParameterizedValue::Uuid(uuid) => PrismaValue::String(uuid.to_string()),
ParameterizedValue::Json(json_value) => {
PrismaValue::String(serde_json::to_string(&json_value).expect("JSON value to string"))
}
ParameterizedValue::Null => PrismaValue::Null,
other => PrismaValue::from(other),
},
})
}
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub enum SqlId {
String(String),
Int(usize),
UUID(Uuid),
}
impl From<SqlId> for DatabaseValue<'static> {
fn from(id: SqlId) -> Self {
match id {
SqlId::String(s) => s.into(),
SqlId::Int(i) => (i as i64).into(),
SqlId::UUID(u) => u.into(),
}
}
}
impl From<&SqlId> for DatabaseValue<'static> {
fn from(id: &SqlId) -> Self {
id.clone().into()
}
}
// We assume the bytes are stored as a big endian signed integer, because that is what
// mysql does if you enter a numeric value for a bits column.
fn interpret_bytes_as_i64(bytes: &[u8]) -> i64 {
match bytes.len() {
8 => i64::from_be_bytes([
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
]),
len if len < 8 => {
let sign_bit_mask: u8 = 0b10000000;
// The first byte will only contain the sign bit.
let most_significant_bit_byte = bytes[0] & sign_bit_mask;
let padding = if most_significant_bit_byte == 0 { 0 } else { 0b11111111 };
let mut i64_bytes = [padding; 8];
for (target_byte, source_byte) in i64_bytes.iter_mut().rev().zip(bytes.iter().rev()) {
*target_byte = *source_byte;
}
i64::from_be_bytes(i64_bytes)
}
0 => 0,
_ => panic!("Attempted to interpret more than 8 bytes as an integer."),
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn quaint_bytes_to_integer_conversion_works() {
// Negative i64
{
let i: i64 = -123456789123;
let bytes = i.to_be_bytes();
let roundtripped = interpret_bytes_as_i64(&bytes);
assert_eq!(roundtripped, i);
}
// Positive i64
{
let i: i64 = 123456789123;
let bytes = i.to_be_bytes();
let roundtripped = interpret_bytes_as_i64(&bytes);
assert_eq!(roundtripped, i);
}
// Positive i32
{
let i: i32 = 123456789;
let bytes = i.to_be_bytes();
let roundtripped = interpret_bytes_as_i64(&bytes);
assert_eq!(roundtripped, i as i64);
}
// Negative i32
{
let i: i32 = -123456789;
let bytes = i.to_be_bytes();
let roundtripped = interpret_bytes_as_i64(&bytes);
assert_eq!(roundtripped, i as i64);
}
// Positive i16
{
let i: i16 = 12345;
let bytes = i.to_be_bytes();
let roundtripped = interpret_bytes_as_i64(&bytes);
assert_eq!(roundtripped, i as i64);
}
// Negative i16
{
let i: i16 = -12345;
let bytes = i.to_be_bytes();
let roundtripped = interpret_bytes_as_i64(&bytes);
assert_eq!(roundtripped, i as i64);
}
}
}