Struct sqlx::types::Text

source ยท
pub struct Text<T>(pub T);
Expand description

Map a SQL text value to/from a Rust type using Display and FromStr.

This can be useful for types that do not have a direct SQL equivalent, or are simply not supported by SQLx for one reason or another.

For strongly typed databases like Postgres, this will report the valueโ€™s type as TEXT. Explicit conversion may be necessary on the SQL side depending on the desired type.

ยงPanics

You should only use this adapter with Display implementations that are infallible, otherwise you may encounter panics when attempting to bind a value.

This is because the design of the Encode trait assumes encoding is infallible, so there is no way to bubble up the error.

Fortunately, most Display implementations are infallible by convention anyway (the standard ToString trait also assumes this), but you may still want to audit the source code for any types you intend to use with this adapter, just to be safe.

ยงExample: SocketAddr

MySQL and SQLite do not have a native SQL equivalent for SocketAddr, so if you want to store and retrieve instances of it, it makes sense to map it to TEXT:


use std::net::SocketAddr;

use sqlx::Connection;
use sqlx::mysql::MySqlConnection;
use sqlx::types::Text;

use uuid::Uuid;
use time::OffsetDateTime;

#[derive(sqlx::FromRow, Debug)]
struct Login {
    user_id: Uuid,
    socket_addr: Text<SocketAddr>,
    login_at: OffsetDateTime
}


let mut conn: MySqlConnection = MySqlConnection::connect("<DATABASE URL>").await?;

let user_id: Uuid = "e9a72cdc-d907-48d6-a488-c64a91fd063c".parse().unwrap();
let socket_addr: SocketAddr = "198.51.100.47:31790".parse().unwrap();

// CREATE TABLE user_login(user_id VARCHAR(36), socket_addr TEXT, login_at TIMESTAMP);
sqlx::query("INSERT INTO user_login(user_id, socket_addr, login_at) VALUES (?, ?, NOW())")
    .bind(user_id)
    .bind(Text(socket_addr))
    .execute(&mut conn)
    .await?;

let logins: Vec<Login> = sqlx::query_as("SELECT * FROM user_login")
    .fetch_all(&mut conn)
    .await?;

println!("Logins for user ID {user_id}: {logins:?}");

Tuple Fieldsยง

ยง0: T

Implementationsยง

sourceยง

impl<T> Text<T>

source

pub fn into_inner(self) -> T

Extract the inner value.

Trait Implementationsยง

sourceยง

impl<T> Clone for Text<T>
where T: Clone,

sourceยง

fn clone(&self) -> Text<T>

Returns a copy of the value. Read more
1.0.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl<T> Debug for Text<T>
where T: Debug,

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
sourceยง

impl<'r, T> Decode<'r, MySql> for Text<T>
where T: FromStr, Box<dyn Error + Send + Sync>: From<<T as FromStr>::Err>,

sourceยง

