Expand description
Handles datatypes and their conversions between Rust and Mimer SQL.
This module contains definitions for the ToSql and FromSql traits, which defines how a rust datatype should be converted to a Mimer SQL type and vice versa. These traits are implemented for a variety of types as described in the documentation for each trait, but also allows for custom implementations by the user. Below follows an example of how this can be done:
- Define a custom type (e.g. a struct):
#[derive(Debug, PartialEq)]
struct CustomType {
first_value: i32,
second_value: i32,
}- Implement the ToSql and FromSql trait for the custom type: The ToSql trait defines how the custom datatype should be stored in the database (e.g. if the data is to be stored as a string-variant or integer-variant), whereas the FromSql trait defines from what Mimerdatatype the custom datatype can be converted from.
impl ToSql for CustomType {
fn to_sql(&self) -> MimerDatatype {
let mut bytes: [u8; 8] = [0; 8];
bytes[..4].copy_from_slice(&self.first_value.to_le_bytes());
bytes[4..].copy_from_slice(&self.second_value.to_le_bytes());
MimerDatatype::BinaryArray(bytes.to_vec())
}
}
impl FromSql for CustomType {
fn from_sql(value: MimerDatatype) -> Result<Self, i32> {
match value {
MimerDatatype::BinaryArray(v) => {
if v.len() != 8 {
return Err(-26200); // Mimer Rust API error code for unsupported type conversion.
}
Ok(CustomType {
first_value: i32::from_le_bytes(v[0..4].try_into().unwrap()),
second_value: i32::from_le_bytes(v[4..8].try_into().unwrap())
}
)
}
_ => Err(-26200), // Mimer Rust API error code for unsupported type conversion.
}
}
}- Once both the ToSql and FromSql traits are implemented, the custom type can be used in the API. An example of this is shown below:
let mut conn = Connection::open(db, ident, pass).unwrap();
_ = conn.execute_statement("DROP TABLE my_table");
conn.execute_statement("CREATE TABLE my_table (my_custom_column BINARY(8))").unwrap();
let custom_type = CustomType {
first_value: 1,
second_value: 2,
};
let stmnt = conn.prepare("INSERT INTO my_table (my_custom_column) VALUES(:param)", CursorMode::Forward).unwrap();
stmnt.execute_bind(&[&custom_type]).unwrap();
let stmnt = conn.prepare("SELECT * FROM my_table", CursorMode::Forward).unwrap();
let mut cursor = stmnt.open_cursor().unwrap();
let row = cursor.next_row().unwrap().unwrap();
let fetched_custom_type = row.get::<CustomType>(1).unwrap().unwrap();
assert_eq!(custom_type, fetched_custom_type);Enums§
- Represents Mimer SQL data types. Can be seen as an “intermediary”-datatype between Rust and Mimer SQL.
Traits§
- Defines translation of datatypes from Mimer SQL to Rust.
- Defines translation of datatypes from Rust to Mimer SQL.