pub trait DrizzleMySQLColumn: Sized {
type SQLType: MySQLColumnType;
const SQL_TYPE: &'static str;
// Required methods
fn decode(value: MySQLValue<'_>) -> Result<Self, DrizzleError>;
fn encode(&self) -> MySQLValue<'_>;
// Provided method
fn encode_owned(self) -> OwnedMySQLValue { ... }
}Expand description
A Rust type that can be stored in a MySQL column.
Implement it to use your own type as a field of a #[MySQLTable].
SQLType sets which expressions the column can be used
in, SQL_TYPE is written into the DDL, and
decode / encode convert values.
Implementing it also gives From<T> for MySQLValue, which goes through
encode_owned.
§Examples
A u32 stored as four big-endian bytes:
use drizzle_core::error::DrizzleError;
use drizzle_mysql::traits::DrizzleMySQLColumn;
use drizzle_mysql::types::Binary;
use drizzle_mysql::values::MySQLValue;
use std::borrow::Cow;
struct U32Be(u32);
impl DrizzleMySQLColumn for U32Be {
type SQLType = Binary;
const SQL_TYPE: &'static str = "BINARY(4)";
fn decode(value: MySQLValue<'_>) -> Result<Self, DrizzleError> {
let MySQLValue::Bytes(bytes) = value else {
return Err(DrizzleError::ConversionError("expected bytes".into()));
};
let bytes: [u8; 4] = bytes
.as_ref()
.try_into()
.map_err(|_| DrizzleError::ConversionError("expected 4 bytes".into()))?;
Ok(Self(u32::from_be_bytes(bytes)))
}
fn encode(&self) -> MySQLValue<'_> {
MySQLValue::Bytes(Cow::Owned(self.0.to_be_bytes().to_vec()))
}
}
let value = MySQLValue::from(U32Be(7));
assert_eq!(value, MySQLValue::Bytes(Cow::Borrowed(&[0, 0, 0, 7][..])));
assert_eq!(U32Be::decode(value).unwrap().0, 7);
assert!(U32Be::decode(MySQLValue::Int(7)).is_err());Required Associated Constants§
Required Associated Types§
Sourcetype SQLType: MySQLColumnType
type SQLType: MySQLColumnType
The SQL type marker of the column, one of the markers in
crate::types.
Required Methods§
Sourcefn decode(value: MySQLValue<'_>) -> Result<Self, DrizzleError>
fn decode(value: MySQLValue<'_>) -> Result<Self, DrizzleError>
Decodes a value read from the database.
§Errors
Returns DrizzleError::ConversionError when value does not match
this column’s storage representation.
Sourcefn encode(&self) -> MySQLValue<'_>
fn encode(&self) -> MySQLValue<'_>
Encodes the value as a bind parameter, borrowing from self where
possible.
Provided Methods§
Sourcefn encode_owned(self) -> OwnedMySQLValue
fn encode_owned(self) -> OwnedMySQLValue
Encodes the value as an owned bind parameter.
The default calls encode and copies the result.
Override it when the type can move its buffer into the value instead.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".