-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathto_sql.rs
More file actions
58 lines (51 loc) · 2.33 KB
/
Copy pathto_sql.rs
File metadata and controls
58 lines (51 loc) · 2.33 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
use crate::error::EncryptError;
use crate::{error::Error, postgresql::format_code::FormatCode};
use bytes::BytesMut;
use cipherstash_client::encryption::Plaintext;
use postgres_types::ToSql;
use postgres_types::Type;
pub fn to_sql(plaintext: &Plaintext, format_code: &FormatCode) -> Result<Option<BytesMut>, Error> {
let bytes = match format_code {
FormatCode::Text => text_to_sql(plaintext)?,
FormatCode::Binary => binary_to_sql(plaintext)?,
};
Ok(Some(bytes))
}
fn text_to_sql(plaintext: &Plaintext) -> Result<BytesMut, Error> {
let s = match &plaintext {
Plaintext::Text(Some(x)) => x.to_string(),
Plaintext::Int(Some(x)) => x.to_string(),
Plaintext::BigInt(Some(x)) => x.to_string(),
Plaintext::BigUInt(Some(x)) => x.to_string(),
Plaintext::Boolean(Some(x)) => x.to_string(),
Plaintext::Decimal(Some(x)) => x.to_string(),
Plaintext::Float(Some(x)) => x.to_string(),
Plaintext::NaiveDate(Some(x)) => x.to_string(),
Plaintext::SmallInt(Some(x)) => x.to_string(),
Plaintext::Timestamp(Some(x)) => x.to_string(),
Plaintext::Json(Some(x)) => x.to_string(),
_ => "".to_string(),
};
Ok(BytesMut::from(s.as_bytes()))
}
fn binary_to_sql(plaintext: &Plaintext) -> Result<BytesMut, Error> {
let mut bytes = BytesMut::new();
let result = match &plaintext {
Plaintext::BigInt(x) => x.to_sql_checked(&Type::INT8, &mut bytes),
Plaintext::Boolean(x) => x.to_sql_checked(&Type::BOOL, &mut bytes),
Plaintext::Float(x) => x.to_sql_checked(&Type::FLOAT8, &mut bytes),
Plaintext::Int(x) => x.to_sql_checked(&Type::INT4, &mut bytes),
Plaintext::NaiveDate(x) => x.to_sql_checked(&Type::DATE, &mut bytes),
Plaintext::SmallInt(x) => x.to_sql_checked(&Type::INT2, &mut bytes),
Plaintext::Timestamp(x) => x.to_sql_checked(&Type::TIMESTAMPTZ, &mut bytes),
Plaintext::Text(x) => x.to_sql_checked(&Type::TEXT, &mut bytes),
Plaintext::Json(x) => x.to_sql_checked(&Type::JSONB, &mut bytes),
Plaintext::Decimal(x) => x.to_sql_checked(&Type::NUMERIC, &mut bytes),
// TODO: Implement these
Plaintext::BigUInt(_x) => unimplemented!(),
};
match result {
Ok(_) => Ok(bytes),
Err(_e) => Err(EncryptError::PlaintextCouldNotBeEncoded.into()),
}
}