opendal/services/d1/
model.rs1use std::fmt::Debug;
19
20use bytes::Bytes;
21use serde::Deserialize;
22use serde::Serialize;
23use serde_json::Map;
24use serde_json::Value;
25
26use crate::Buffer;
27use crate::Error;
28
29#[derive(Deserialize, Debug)]
31pub struct D1Response {
32 pub result: Vec<D1Result>,
33 pub success: bool,
34 pub errors: Vec<D1Error>,
35}
36
37impl D1Response {
38 pub fn parse(bs: &Bytes) -> Result<D1Response, Error> {
39 let response: D1Response = serde_json::from_slice(bs).map_err(|e| {
40 Error::new(
41 crate::ErrorKind::Unexpected,
42 format!("failed to parse error response: {}", e),
43 )
44 })?;
45
46 if !response.success {
47 return Err(Error::new(
48 crate::ErrorKind::Unexpected,
49 String::from_utf8_lossy(bs),
50 ));
51 }
52 Ok(response)
53 }
54
55 pub fn get_result(&self, key: &str) -> Option<Buffer> {
56 if self.result.is_empty() || self.result[0].results.is_empty() {
57 return None;
58 }
59 let result = &self.result[0].results[0];
60 let value = result.get(key);
61
62 match value {
63 Some(Value::Array(s)) => {
64 let mut v = Vec::new();
65 for i in s {
66 if let Value::Number(n) = i {
67 v.push(n.as_u64().unwrap() as u8);
68 }
69 }
70 Some(Buffer::from(v))
71 }
72 _ => None,
73 }
74 }
75}
76
77#[derive(Deserialize, Debug)]
78pub struct D1Result {
79 pub results: Vec<Map<String, Value>>,
80}
81
82#[derive(Clone, Deserialize, Debug, Serialize)]
83pub struct D1Error {
84 pub message: String,
85 pub code: i32,
86}
87
88#[cfg(test)]
89mod test {
90 use super::*;
91
92 #[test]
93 fn test_deserialize_get_object_json_response() {
94 let data = r#"
95 {
96 "result": [
97 {
98 "results": [
99 {
100 "CustomerId": "4",
101 "CompanyName": "Around the Horn",
102 "ContactName": "Thomas Hardy"
103 }
104 ],
105 "success": true,
106 "meta": {
107 "served_by": "v3-prod",
108 "duration": 0.2147,
109 "changes": 0,
110 "last_row_id": 0,
111 "changed_db": false,
112 "size_after": 2162688,
113 "rows_read": 3,
114 "rows_written": 2
115 }
116 }
117 ],
118 "success": true,
119 "errors": [],
120 "messages": []
121 }"#;
122 let response: D1Response = serde_json::from_str(data).unwrap();
123 println!("{:?}", response.result[0].results[0]);
124 }
125}