Skip to content

Commit b89eedb

Browse files
committed
impl Encode/Decode for Url
I'd like to use a `Url` as a Sqlite column. This allows it!
1 parent 452da1a commit b89eedb

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

sqlx-sqlite/src/types/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,5 +236,6 @@ mod text;
236236
#[cfg(feature = "time")]
237237
mod time;
238238
mod uint;
239+
mod url;
239240
#[cfg(feature = "uuid")]
240241
mod uuid;

sqlx-sqlite/src/types/url.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
use crate::arguments::SqliteArgumentsBuffer;
2+
use crate::decode::Decode;
3+
use crate::encode::{Encode, IsNull};
4+
use crate::error::BoxDynError;
5+
use crate::type_info::DataType;
6+
use crate::types::Type;
7+
use crate::{Sqlite, SqliteArgumentValue, SqliteTypeInfo, SqliteValueRef};
8+
use std::sync::Arc;
9+
use url::Url;
10+
11+
impl Type<Sqlite> for Url {
12+
fn type_info() -> SqliteTypeInfo {
13+
SqliteTypeInfo(DataType::Text)
14+
}
15+
16+
fn compatible(ty: &SqliteTypeInfo) -> bool {
17+
matches!(ty.0, DataType::Text)
18+
}
19+
}
20+
21+
impl Encode<'_, Sqlite> for Url {
22+
fn encode_by_ref(&self, args: &mut SqliteArgumentsBuffer) -> Result<IsNull, BoxDynError> {
23+
args.push(SqliteArgumentValue::Text(Arc::new(
24+
self.as_str().to_string(),
25+
)));
26+
27+
Ok(IsNull::No)
28+
}
29+
}
30+
31+
impl Decode<'_, Sqlite> for Url {
32+
fn decode(value: SqliteValueRef<'_>) -> Result<Self, BoxDynError> {
33+
Url::parse(value.text_borrowed()?).map_err(Into::into)
34+
}
35+
}

tests/sqlite/types.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use std::borrow::Cow;
1111
use std::net::SocketAddr;
1212
use std::rc::Rc;
1313
use std::sync::Arc;
14+
use url::Url;
1415

1516
test_type!(null<Option<i32>>(Sqlite,
1617
"NULL" == None::<i32>
@@ -218,6 +219,8 @@ test_type!(test_cow_slice<Cow<'_, [u8]>>(Sqlite, "X'01020304'" == Cow::<'static,
218219
test_type!(test_arc_slice<Arc<[u8]>>(Sqlite, "X'01020304'" == Arc::<[u8]>::from([1,2,3,4])));
219220
test_type!(test_rc_slice<Rc<[u8]>>(Sqlite, "X'01020304'" == Rc::<[u8]>::from([1,2,3,4])));
220221

222+
test_type!(test_url<Url>(Sqlite, "'https://example.com/'" == Url::parse("https://example.com/").unwrap()));
223+
221224
#[sqlx_macros::test]
222225
async fn test_text_adapter() -> anyhow::Result<()> {
223226
#[derive(sqlx::FromRow, Debug, PartialEq, Eq)]

0 commit comments

Comments
 (0)