1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use url::Url;
use crate::Result;
use crate::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef};
impl ToSql for Url {
fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
Ok(ToSqlOutput::from(self.as_str()))
}
}
impl FromSql for Url {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
match value {
ValueRef::Text(s) => Url::parse(s),
_ => return Err(FromSqlError::InvalidType),
}
.map_err(|err| FromSqlError::Other(Box::new(err)))
}
}
#[cfg(test)]
mod test {
use url::{Url, ParseError};
use crate::{Connection, params, Error, Result};
fn checked_memory_handle() -> Connection {
let db = Connection::open_in_memory().unwrap();
db.execute_batch("CREATE TABLE urls (i INTEGER, v TEXT)")
.unwrap();
db
}
fn get_url(db: &Connection, id: i64) -> Result<Url> {
db.query_row(
"SELECT v FROM urls WHERE i = ?",
params![id],
|r| r.get(0),
)
}
#[test]
fn test_sql_url() {
let db = &checked_memory_handle();
let url0 = Url::parse("http://www.example1.com").unwrap();
let url1 = Url::parse("http://www.example1.com/👌").unwrap();
let url2 = "http://www.example2.com/👌";
db.execute(
"INSERT INTO urls (i, v) VALUES (0, ?), (1, ?), (2, ?), (3, ?)",
params![url0, url1, url2, "illegal"],
)
.unwrap();
assert_eq!(get_url(db, 0).unwrap(), url0);
assert_eq!(get_url(db, 1).unwrap(), url1);
let out_url2: Url = get_url(db, 2).unwrap();
assert_eq!(out_url2, Url::parse(url2).unwrap());
let err = get_url(db, 3).unwrap_err();
match err {
Error::FromSqlConversionFailure(_, _, e) => {
assert_eq!(
*e.downcast::<ParseError>().unwrap(),
ParseError::RelativeUrlWithoutBase,
);
}
e => {
panic!("Expected conversion failure, got {}", e);
}
}
}
}