sea_orm/query/
json.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
use crate::{error::*, FromQueryResult, QueryResult};
use serde_json::Map;
pub use serde_json::Value as JsonValue;

impl FromQueryResult for JsonValue {
    #[allow(unused_variables, unused_mut)]
    fn from_query_result(res: &QueryResult, pre: &str) -> Result<Self, DbErr> {
        let mut map = Map::new();
        #[allow(unused_macros)]
        macro_rules! try_get_type {
            ( $type: ty, $col: ident ) => {
                if let Ok(v) = res.try_get::<Option<$type>>(pre, &$col) {
                    map.insert($col.to_owned(), json!(v));
                    continue;
                }
            };
        }
        match &res.row {
            #[cfg(feature = "sqlx-mysql")]
            crate::QueryResultRow::SqlxMySql(row) => {
                use serde_json::json;
                use sqlx::{Column, MySql, Row, Type};
                for column in row.columns() {
                    let col = if !column.name().starts_with(pre) {
                        continue;
                    } else {
                        column.name().replacen(pre, "", 1)
                    };
                    let col_type = column.type_info();
                    macro_rules! match_mysql_type {
                        ( $type: ty ) => {
                            if <$type as Type<MySql>>::type_info().eq(col_type) {
                                try_get_type!($type, col)
                            }
                        };
                    }
                    macro_rules! match_mysql_compatible_type {
                        ( $type: ty ) => {
                            if <$type as Type<MySql>>::compatible(col_type) {
                                try_get_type!($type, col)
                            }
                        };
                    }
                    match_mysql_type!(bool);
                    match_mysql_type!(i8);
                    match_mysql_type!(i16);
                    match_mysql_type!(i32);
                    match_mysql_type!(i64);
                    match_mysql_type!(u8);
                    match_mysql_type!(u16);
                    match_mysql_type!(u32);
                    match_mysql_type!(u64);
                    match_mysql_type!(f32);
                    match_mysql_type!(f64);
                    match_mysql_type!(String);
                    #[cfg(feature = "with-chrono")]
                    match_mysql_type!(chrono::NaiveDate);
                    #[cfg(feature = "with-chrono")]
                    match_mysql_type!(chrono::NaiveTime);
                    #[cfg(feature = "with-chrono")]
                    match_mysql_type!(chrono::NaiveDateTime);
                    #[cfg(feature = "with-chrono")]
                    match_mysql_type!(chrono::DateTime<chrono::Utc>);
                    #[cfg(feature = "with-time")]
                    match_mysql_type!(time::Date);
                    #[cfg(feature = "with-time")]
                    match_mysql_type!(time::Time);
                    #[cfg(feature = "with-time")]
                    match_mysql_type!(time::PrimitiveDateTime);
                    #[cfg(feature = "with-time")]
                    match_mysql_type!(time::OffsetDateTime);
                    #[cfg(feature = "with-rust_decimal")]
                    match_mysql_type!(rust_decimal::Decimal);
                    match_mysql_compatible_type!(String);
                    #[cfg(feature = "with-json")]
                    try_get_type!(serde_json::Value, col);
                    #[cfg(feature = "with-uuid")]
                    try_get_type!(uuid::Uuid, col);
                    try_get_type!(Vec<u8>, col);
                }
                Ok(JsonValue::Object(map))
            }
            #[cfg(feature = "sqlx-postgres")]
            crate::QueryResultRow::SqlxPostgres(row) => {
                use serde_json::json;
                use sqlx::{postgres::types::Oid, Column, Postgres, Row, Type};

                for column in row.columns() {
                    let col = if !column.name().starts_with(pre) {
                        continue;
                    } else {
                        column.name().replacen(pre, "", 1)
                    };
                    let col_type = column.type_info();

                    macro_rules! match_postgres_type {
                        ( $type: ty ) => {
                            match col_type.kind() {
                                #[cfg(feature = "postgres-array")]
                                sqlx::postgres::PgTypeKind::Array(_) => {
                                    if <Vec<$type> as Type<Postgres>>::type_info().eq(col_type) {
                                        try_get_type!(Vec<$type>, col);
                                    }
                                }
                                _ => {
                                    if <$type as Type<Postgres>>::type_info().eq(col_type) {
                                        try_get_type!($type, col);
                                    }
                                }
                            }
                        };
                    }

                    match_postgres_type!(bool);
                    match_postgres_type!(i8);
                    match_postgres_type!(i16);
                    match_postgres_type!(i32);
                    match_postgres_type!(i64);
                    // match_postgres_type!(u8); // unsupported by SQLx Postgres
                    // match_postgres_type!(u16); // unsupported by SQLx Postgres
                    // Since 0.6.0, SQLx has dropped direct mapping from PostgreSQL's OID to Rust's `u32`;
                    // Instead, `u32` was wrapped by a `sqlx::Oid`.
                    if <Oid as Type<Postgres>>::type_info().eq(col_type) {
                        try_get_type!(u32, col)
                    }
                    // match_postgres_type!(u64); // unsupported by SQLx Postgres
                    match_postgres_type!(f32);
                    match_postgres_type!(f64);
                    #[cfg(feature = "with-chrono")]
                    match_postgres_type!(chrono::NaiveDate);
                    #[cfg(feature = "with-chrono")]
                    match_postgres_type!(chrono::NaiveTime);
                    #[cfg(feature = "with-chrono")]
                    match_postgres_type!(chrono::NaiveDateTime);
                    #[cfg(feature = "with-chrono")]
                    match_postgres_type!(chrono::DateTime<chrono::FixedOffset>);
                    #[cfg(feature = "with-time")]
                    match_postgres_type!(time::Date);
                    #[cfg(feature = "with-time")]
                    match_postgres_type!(time::Time);
                    #[cfg(feature = "with-time")]
                    match_postgres_type!(time::PrimitiveDateTime);
                    #[cfg(feature = "with-time")]
                    match_postgres_type!(time::OffsetDateTime);
                    #[cfg(feature = "with-rust_decimal")]
                    match_postgres_type!(rust_decimal::Decimal);
                    #[cfg(feature = "with-json")]
                    try_get_type!(serde_json::Value, col);
                    #[cfg(all(feature = "with-json", feature = "postgres-array"))]
                    try_get_type!(Vec<serde_json::Value>, col);
                    try_get_type!(String, col);
                    #[cfg(feature = "postgres-array")]
                    try_get_type!(Vec<String>, col);
                    #[cfg(feature = "with-uuid")]
                    try_get_type!(uuid::Uuid, col);
                    #[cfg(all(feature = "with-uuid", feature = "postgres-array"))]
                    try_get_type!(Vec<uuid::Uuid>, col);
                    try_get_type!(Vec<u8>, col);
                }
                Ok(JsonValue::Object(map))
            }
            #[cfg(feature = "sqlx-sqlite")]
            crate::QueryResultRow::SqlxSqlite(row) => {
                use serde_json::json;
                use sqlx::{Column, Row, Sqlite, Type};
                for column in row.columns() {
                    let col = if !column.name().starts_with(pre) {
                        continue;
                    } else {
                        column.name().replacen(pre, "", 1)
                    };
                    let col_type = column.type_info();
                    macro_rules! match_sqlite_type {
                        ( $type: ty ) => {
                            if <$type as Type<Sqlite>>::type_info().eq(col_type) {
                                try_get_type!($type, col)
                            }
                        };
                    }
                    match_sqlite_type!(bool);
                    match_sqlite_type!(i8);
                    match_sqlite_type!(i16);
                    match_sqlite_type!(i32);
                    match_sqlite_type!(i64);
                    match_sqlite_type!(u8);
                    match_sqlite_type!(u16);
                    match_sqlite_type!(u32);
                    // match_sqlite_type!(u64); // unsupported by SQLx Sqlite
                    match_sqlite_type!(f32);
                    match_sqlite_type!(f64);
                    #[cfg(feature = "with-chrono")]
                    match_sqlite_type!(chrono::NaiveDate);
                    #[cfg(feature = "with-chrono")]
                    match_sqlite_type!(chrono::NaiveTime);
                    #[cfg(feature = "with-chrono")]
                    match_sqlite_type!(chrono::NaiveDateTime);
                    #[cfg(feature = "with-time")]
                    match_sqlite_type!(time::Date);
                    #[cfg(feature = "with-time")]
                    match_sqlite_type!(time::Time);
                    #[cfg(feature = "with-time")]
                    match_sqlite_type!(time::PrimitiveDateTime);
                    #[cfg(feature = "with-time")]
                    match_sqlite_type!(time::OffsetDateTime);
                    try_get_type!(String, col);
                    #[cfg(feature = "with-uuid")]
                    try_get_type!(uuid::Uuid, col);
                    try_get_type!(Vec<u8>, col);
                }
                Ok(JsonValue::Object(map))
            }
            #[cfg(feature = "mock")]
            crate::QueryResultRow::Mock(row) => {
                for (column, value) in row.clone().into_column_value_tuples() {
                    let col = if !column.starts_with(pre) {
                        continue;
                    } else {
                        column.replacen(pre, "", 1)
                    };
                    map.insert(col, sea_query::sea_value_to_json_value(&value));
                }
                Ok(JsonValue::Object(map))
            }
            #[cfg(feature = "proxy")]
            crate::QueryResultRow::Proxy(row) => {
                for (column, value) in row.clone().into_column_value_tuples() {
                    let col = if !column.starts_with(pre) {
                        continue;
                    } else {
                        column.replacen(pre, "", 1)
                    };
                    map.insert(col, sea_query::sea_value_to_json_value(&value));
                }
                Ok(JsonValue::Object(map))
            }
            #[allow(unreachable_patterns)]
            _ => unreachable!(),
        }
    }
}

#[cfg(test)]
#[cfg(feature = "mock")]
mod tests {
    use crate::tests_cfg::cake;
    use crate::{entity::*, DbBackend, DbErr, MockDatabase};
    use sea_query::Value;

    #[smol_potat::test]
    async fn to_json_1() -> Result<(), DbErr> {
        let db = MockDatabase::new(DbBackend::Postgres)
            .append_query_results([[maplit::btreemap! {
                "id" => Into::<Value>::into(128), "name" => Into::<Value>::into("apple")
            }]])
            .into_connection();

        assert_eq!(
            cake::Entity::find().into_json().one(&db).await.unwrap(),
            Some(serde_json::json!({
                "id": 128,
                "name": "apple"
            }))
        );

        Ok(())
    }
}