From f5434dfaef2bfc65fbb966bae9b374737d4c7e9d Mon Sep 17 00:00:00 2001 From: nociza Date: Mon, 24 Apr 2023 19:42:42 -0700 Subject: [PATCH] Use base64 encoding for serializing Vec --- Cargo.toml | 1 + src/dbc.rs | 33 ++++++++++++++++++++++++++++----- tests/common.rs | 2 +- 3 files changed, 30 insertions(+), 6 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index af4fbef..357cc48 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ license = "MIT" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +base64 = "0.21.0" mysql = "23.0.1" mysql_common = "0.29.2" postgres = "0.19.4" diff --git a/src/dbc.rs b/src/dbc.rs index 8f6f464..bcc76dc 100644 --- a/src/dbc.rs +++ b/src/dbc.rs @@ -12,7 +12,6 @@ pub trait Connection { } pub struct Database { - pub(crate) url: String, pub(crate) connection: Box, } @@ -24,10 +23,7 @@ impl Database { _ => return Err("Unsupported dbc type".into()), }; - Ok(Database { - url: url.to_string(), - connection, - }) + Ok(Database { connection }) } pub fn execute_query(&mut self, query: &str) -> Result { @@ -58,6 +54,7 @@ impl Database { #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub enum Value { NULL, + #[serde(with = "base64")] Bytes(Vec), String(String), Bool(bool), @@ -137,3 +134,29 @@ pub enum ColumnType { GEOMETRY, UNKNOWN, } + +mod base64 { + use base64::Engine; + use serde::{Deserialize, Serialize}; + use serde::{Deserializer, Serializer}; + + pub fn serialize(v: &Vec, s: S) -> Result { + let engine = base64::engine::GeneralPurpose::new( + &base64::alphabet::STANDARD, + base64::engine::general_purpose::NO_PAD, + ); + let base64 = engine.encode(v); + String::serialize(&base64, s) + } + + pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + let base64 = String::deserialize(d)?; + let engine = base64::engine::GeneralPurpose::new( + &base64::alphabet::STANDARD, + base64::engine::general_purpose::NO_PAD, + ); + engine + .decode(base64.as_bytes()) + .map_err(serde::de::Error::custom) + } +} diff --git a/tests/common.rs b/tests/common.rs index 9b76b41..e37912a 100644 --- a/tests/common.rs +++ b/tests/common.rs @@ -121,7 +121,7 @@ pub(crate) async fn test_query_with_params_and_serialize( let result = serde_json::to_string(&result)?; // Verify the data returned by the query - let expected_result = r#"{"rows":[{"values":[{"Int":1},{"Bytes":[117,112,100,97,116,101,100]}],"columns":[{"name":"id","column_type":"INT"},{"name":"name","column_type":"VARCHAR"}]}],"affected_rows":0}"#; + let expected_result = r#"{"rows":[{"values":[{"Int":1},{"Bytes":"dXBkYXRlZA"}],"columns":[{"name":"id","column_type":"INT"},{"name":"name","column_type":"VARCHAR"}]}],"affected_rows":0}"#; assert_eq!(result, expected_result); _cleanup_database(database)?;