opendal/services/d1/
model.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::fmt::Debug;
19
20use bytes::Bytes;
21use serde::Deserialize;
22use serde::Serialize;
23use serde_json::Map;
24use serde_json::Value;
25
26use crate::*;
27
28/// response data from d1
29#[derive(Deserialize, Debug)]
30pub struct D1Response {
31    pub result: Vec<D1Result>,
32    pub success: bool,
33    pub errors: Vec<D1Error>,
34}
35
36impl D1Response {
37    pub fn parse(bs: &Bytes) -> Result<D1Response, Error> {
38        let response: D1Response = serde_json::from_slice(bs).map_err(|e| {
39            Error::new(
40                crate::ErrorKind::Unexpected,
41                format!("failed to parse error response: {e}"),
42            )
43        })?;
44
45        if !response.success {
46            return Err(Error::new(
47                crate::ErrorKind::Unexpected,
48                String::from_utf8_lossy(bs),
49            ));
50        }
51        Ok(response)
52    }
53
54    pub fn get_result(&self, key: &str) -> Option<Buffer> {
55        if self.result.is_empty() || self.result[0].results.is_empty() {
56            return None;
57        }
58        let result = &self.result[0].results[0];
59        let value = result.get(key);
60
61        match value {
62            Some(Value::Array(s)) => {
63                let mut v = Vec::new();
64                for i in s {
65                    if let Value::Number(n) = i {
66                        v.push(n.as_u64().unwrap() as u8);
67                    }
68                }
69                Some(Buffer::from(v))
70            }
71            _ => None,
72        }
73    }
74}
75
76#[derive(Deserialize, Debug)]
77pub struct D1Result {
78    pub results: Vec<Map<String, Value>>,
79}
80
81#[derive(Clone, Deserialize, Debug, Serialize)]
82pub struct D1Error {
83    pub message: String,
84    pub code: i32,
85}
86
87#[cfg(test)]
88mod test {
89    use super::*;
90
91    #[test]
92    fn test_deserialize_get_object_json_response() {
93        let data = r#"
94        {
95            "result": [
96                {
97                    "results": [
98                        {
99                            "CustomerId": "4",
100                            "CompanyName": "Around the Horn",
101                            "ContactName": "Thomas Hardy"
102                        }
103                    ],
104                    "success": true,
105                    "meta": {
106                        "served_by": "v3-prod",
107                        "duration": 0.2147,
108                        "changes": 0,
109                        "last_row_id": 0,
110                        "changed_db": false,
111                        "size_after": 2162688,
112                        "rows_read": 3,
113                        "rows_written": 2
114                    }
115                }
116            ],
117            "success": true,
118            "errors": [],
119            "messages": []
120        }"#;
121        let response: D1Response = serde_json::from_str(data).unwrap();
122        println!("{:?}", response.result[0].results[0]);
123    }
124}