opendal/services/mysql/
config.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 serde::Deserialize;
21use serde::Serialize;
22
23use super::backend::MysqlBuilder;
24
25/// Config for Mysql services support.
26#[derive(Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
27#[serde(default)]
28#[non_exhaustive]
29pub struct MysqlConfig {
30    /// This connection string is used to connect to the mysql service. There are url based formats.
31    ///
32    /// The format of connect string resembles the url format of the mysql client.
33    /// The format is: `[scheme://][user[:[password]]@]host[:port][/schema][?attribute1=value1&attribute2=value2...`
34    ///
35    /// - `mysql://user@localhost`
36    /// - `mysql://user:password@localhost`
37    /// - `mysql://user:password@localhost:3306`
38    /// - `mysql://user:password@localhost:3306/db`
39    ///
40    /// For more information, please refer to <https://docs.rs/sqlx/latest/sqlx/mysql/struct.MySqlConnectOptions.html>.
41    pub connection_string: Option<String>,
42
43    /// The table name for mysql.
44    pub table: Option<String>,
45    /// The key field name for mysql.
46    pub key_field: Option<String>,
47    /// The value field name for mysql.
48    pub value_field: Option<String>,
49    /// The root for mysql.
50    pub root: Option<String>,
51}
52
53impl Debug for MysqlConfig {
54    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        f.debug_struct("MysqlConfig")
56            .field("root", &self.root)
57            .field("table", &self.table)
58            .field("key_field", &self.key_field)
59            .field("value_field", &self.value_field)
60            .finish_non_exhaustive()
61    }
62}
63
64impl crate::Configurator for MysqlConfig {
65    type Builder = MysqlBuilder;
66
67    fn from_uri(uri: &crate::types::OperatorUri) -> crate::Result<Self> {
68        let mut map = uri.options().clone();
69
70        if let Some(authority) = uri.authority() {
71            map.entry("connection_string".to_string())
72                .or_insert_with(|| format!("mysql://{authority}"));
73        }
74
75        if let Some(path) = uri.root() {
76            if !path.is_empty() {
77                let (table_segment, rest) = match path.split_once('/') {
78                    Some((table, remainder)) => (table, Some(remainder)),
79                    None => (path, None),
80                };
81
82                if !table_segment.is_empty() {
83                    map.entry("table".to_string())
84                        .or_insert_with(|| table_segment.to_string());
85                }
86
87                if let Some(root) = rest {
88                    if !root.is_empty() {
89                        map.insert("root".to_string(), root.to_string());
90                    }
91                }
92            }
93        }
94
95        Self::from_iter(map)
96    }
97
98    fn into_builder(self) -> Self::Builder {
99        MysqlBuilder { config: self }
100    }
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106    use crate::Configurator;
107    use crate::types::OperatorUri;
108
109    #[test]
110    fn from_uri_sets_connection_string_table_and_root() {
111        let uri = OperatorUri::new(
112            "mysql://db.example.com:3306/kv/cache",
113            Vec::<(String, String)>::new(),
114        )
115        .unwrap();
116
117        let cfg = MysqlConfig::from_uri(&uri).unwrap();
118        assert_eq!(
119            cfg.connection_string.as_deref(),
120            Some("mysql://db.example.com:3306")
121        );
122        assert_eq!(cfg.table.as_deref(), Some("kv"));
123        assert_eq!(cfg.root.as_deref(), Some("cache"));
124    }
125
126    #[test]
127    fn from_uri_respects_existing_table() {
128        let uri = OperatorUri::new(
129            "mysql://db.example.com:3306/users?root=logs",
130            Vec::<(String, String)>::new(),
131        )
132        .unwrap();
133
134        let cfg = MysqlConfig::from_uri(&uri).unwrap();
135        assert_eq!(cfg.table.as_deref(), Some("users"));
136        assert_eq!(cfg.root.as_deref(), Some("logs"));
137    }
138}