- Notifications
You must be signed in to change notification settings - Fork85
Common primitives of MySql protocol.
License
Apache-2.0, MIT licenses found
Licenses found
blackbeam/rust_mysql_common
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
This crate is an implementation of basic MySql protocol primitives.
This crate:
- defines basic MySql constants;
- implements necessary functionality for MySql
cached_sha2_password
,mysql_native_password
and legacy authentication plugins; - implements helper traits for MySql protocol IO;
- implements support of named parameters for prepared statements;
- implements parsers for a subset of MySql protocol packets (including binlog packets);
- defines rust representation of MySql protocol values and rows;
- implements conversion between MySql values and rust types, between MySql rows and tuplesof rust types.
- implementsFromRow and FromValue derive macros
Crate offers conversion from/to MySql values for following types (please see MySql documentationon supported ranges for numeric types). Following table refers to MySql protocol types(seeValue
struct) and not to MySql column types. Please seeMySql documentation forcolumn and protocol type correspondence:
Type | Notes |
---|---|
{i,u}8..{i,u}128 ,{i,u}size | MySql int/uint will be converted, bytes will be parsed.{i,u}128 is greater than supported by MySql integer types but it'll be serialized anyway (as decimal bytes string). |
f32 | MySql float will be converted tof32 , bytes will be parsed asf32 .f32 to avoid precision loss (see #17) |
f64 | MySql float and double will be converted tof64 , bytes will be parsed asf64 . |
bool | MySql int {0 ,1 } or bytes {"0x30" ,"0x31" } |
Vec<u8> | MySql bytes |
String | MySql bytes parsed as utf8 |
Duration (std andtime ) | MySql time or bytes parsed as MySql time string |
[time::PrimitiveDateTime ] (v0.2.x) | MySql date time or bytes parsed as MySql date time string ( |
[time::Date ] (v0.2.x) | MySql date or bytes parsed as MySql date string ( |
[time::Time ] (v0.2.x) | MySql time or bytes parsed as MySql time string ( |
[time::Duration ] (v0.2.x) | MySql time or bytes parsed as MySql time string |
[time::PrimitiveDateTime ] (v0.3.x) | MySql date time or bytes parsed as MySql date time string ( |
[time::Date ] (v0.3.x) | MySql date or bytes parsed as MySql date string ( |
[time::Time ] (v0.3.x) | MySql time or bytes parsed as MySql time string ( |
[time::Duration ] (v0.3.x) | MySql time or bytes parsed as MySql time string |
[chrono::NaiveTime ] | MySql date or bytes parsed as MySql date string |
[chrono::NaiveDate ] | MySql date or bytes parsed as MySql date string |
[chrono::NaiveDateTime ] | MySql date or bytes parsed as MySql date string |
[uuid::Uuid ] | MySql bytes parsed usingUuid::from_slice |
[serde_json::Value ] | MySql bytes parsed usingserde_json::from_str |
mysql_common::Deserialized<T : DeserializeOwned> | MySql bytes parsed usingserde_json::from_str |
Option<T: FromValue> | Must be used for nullable columns to avoid errors |
[decimal::Decimal ] | MySql int, uint or bytes parsed usingDecimal::from_str .DECIMAL type. |
[bigdecimal::BigDecimal ] | MySql int, uint, floats or bytes parsed usingBigDecimal::parse_bytes .DECIMAL type but it'll be serialized anyway. |
num_bigint::{BigInt, BigUint} | MySql int, uint or bytes parsed using_::parse_bytes . |
Also crate provides from-row convertion for the following list of types (seeFromRow
trait):
Type | Notes |
---|---|
Row | Trivial conversion forRow itself. |
T: FromValue | For rows with a single column. |
(T1: FromValue [, ..., T12: FromValue]) | Row to a tuple of arity 1-12. |
[frunk::hlist::HList ] types | Usefull to overcome tuple arity limitation |
Feature | Description | Default |
---|---|---|
bigdecimal | Enablesbigdecimal >=0.3.x, <0.5.x types support | 🔴 |
chrono | Enableschrono types support | 🔴 |
rust_decimal | Enablesrust_decimal types support | 🔴 |
time | Enablestime v0.3.x types support | 🔴 |
frunk | EnablesFromRow forfrunk::Hlist! types | 🔴 |
derive | EnablesFromValue andFromRow derive macros | 🟢 |
binlog | Binlog-related functionality | 🔴 |
client_ed25519 | Enablesed25519 authentication plugin support | 🔴 |
Supported derivations:
- for enum – you should carefully read thecorresponding section of MySql documentation.
- for newtypes (seeNew Type Idiom) – given that the wrapped type itself satisfies
FromValue
.
#[mysql(crate_name = "some_name")]
– overrides an attempt to guess a crate that providesrequired traits#[mysql(rename_all = ...)]
– rename all the variants according to the given caseconvention. The possible values are "lowercase", "UPPERCASE", "PascalCase", "camelCase","snake_case", "SCREAMING_SNAKE_CASE", "kebab-case", "SCREAMING-KEBAB-CASE"#[mysql(is_integer)]
– tells derive macro that the value is an integer rather than MySqlENUM. Macro won't warn if variants are sparse or greater than u16 and will not try to parsetextual representation.#[mysql(is_string)]
– tells derive macro that the value is a string rather than MySqlENUM. Macro won't warn if variants are sparse or greater than u16 and will not try to parseinteger representation.
GivenENUM('x-small', 'small', 'medium', 'large', 'x-large')
on MySql side:
fnmain(){/// Note: the `crate_name` attribute should not be necessary.#[derive(FromValue)]#[mysql(rename_all ="kebab-case", crate_name ="mysql_common")]#[repr(u8)]enumSize{XSmall =1,Small,Medium,Large,XLarge,}fnassert_from_row_works(x:Row) ->Size{from_row(x)}}
It is expected, that wrapper value satisfiesFromValue
ordeserialize_with
is given.Also note, that to supportFromRow
the wrapped value must satisfyInto<Value>
orserialize_with
must be given.
#[mysql(crate_name = "some_name")]
– overrides an attempt to guess a crate to import types from#[mysql(bound = "Foo: Bar, Baz: Quux")]
– use the following additional bounds#[mysql(deserialize_with = "some::path")]
– use the following function to deserializethe wrapped value. Expected signature isfn (Value) -> Result<Wrapped, FromValueError>
.#[mysql(serialize_with = "some::path")]
– use the following function to serializethe wrapped value. Expected signature isfn (Wrapped) -> Value
.
/// Trivial example#[derive(FromValue)]structInch(i32);/// Example of a {serialize|deserialize}_with.#[derive(FromValue)]#[mysql(deserialize_with ="neg_de", serialize_with ="neg_ser")]structNeg(i64);/// Wrapped generic. Bounds are inferred.#[derive(FromValue)]structFoo<T>(Option<T>);/// Example of additional bounds.#[derive(FromValue)]#[mysql(bound ="'b: 'a, T: 'a, U: From<String>, V: From<u64>")]structBar<'a,'b,constN:usize,T,U,V>(ComplexTypeToWrap<'a,'b,N,T,U,V>);fnassert_from_row_works<'a,'b,constN:usize,T,U,V>(x:Row) ->(Inch,Neg,Foo<u8>,Bar<'a,'b,N,T,U,V>)where'b:'a,T:'a,U:From<String>,V:From<u64>,{from_row(x)}// test boilerplate../// Dummy complex type with additional bounds on FromValue impl.structComplexTypeToWrap<'a,'b,constN:usize,T,U,V>([(&'aT,&'bU,V);N]);structFakeIr;implTryFrom<Value>forFakeIr{// ...}impl<'a,'b:'a,constN:usize,T:'a,U:From<String>,V:From<u64>>From<FakeIr>forComplexTypeToWrap<'a,'b,N,T,U,V>{// ...}implFrom<FakeIr>forValue{// ...}impl<'a,'b:'a,constN:usize,T:'a,U:From<String>,V:From<u64>>FromValueforComplexTypeToWrap<'a,'b,N,T,U,V>{typeIntermediate =FakeIr;}fnneg_de(v:Value) ->Result<i64,FromValueError>{match v{Value::Int(x) =>Ok(-x),Value::UInt(x) =>Ok(-(xasi64)), x =>Err(FromValueError(x)),}}fnneg_ser(x:i64) ->Value{Value::Int(-x)}
Also defines some constants on the struct:
const TABLE_NAME: &str
– iftable_name
is givenconst {}_FIELD: &str
– for each struct field ({}
is a SCREAMING_SNAKE_CASE representationof a struct field name (not a column name))
Supported derivations:
- for a struct with named fields – field name will be used as a column name to search for a value
#[mysql(crate_name = "some_name")]
– overrides an attempt to guess a crate that providesrequired traits#[mysql(rename_all = ...)]
– rename all column names according to the given caseconvention. The possible values are "lowercase", "UPPERCASE", "PascalCase", "camelCase","snake_case", "SCREAMING_SNAKE_CASE", "kebab-case", "SCREAMING-KEBAB-CASE"#[mysql(table_name = "some_name")]
– definespub const TABLE_NAME: &str
on the struct
#[mysql(rename = "some_name")]
– overrides column name of a field#[mysql(json)]
- column will be interpreted as a JSON string containinga value of a field type#[mysql(deserialize_with = "some::path")]
– the following functionwill be used to deserialize the field (instead ofFromValue
). Expected signature isfn (Value) -> Result<T, FromValueError>
.#[mysql(serialize_with = "some::path")]
– the following functionwill be used to serialize the field (instead ofInto<Value>
). Expected signature isfn (T) -> Value
.
use time::{ macros::{datetime, offset},OffsetDateTime,PrimitiveDateTime,UtcOffset,};/// Note: the `crate_name` attribute should not be necessary.#[derive(Debug,PartialEq,Eq,FromRow)]#[mysql(table_name ="Foos", crate_name ="mysql_common")]structFoo{id:u64,#[mysql( serialize_with ="datetime_to_value", deserialize_with ="value_to_datetime",)]ctime:OffsetDateTime,#[mysql(json, rename ="def")]definition:Bar,child:Option<u64>,}fnvalue_to_datetime(value:Value) ->Result<OffsetDateTime,FromValueError>{// assume mysql session timezone has been properly set upconstOFFSET:UtcOffset =offset!(+3);let primitive =PrimitiveDateTime::from_value_opt(value)?;Ok(primitive.assume_offset(OFFSET))}fndatetime_to_value(datetime:OffsetDateTime) ->Value{// assume mysql session timezone has been properly set upPrimitiveDateTime::new(datetime.date(), datetime.time()).into()}#[derive(Debug, serde::Deserialize,PartialEq,Eq)]enumBar{Left,Right,}/// Returns the following row:////// ```/// +----+-----------+-------+------------------------+/// | id | def | child | ctime |/// +----+-----------+-------+------------------------+/// | 42 | '"Right"' | NULL | '2015-05-15 12:00:00' |/// +----+-----------+-------+------------------------+/// ```fnget_row() ->Row{// ...}assert_eq!(Foo::TABLE_NAME,"Foos");assert_eq!(Foo::ID_FIELD,"id");assert_eq!(Foo::DEFINITION_FIELD,"def");assert_eq!(Foo::CHILD_FIELD,"child");let foo =from_row::<Foo>(get_row());assert_eq!( foo,Foo{ id:42, definition:Bar::Right, child:None, ctime: datetime!(2015-05-1512:00 +3),});
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE orhttp://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT orhttp://opensource.org/licenses/MIT)at your option.
Unless you explicitly state otherwise, any contribution intentionally submittedfor inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without anyadditional terms or conditions.
About
Common primitives of MySql protocol.
Resources
License
Apache-2.0, MIT licenses found
Licenses found
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.