Struct sqlx_core::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> Clone for Text<T>

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> Debug for Text<T>

source§

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

Formats the value using the given formatter. Read more
source§

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

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) -> &Self::Target

Dereferences the value.
source§

impl<T> DerefMut for Text<T>

source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
source§

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

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) -> Selfwhere Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

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

Compares and returns the minimum of two values. Read more
1.50.0 · source§

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

Restrict a value to a certain interval. Read more
source§

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

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> PartialOrd for Text<T>

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: Copy> Copy for Text<T>

source§

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

source§

impl<T> StructuralEq for Text<T>

source§

impl<T> StructuralPartialEq for Text<T>

Auto Trait Implementations§

§

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 Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

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

Mutably borrows from an owned value. Read more
§

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

§

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

Compare self to key and return their ordering.
§

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

§

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

Checks if this value is equivalent to the given key. Read more
§

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

§

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 Twhere 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> ToOwned for Twhere 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 Twhere 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 Twhere 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<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