fn decode( value: MySqlValueRef<'r> ) -> Result<Text<T>, Box<dyn Error + Send + Sync>>

Decode a new value of this type using a raw value from the database.
sourceยง

impl<'r, T> Decode<'r, Postgres> for Text<T>
where T: FromStr, Box<dyn Error + Send + Sync>: From<<T as FromStr>::Err>,

sourceยง

fn decode( value: PgValueRef<'r> ) -> Result<Text<T>, Box<dyn Error + Send + Sync>>

Decode a new value of this type using a raw value from the database.
sourceยง

impl<'r, T> Decode<'r, Sqlite> for Text<T>
where T: FromStr, Box<dyn Error + Send + Sync>: From<<T as FromStr>::Err>,

sourceยง

fn decode( value: SqliteValueRef<'r> ) -> Result<Text<T>, Box<dyn Error + Send + Sync>>

Decode a new value of this type using a raw value from the database.
sourceยง

impl<T> Default for Text<T>
where T: Default,

sourceยง

fn default() -> Text<T>

Returns the โ€œdefault valueโ€ for a type. Read more
sourceยง

impl<T> Deref for Text<T>

ยง

type Target = T

The resulting type after dereferencing.
sourceยง

fn deref(&self) -> &<Text<T> as Deref>::Target

Dereferences the value.
sourceยง

impl<T> DerefMut for Text<T>

sourceยง

fn deref_mut(&mut self) -> &mut <Text<T> as Deref>::Target

Mutably dereferences the value.
sourceยง

impl<'q, T> Encode<'q, MySql> for Text<T>
where T: Display,

sourceยง

fn encode_by_ref(&self, buf: &mut Vec<u8>) -> IsNull

Writes the value of self into buf without moving self. Read more
sourceยง

fn encode(self, buf: &mut <DB as HasArguments<'q>>::ArgumentBuffer) -> IsNull
where Self: Sized,

Writes the value of self into buf in the expected format for the database.
sourceยง

fn produces(&self) -> Option<<DB as Database>::TypeInfo>

sourceยง

fn size_hint(&self) -> usize

sourceยง

impl<'q, T> Encode<'q, Postgres> for Text<T>
where T: Display,

sourceยง

fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull

Writes the value of self into buf without moving self. Read more
sourceยง

fn encode(self, buf: &mut <DB as HasArguments<'q>>::ArgumentBuffer) -> IsNull
where Self: Sized,

Writes the value of self into buf in the expected format for the database.
sourceยง

fn produces(&self) -> Option<<DB as Database>::TypeInfo>

sourceยง

fn size_hint(&self) -> usize

sourceยง

impl<'q, T> Encode<'q, Sqlite> for Text<T>
where T: Display,

sourceยง

fn encode_by_ref(&self, buf: &mut Vec<SqliteArgumentValue<'q>>) -> IsNull

Writes the value of self into buf without moving self. Read more
sourceยง

fn encode(self, buf: &mut <DB as HasArguments<'q>>::ArgumentBuffer) -> IsNull
where Self: Sized,

Writes the value of self into buf in the expected format for the database.
sourceยง

fn produces(&self) -> Option<<DB as Database>::TypeInfo>

sourceยง

fn size_hint(&self) -> usize

sourceยง

impl<T> Ord for Text<T>
where T: Ord,

sourceยง

fn cmp(&self, other: &Text<T>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 ยท sourceยง

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 ยท sourceยง

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 ยท sourceยง

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
sourceยง

impl<T> PartialEq for Text<T>
where T: PartialEq,

sourceยง

fn eq(&self, other: &Text<T>) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 ยท sourceยง

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
sourceยง

impl<T> PartialOrd for Text<T>
where T: PartialOrd,

sourceยง

fn partial_cmp(&self, other: &Text<T>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 ยท sourceยง

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 ยท sourceยง

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 ยท sourceยง

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 ยท sourceยง

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
sourceยง

impl<T> PgHasArrayType for Text<T>

sourceยง

impl<T> Type<MySql> for Text<T>

sourceยง

fn type_info() -> MySqlTypeInfo

Returns the canonical SQL type for this Rust type. Read more
sourceยง

fn compatible(ty: &MySqlTypeInfo) -> bool

Determines if this Rust type is compatible with the given SQL type. Read more
sourceยง

impl<T> Type<Postgres> for Text<T>

sourceยง

fn type_info() -> PgTypeInfo

Returns the canonical SQL type for this Rust type. Read more
sourceยง

fn compatible(ty: &PgTypeInfo) -> bool

Determines if this Rust type is compatible with the given SQL type. Read more
sourceยง

impl<T> Type<Sqlite> for Text<T>

sourceยง

fn type_info() -> SqliteTypeInfo

Returns the canonical SQL type for this Rust type. Read more
sourceยง

fn compatible(ty: &SqliteTypeInfo) -> bool

Determines if this Rust type is compatible with the given SQL type. Read more
sourceยง

impl<T> Copy for Text<T>
where T: Copy,

sourceยง

impl<T> Eq for Text<T>
where T: Eq,

sourceยง

impl<T> StructuralPartialEq for Text<T>

Auto Trait Implementationsยง

ยง

impl<T> Freeze for Text<T>
where T: Freeze,

ยง

impl<T> RefUnwindSafe for Text<T>
where T: RefUnwindSafe,

ยง

impl<T> Send for Text<T>
where T: Send,

ยง

impl<T> Sync for Text<T>
where T: Sync,

ยง

impl<T> Unpin for Text<T>
where T: Unpin,

ยง

impl<T> UnwindSafe for Text<T>
where T: UnwindSafe,

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<Q, K> Comparable<K> for Q
where Q: Ord + ?Sized, K: Borrow<Q> + ?Sized,

sourceยง

fn compare(&self, key: &K) -> Ordering

Compare self to key and return their ordering.
sourceยง

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

sourceยง

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
sourceยง

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

sourceยง

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

sourceยง

impl<T> Instrument for T

sourceยง

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
sourceยง

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
sourceยง

impl<T, U> Into<U> for T
where U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

sourceยง

impl<T> Same for T

ยง

type Output = T

Should always be Self
sourceยง

impl<T> ToOwned for T
where T: Clone,

ยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where U: Into<T>,

ยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

ยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
sourceยง

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

sourceยง

fn vzip(self) -> V

sourceยง

impl<T> WithSubscriber for T

sourceยง

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
sourceยง

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
sourceยง

impl<T> Formattable for T
where T: Deref, <T as Deref>::Target: Formattable,

sourceยง

impl<T> Parsable for T
where T: Deref, <T as Deref>::Target: Parsable,