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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
use std::{fmt, string::String as StdString};
use sqlx::{
encode::{Encode, IsNull},
Database, Decode, Type,
};
use unicode_normalization::UnicodeNormalization as _;
#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(from = "StdString", into = "StdString")]
pub struct String(StdString);
impl fmt::Display for String {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self(value) = self;
value.fmt(f)
}
}
impl From<StdString> for String {
fn from(value: StdString) -> Self {
let value = value.nfc().collect();
Self(value)
}
}
impl From<String> for StdString {
fn from(value: String) -> Self {
let String(value) = value;
value
}
}
impl std::ops::Deref for String {
type Target = StdString;
fn deref(&self) -> &Self::Target {
let Self(value) = self;
value
}
}
// Type is manually implemented so that we can implement Decode to do
// normalization on read. Implementation is otherwise based on
// `#[derive(sqlx::Type)]` with the `#[sqlx(transparent)]` attribute.
impl<DB> Type<DB> for String
where
DB: Database,
StdString: Type<DB>,
{
fn type_info() -> <DB as Database>::TypeInfo {
<StdString as Type<DB>>::type_info()
}
fn compatible(ty: &<DB as Database>::TypeInfo) -> bool {
<StdString as Type<DB>>::compatible(ty)
}
}
impl<'r, DB> Decode<'r, DB> for String
where
DB: Database,
StdString: Decode<'r, DB>,
{
fn decode(value: <DB as Database>::ValueRef<'r>) -> Result<Self, sqlx::error::BoxDynError> {
let value = StdString::decode(value)?;
let value = value.nfc().collect();
Ok(Self(value))
}
}
impl<'q, DB> Encode<'q, DB> for String
where
DB: Database,
StdString: Encode<'q, DB>,
{
fn encode_by_ref(
&self,
buf: &mut <DB as Database>::ArgumentBuffer<'q>,
) -> Result<IsNull, sqlx::error::BoxDynError> {
let Self(value) = self;
value.encode_by_ref(buf)
}
fn encode(
self,
buf: &mut <DB as Database>::ArgumentBuffer<'q>,
) -> Result<IsNull, sqlx::error::BoxDynError> {
let Self(value) = self;
value.encode(buf)
}
fn produces(&self) -> Option<<DB as Database>::TypeInfo> {
let Self(value) = self;
value.produces()
}
fn size_hint(&self) -> usize {
let Self(value) = self;
value.size_hint()
}
}
|