zino_orm/
decode.rs

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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
use super::{DatabaseDriver, DatabaseRow};
use sqlx::{Database, Decode, Row, ValueRef};
use zino_core::{error::Error, warn, Decimal, Uuid};

/// Decodes a single value as `T` for the field in a row.
#[inline]
pub fn decode<'r, T>(row: &'r DatabaseRow, field: &str) -> Result<T, Error>
where
    T: Decode<'r, DatabaseDriver>,
{
    row.try_get_unchecked(field)
        .map_err(|err| warn!("fail to decode the `{}` field: {}", field, err))
}

/// Decodes a single value as `T` for the field in a row,
/// returning `None` if it was not found.
#[inline]
pub fn decode_optional<'r, T>(row: &'r DatabaseRow, field: &str) -> Result<Option<T>, Error>
where
    T: Decode<'r, DatabaseDriver>,
{
    match row.try_get_raw(field) {
        Ok(value) => {
            if value.is_null() {
                Ok(None)
            } else {
                let value = decode_raw(field, value)?;
                Ok(Some(value))
            }
        }
        Err(err) => {
            if let sqlx::Error::ColumnNotFound(_) = err {
                Ok(None)
            } else {
                Err(warn!("fail to get the `{}` field: {}", field, err))
            }
        }
    }
}

/// Decodes a single value as `Decimal` for the field in a row.
#[cfg(any(
    feature = "orm-mariadb",
    feature = "orm-mysql",
    feature = "orm-postgres",
    feature = "orm-tidb"
))]
#[inline]
pub fn decode_decimal(row: &DatabaseRow, field: &str) -> Result<Decimal, Error> {
    match row.try_get_raw(field) {
        Ok(value) => {
            if value.is_null() {
                Ok(Decimal::ZERO)
            } else {
                let value = decode_raw(field, value)?;
                Ok(value)
            }
        }
        Err(err) => {
            if let sqlx::Error::ColumnNotFound(_) = err {
                Ok(Decimal::ZERO)
            } else {
                Err(warn!("fail to get the `{}` field: {}", field, err))
            }
        }
    }
}

/// Decodes a single value as `Decimal` for the field in a row.
#[cfg(not(any(
    feature = "orm-mariadb",
    feature = "orm-mysql",
    feature = "orm-postgres",
    feature = "orm-tidb"
)))]
#[inline]
pub fn decode_decimal(row: &DatabaseRow, field: &str) -> Result<Decimal, Error> {
    let Some(value) = decode_optional::<String>(row, field)? else {
        return Ok(Decimal::ZERO);
    };
    value
        .parse()
        .map_err(|err| warn!("fail to decode the `{}` field: {}", field, err))
}

/// Decodes a single value as `Uuid` for the field in a row.
#[cfg(feature = "orm-postgres")]
#[inline]
pub fn decode_uuid(row: &DatabaseRow, field: &str) -> Result<Uuid, Error> {
    match row.try_get_raw(field) {
        Ok(value) => {
            if value.is_null() {
                Ok(Uuid::nil())
            } else {
                let id = decode_raw(field, value)?;
                Ok(id)
            }
        }
        Err(err) => {
            if let sqlx::Error::ColumnNotFound(_) = err {
                Ok(Uuid::nil())
            } else {
                Err(warn!("fail to get the `{}` field: {}", field, err))
            }
        }
    }
}

/// Decodes a single value as `Uuid` for the field in a row.
#[cfg(not(feature = "orm-postgres"))]
#[inline]
pub fn decode_uuid(row: &DatabaseRow, field: &str) -> Result<Uuid, Error> {
    let Some(value) = decode_optional::<String>(row, field)? else {
        return Ok(Uuid::nil());
    };
    value
        .parse()
        .map_err(|err| warn!("fail to decode the `{}` field: {}", field, err))
}

/// Decodes a single value as `Vec<T>` for the field in a row.
#[cfg(feature = "orm-postgres")]
#[inline]
pub fn decode_array<'r, T>(row: &'r DatabaseRow, field: &str) -> Result<Vec<T>, Error>
where
    T: for<'a> Decode<'a, DatabaseDriver> + sqlx::Type<DatabaseDriver>,
{
    match row.try_get_raw(field) {
        Ok(value) => {
            if value.is_null() {
                Ok(Vec::new())
            } else {
                let vec = decode_raw(field, value)?;
                Ok(vec)
            }
        }
        Err(err) => {
            if let sqlx::Error::ColumnNotFound(_) = err {
                Ok(Vec::new())
            } else {
                Err(warn!("fail to get the `{}` field: {}", field, err))
            }
        }
    }
}

/// Decodes a single value as `Vec<T>` for the field in a row.
#[cfg(feature = "orm-mariadb")]
#[inline]
pub fn decode_array<'r, T>(row: &'r DatabaseRow, field: &str) -> Result<Vec<T>, Error>
where
    T: Decode<'r, DatabaseDriver> + serde::de::DeserializeOwned,
{
    let Some(value) = decode_optional::<String>(row, field)? else {
        return Ok(Vec::new());
    };
    if value.starts_with('[') && value.ends_with(']') {
        serde_json::from_str(&value)
            .map_err(|err| warn!("fail to decode the `{}` field: {}", field, err))
    } else {
        zino_core::bail!("invalid array data for the `{}` field", field);
    }
}

/// Decodes a single value as `Vec<T>` for the field in a row.
#[cfg(not(any(feature = "orm-mariadb", feature = "orm-postgres")))]
#[inline]
pub fn decode_array<'r, T>(row: &'r DatabaseRow, field: &str) -> Result<Vec<T>, Error>
where
    T: Decode<'r, DatabaseDriver> + std::str::FromStr,
    <T as std::str::FromStr>::Err: std::error::Error + Send + 'static,
{
    use zino_core::{extension::JsonValueExt, JsonValue};

    let Some(value) = decode_optional::<JsonValue>(row, field)? else {
        return Ok(Vec::new());
    };
    if let Some(result) = value.parse_array() {
        result.map_err(|err| warn!("fail to decode the `{}` field: {}", field, err))
    } else {
        Ok(Vec::new())
    }
}

/// Decodes a raw value at the index.
#[inline]
pub(super) fn decode_raw<'r, T>(
    field: &str,
    value: <DatabaseDriver as Database>::ValueRef<'r>,
) -> Result<T, sqlx::Error>
where
    T: Decode<'r, DatabaseDriver>,
{
    T::decode(value).map_err(|source| {
        tracing::error!("fail to decode the `{}` field", field);
        sqlx::Error::ColumnDecode {
            index: field.to_owned(),
            source,
        }
    })
}