mochow_sdk_rust/mochow/api/
database.rs

1/*
2 * Copyright 2024 Baidu, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
5 * except in compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the
10 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
11 * either express or implied. See the License for the specific language governing permissions
12 * and limitations under the License.
13 */
14
15use derive_builder::Builder;
16use reqwest_middleware::{ClientWithMiddleware, RequestBuilder};
17use serde::{Deserialize, Serialize};
18
19use crate::mochow::{client::IntoRequest, config::ClientConfiguration};
20
21/**
22 * create database args, response with [crate::mochow::api::CommonResponse]
23 */
24#[derive(Debug, Clone, Serialize, Builder)]
25pub struct CreateDatabaseArgs {
26    #[builder(setter(into))]
27    pub database: String,
28}
29
30/**
31 * drop database args, response with [crate::mochow::api::CommonResponse]
32 */
33#[derive(Debug, Clone, Serialize, Builder)]
34pub struct DropDatabaseArgs {
35    #[builder(setter(into))]
36    pub database: String,
37}
38
39/**
40 * list databse args, response with [ListDatabaseResponse]
41 */
42#[derive(Debug, Clone, Builder, Serialize)]
43pub struct ListDatabaseArgs {}
44
45#[derive(Debug, Clone, Deserialize)]
46pub struct ListDatabaseResponse {
47    pub code: i32,
48    pub msg: String,
49
50    #[serde(default)]
51    pub databases: Vec<String>,
52}
53
54impl IntoRequest for CreateDatabaseArgs {
55    fn into_request(
56        self,
57        config: &ClientConfiguration,
58        client: &ClientWithMiddleware,
59    ) -> RequestBuilder {
60        let url = format!("{}/{}/database?create", config.endpoint, config.version);
61        client.post(url).json(&self)
62    }
63}
64
65impl IntoRequest for DropDatabaseArgs {
66    fn into_request(
67        self,
68        config: &ClientConfiguration,
69        client: &ClientWithMiddleware,
70    ) -> RequestBuilder {
71        let url = format!("{}/{}/database", config.endpoint, config.version);
72        client.delete(url).json(&self)
73    }
74}
75
76impl IntoRequest for ListDatabaseArgs {
77    fn into_request(
78        self,
79        config: &ClientConfiguration,
80        client: &ClientWithMiddleware,
81    ) -> RequestBuilder {
82        let url = format!("{}/{}/database?list", config.endpoint, config.version);
83        client.post(url)
84    }
85}
86
87#[cfg(test)]
88mod tests {
89    use crate::error::SdkError;
90    use anyhow::Result;
91
92    use super::*;
93
94    use crate::mochow::{TESTDATABSE, UTCLIENT};
95
96    #[test]
97    fn create_database_param_serialize() -> Result<()> {
98        let param = CreateDatabaseArgsBuilder::default()
99            .database("test_db")
100            .build()?;
101
102        let json = serde_json::to_value(param)?;
103        assert_eq!(
104            json,
105            serde_json::json!({
106                "database":"test_db"
107            })
108        );
109        Ok(())
110    }
111
112    #[test]
113    fn list_database_response_deserialize() -> Result<()> {
114        let data = r#"
115            {
116                "code": 0,
117                "msg": "Success",
118                "databases": [
119                    "test_db1",
120                    "test_db2"
121                ]
122            }
123        "#;
124        let v: ListDatabaseResponse = serde_json::from_str(&data)?;
125        println!("{:?}", v);
126        Ok(())
127    }
128
129    #[tokio::test]
130    async fn test_create_database() -> Result<()> {
131        let _ret = UTCLIENT.create_database(&TESTDATABSE).await;
132        match _ret {
133            Ok(res) => {
134                println!("{:?}", res);
135            }
136            Err(e) => match e {
137                // check service error
138                SdkError::ServiceError(e) => {
139                    println!("{}", e.request_id);
140                    println!("err code: {}", e.resp.code);
141                    println!("err msg: {}", e.resp.msg);
142                    println!("{}", e.status_code);
143                    println!("{:?}", e.server_code);
144                    return Err(SdkError::ServiceError(e).into());
145                }
146                _ => return Err(e.into()),
147            },
148        }
149        // println!("{:?}", _ret);
150        Ok(())
151    }
152
153    #[tokio::test]
154    async fn test_list_database() -> Result<()> {
155        let ret = UTCLIENT.list_database().await?;
156        println!("{:?}", ret);
157        Ok(())
158    }
159
160    #[tokio::test]
161    async fn test_drop_database() -> Result<()> {
162        let ret = UTCLIENT.drop_database(&TESTDATABSE).await?;
163        println!("{:?}", ret);
164        Ok(())
165    }
166}