Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Common primitives of MySql protocol.

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT
NotificationsYou must be signed in to change notification settings

blackbeam/rust_mysql_common

Repository files navigation

Gitter

Crates.ioDocs.rsBuild Status

mysql_common

This crate is an implementation of basic MySql protocol primitives.

This crate:

  • defines basic MySql constants;
  • implements necessary functionality for MySqlcached_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

Supported rust types

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:

TypeNotes
{i,u}8..{i,u}128,{i,u}sizeMySql int/uint will be converted, bytes will be parsed.
⚠️ Note that range of{i,u}128 is greater than supported by MySql integer types but it'll be serialized anyway (as decimal bytes string).
f32MySql float will be converted tof32, bytes will be parsed asf32.
⚠️ MySql double won't be converted tof32 to avoid precision loss (see #17)
f64MySql float and double will be converted tof64, bytes will be parsed asf64.
boolMySql int {0,1} or bytes {"0x30","0x31"}
Vec<u8>MySql bytes
StringMySql 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 (⚠️ lossy! microseconds are ignored)
[time::Date] (v0.2.x)MySql date or bytes parsed as MySql date string (⚠️ lossy! microseconds are ignored)
[time::Time] (v0.2.x)MySql time or bytes parsed as MySql time string (⚠️ lossy! microseconds are ignored)
[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 (⚠️ lossy! microseconds are ignored)
[time::Date] (v0.3.x)MySql date or bytes parsed as MySql date string (⚠️ lossy! microseconds are ignored)
[time::Time] (v0.3.x)MySql time or bytes parsed as MySql time string (⚠️ lossy! microseconds are ignored)
[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.
⚠️ Note that this type doesn't support full range of MySqlDECIMAL type.
[bigdecimal::BigDecimal]MySql int, uint, floats or bytes parsed usingBigDecimal::parse_bytes.
⚠️ Note that range of this type is greater than supported by MySqlDECIMAL type but it'll be serialized anyway.
num_bigint::{BigInt, BigUint}MySql int, uint or bytes parsed using_::parse_bytes.
⚠️ Note that range of this type is greater than supported by MySql integer types but it'll be serialized anyway (as decimal bytes string).

Also crate provides from-row convertion for the following list of types (seeFromRow trait):

TypeNotes
RowTrivial conversion forRow itself.
T: FromValueFor rows with a single column.
(T1: FromValue [, ..., T12: FromValue])Row to a tuple of arity 1-12.
[frunk::hlist::HList] typesUsefull to overcome tuple arity limitation

Crate features

FeatureDescriptionDefault
bigdecimalEnablesbigdecimal >=0.3.x, <0.5.x types support🔴
chronoEnableschrono types support🔴
rust_decimalEnablesrust_decimal types support🔴
timeEnablestime v0.3.x types support🔴
frunkEnablesFromRow forfrunk::Hlist! types🔴
deriveEnablesFromValue andFromRow derive macros🟢
binlogBinlog-related functionality🔴
client_ed25519Enablesed25519 authentication plugin support🔴

Derive Macros

FromValue Derive

Supported derivations:

Enums

Container attributes:
  • #[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.
Example

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)}}

Newtypes

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.

Container attributes:
  • #[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.
Example
/// 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)}

FromRow Derive

Also defines some constants on the struct:

  • const TABLE_NAME: &str – iftable_name is given
  • const {}_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

Container attributes:

  • #[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

Field attributes:

  • #[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.

Example

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),});

License

Licensed under either of

Contribution

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

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT

Stars

Watchers

Forks

Packages

No packages published

Contributors37


[8]ページ先頭

©2009-2025 Movatter.jp