| 1 | use std::ops::{Deref, DerefMut}; |
| 2 | |
| 3 | /// Map a SQL text value to/from a Rust type using [`Display`] and [`FromStr`]. |
| 4 | /// |
| 5 | /// This can be useful for types that do not have a direct SQL equivalent, or are simply not |
| 6 | /// supported by SQLx for one reason or another. |
| 7 | /// |
| 8 | /// For strongly typed databases like Postgres, this will report the value's type as `TEXT`. |
| 9 | /// Explicit conversion may be necessary on the SQL side depending on the desired type. |
| 10 | /// |
| 11 | /// [`Display`]: std::fmt::Display |
| 12 | /// [`FromStr`]: std::str::FromStr |
| 13 | /// |
| 14 | /// ### Panics |
| 15 | /// |
| 16 | /// You should only use this adapter with `Display` implementations that are infallible, |
| 17 | /// otherwise you may encounter panics when attempting to bind a value. |
| 18 | /// |
| 19 | /// This is because the design of the `Encode` trait assumes encoding is infallible, so there is no |
| 20 | /// way to bubble up the error. |
| 21 | /// |
| 22 | /// Fortunately, most `Display` implementations are infallible by convention anyway |
| 23 | /// (the standard `ToString` trait also assumes this), but you may still want to audit |
| 24 | /// the source code for any types you intend to use with this adapter, just to be safe. |
| 25 | /// |
| 26 | /// ### Example: `SocketAddr` |
| 27 | /// |
| 28 | /// MySQL and SQLite do not have a native SQL equivalent for `SocketAddr`, so if you want to |
| 29 | /// store and retrieve instances of it, it makes sense to map it to `TEXT`: |
| 30 | /// |
| 31 | /// ```rust,no_run |
| 32 | /// # use sqlx::types::{time, uuid}; |
| 33 | /// |
| 34 | /// use std::net::SocketAddr; |
| 35 | /// |
| 36 | /// use sqlx::Connection; |
| 37 | /// use sqlx::mysql::MySqlConnection; |
| 38 | /// use sqlx::types::Text; |
| 39 | /// |
| 40 | /// use uuid::Uuid; |
| 41 | /// use time::OffsetDateTime; |
| 42 | /// |
| 43 | /// #[derive(sqlx::FromRow, Debug)] |
| 44 | /// struct Login { |
| 45 | /// user_id: Uuid, |
| 46 | /// socket_addr: Text<SocketAddr>, |
| 47 | /// login_at: OffsetDateTime |
| 48 | /// } |
| 49 | /// |
| 50 | /// # async fn example() -> Result<(), Box<dyn std::error::Error>> { |
| 51 | /// |
| 52 | /// let mut conn: MySqlConnection = MySqlConnection::connect("<DATABASE URL>").await?; |
| 53 | /// |
| 54 | /// let user_id: Uuid = "e9a72cdc-d907-48d6-a488-c64a91fd063c".parse().unwrap(); |
| 55 | /// let socket_addr: SocketAddr = "198.51.100.47:31790".parse().unwrap(); |
| 56 | /// |
| 57 | /// // CREATE TABLE user_login(user_id VARCHAR(36), socket_addr TEXT, login_at TIMESTAMP); |
| 58 | /// sqlx::query("INSERT INTO user_login(user_id, socket_addr, login_at) VALUES (?, ?, NOW())") |
| 59 | /// .bind(user_id) |
| 60 | /// .bind(Text(socket_addr)) |
| 61 | /// .execute(&mut conn) |
| 62 | /// .await?; |
| 63 | /// |
| 64 | /// let logins: Vec<Login> = sqlx::query_as("SELECT * FROM user_login") |
| 65 | /// .fetch_all(&mut conn) |
| 66 | /// .await?; |
| 67 | /// |
| 68 | /// println!("Logins for user ID {user_id}: {logins:?}"); |
| 69 | /// |
| 70 | /// # Ok(()) |
| 71 | /// # } |
| 72 | /// ``` |
| 73 | #[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] |
| 74 | pub struct Text<T>(pub T); |
| 75 | |
| 76 | impl<T> Text<T> { |
| 77 | /// Extract the inner value. |
| 78 | pub fn into_inner(self) -> T { |
| 79 | self.0 |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | impl<T> Deref for Text<T> { |
| 84 | type Target = T; |
| 85 | |
| 86 | fn deref(&self) -> &Self::Target { |
| 87 | &self.0 |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | impl<T> DerefMut for Text<T> { |
| 92 | fn deref_mut(&mut self) -> &mut Self::Target { |
| 93 | &mut self.0 |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | /* We shouldn't use blanket impls so individual drivers can provide specialized ones. |
| 98 | impl<T, DB> Type<DB> for Text<T> |
| 99 | where |
| 100 | String: Type<DB>, |
| 101 | DB: Database, |
| 102 | { |
| 103 | fn type_info() -> DB::TypeInfo { |
| 104 | String::type_info() |
| 105 | } |
| 106 | |
| 107 | fn compatible(ty: &DB::TypeInfo) -> bool { |
| 108 | String::compatible(ty) |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | impl<'q, T, DB> Encode<'q, DB> for Text<T> |
| 113 | where |
| 114 | T: Display, |
| 115 | String: Encode<'q, DB>, |
| 116 | DB: Database, |
| 117 | { |
| 118 | fn encode_by_ref(&self, buf: &mut <DB as Database>::ArgumentBuffer<'q>) -> Result<IsNull, BoxDynError> { |
| 119 | self.0.to_string().encode(buf) |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | impl<'r, T, DB> Decode<'r, DB> for Text<T> |
| 124 | where |
| 125 | T: FromStr, |
| 126 | BoxDynError: From<<T as FromStr>::Err>, |
| 127 | &'r str: Decode<'r, DB>, |
| 128 | DB: Database, |
| 129 | { |
| 130 | fn decode(value: <DB as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> { |
| 131 | Ok(Text(<&'r str as Decode<'r, DB>>::decode(value)?.parse()?)) |
| 132 | } |
| 133 | } |
| 134 | */ |