Skip to main content

opendal_service_mysql/
backend.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;
19use std::sync::Arc;
20
21use mea::once::OnceCell;
22use sqlx::mysql::MySqlConnectOptions;
23
24use super::MYSQL_SCHEME;
25use super::config::MysqlConfig;
26use super::core::*;
27use super::deleter::MysqlDeleter;
28use super::lister::MysqlLazyLister;
29use super::reader::*;
30use super::writer::MysqlWriter;
31use opendal_core::raw::oio;
32use opendal_core::raw::*;
33use opendal_core::*;
34
35#[doc = include_str!("docs.md")]
36#[derive(Debug, Default)]
37pub struct MysqlBuilder {
38    pub(super) config: MysqlConfig,
39}
40
41impl MysqlBuilder {
42    /// Set the connection_string of the mysql service.
43    ///
44    /// This connection string is used to connect to the mysql service. There are url based formats:
45    ///
46    /// ## Url
47    ///
48    /// This format resembles the url format of the mysql client. The format is: `[scheme://][user[:[password]]@]host[:port][/schema][?attribute1=value1&attribute2=value2...`
49    ///
50    /// - `mysql://user@localhost`
51    /// - `mysql://user:password@localhost`
52    /// - `mysql://user:password@localhost:3306`
53    /// - `mysql://user:password@localhost:3306/db`
54    ///
55    /// For more information, please refer to <https://docs.rs/sqlx/latest/sqlx/mysql/struct.MySqlConnectOptions.html>.
56    pub fn connection_string(mut self, v: &str) -> Self {
57        if !v.is_empty() {
58            self.config.connection_string = Some(v.to_string());
59        }
60        self
61    }
62
63    /// set the working directory, all operations will be performed under it.
64    ///
65    /// default: "/"
66    pub fn root(mut self, root: &str) -> Self {
67        self.config.root = if root.is_empty() {
68            None
69        } else {
70            Some(root.to_string())
71        };
72
73        self
74    }
75
76    /// Set the table name of the mysql service to read/write.
77    pub fn table(mut self, table: &str) -> Self {
78        if !table.is_empty() {
79            self.config.table = Some(table.to_string());
80        }
81        self
82    }
83
84    /// Set the key field name of the mysql service to read/write.
85    ///
86    /// Default to `key` if not specified.
87    pub fn key_field(mut self, key_field: &str) -> Self {
88        if !key_field.is_empty() {
89            self.config.key_field = Some(key_field.to_string());
90        }
91        self
92    }
93
94    /// Set the value field name of the mysql service to read/write.
95    ///
96    /// Default to `value` if not specified.
97    pub fn value_field(mut self, value_field: &str) -> Self {
98        if !value_field.is_empty() {
99            self.config.value_field = Some(value_field.to_string());
100        }
101        self
102    }
103}
104
105impl Builder for MysqlBuilder {
106    type Config = MysqlConfig;
107
108    fn build(self) -> Result<impl Service> {
109        let conn = match self.config.connection_string {
110            Some(v) => v,
111            None => {
112                return Err(
113                    Error::new(ErrorKind::ConfigInvalid, "connection_string is empty")
114                        .with_context("service", MYSQL_SCHEME),
115                );
116            }
117        };
118
119        let config = conn.parse::<MySqlConnectOptions>().map_err(|err| {
120            Error::new(ErrorKind::ConfigInvalid, "connection_string is invalid")
121                .with_context("service", MYSQL_SCHEME)
122                .set_source(err)
123        })?;
124
125        let table = match self.config.table {
126            Some(v) => v,
127            None => {
128                return Err(Error::new(ErrorKind::ConfigInvalid, "table is empty")
129                    .with_context("service", MYSQL_SCHEME));
130            }
131        };
132
133        let key_field = self.config.key_field.unwrap_or_else(|| "key".to_string());
134
135        let value_field = self
136            .config
137            .value_field
138            .unwrap_or_else(|| "value".to_string());
139
140        let root = normalize_root(self.config.root.unwrap_or_else(|| "/".to_string()).as_str());
141
142        Ok(MysqlBackend::new(MysqlCore {
143            pool: OnceCell::new(),
144            config,
145            table,
146            key_field,
147            value_field,
148        })
149        .with_normalized_root(root))
150    }
151}
152
153/// Backend for mysql service
154#[derive(Clone, Debug)]
155pub struct MysqlBackend {
156    pub(crate) core: Arc<MysqlCore>,
157    pub(crate) root: String,
158    pub(crate) info: ServiceInfo,
159    pub(crate) capability: Capability,
160}
161
162impl MysqlBackend {
163    pub fn new(core: MysqlCore) -> Self {
164        let info = ServiceInfo::new(MYSQL_SCHEME, "/", &core.table);
165        let capability = Capability {
166            read: true,
167            list: true,
168            list_with_recursive: true,
169            stat: true,
170            write: true,
171            write_can_empty: true,
172            delete: true,
173            shared: true,
174            ..Default::default()
175        };
176
177        Self {
178            core: Arc::new(core),
179            root: "/".to_string(),
180            info,
181            capability,
182        }
183    }
184
185    fn with_normalized_root(mut self, root: String) -> Self {
186        self.info = self.info.with_root(&root);
187        self.root = root;
188        self
189    }
190}
191
192impl Service for MysqlBackend {
193    type Reader = oio::StreamReader<MysqlReader>;
194    type Writer = MysqlWriter;
195    type Lister = oio::HierarchyLister<MysqlLazyLister>;
196    type Deleter = oio::OneShotDeleter<MysqlDeleter>;
197    type Copier = ();
198
199    fn info(&self) -> ServiceInfo {
200        self.info.clone()
201    }
202
203    fn capability(&self) -> Capability {
204        self.capability
205    }
206
207    async fn create_dir(
208        &self,
209        _ctx: &OperationContext,
210        _path: &str,
211        _args: OpCreateDir,
212    ) -> Result<RpCreateDir> {
213        Err(Error::new(
214            ErrorKind::Unsupported,
215            "operation is not supported",
216        ))
217    }
218
219    async fn stat(&self, _ctx: &OperationContext, path: &str, _: OpStat) -> Result<RpStat> {
220        let p = build_abs_path(&self.root, path);
221
222        if p == build_abs_path(&self.root, "") {
223            Ok(RpStat::new(Metadata::new(EntryMode::DIR)))
224        } else {
225            match self.core.get_length(&p).await? {
226                Some(length) => Ok(RpStat::new(
227                    Metadata::new(EntryMode::FILE).with_content_length(length as u64),
228                )),
229                None => Err(Error::new(ErrorKind::NotFound, "kv not found in mysql")),
230            }
231        }
232    }
233    fn read(&self, _ctx: &OperationContext, path: &str, args: OpRead) -> Result<Self::Reader> {
234        let output: oio::StreamReader<MysqlReader> = {
235            Ok(oio::StreamReader::new(MysqlReader::new(
236                self.clone(),
237                path,
238                args,
239            )))
240        }?;
241
242        Ok(output)
243    }
244
245    fn write(&self, _ctx: &OperationContext, path: &str, _: OpWrite) -> Result<Self::Writer> {
246        let output: MysqlWriter = {
247            let p = build_abs_path(&self.root, path);
248            Ok(MysqlWriter::new(self.core.clone(), p))
249        }?;
250
251        Ok(output)
252    }
253
254    fn delete(&self, _ctx: &OperationContext) -> Result<Self::Deleter> {
255        let output: oio::OneShotDeleter<MysqlDeleter> = {
256            Ok(oio::OneShotDeleter::new(MysqlDeleter::new(
257                self.core.clone(),
258                self.root.clone(),
259            )))
260        }?;
261
262        Ok(output)
263    }
264
265    fn list(&self, _ctx: &OperationContext, path: &str, args: OpList) -> Result<Self::Lister> {
266        let output: oio::HierarchyLister<MysqlLazyLister> = {
267            let lister =
268                MysqlLazyLister::new(self.core.clone(), self.root.clone(), path.to_string());
269            let lister = oio::HierarchyLister::new(lister, path, args.recursive());
270            Ok(lister)
271        }?;
272
273        Ok(output)
274    }
275
276    fn copy(
277        &self,
278        _ctx: &OperationContext,
279        _from: &str,
280        _to: &str,
281        _args: OpCopy,
282        _opts: OpCopier,
283    ) -> Result<Self::Copier> {
284        Err(Error::new(
285            ErrorKind::Unsupported,
286            "operation is not supported",
287        ))
288    }
289
290    async fn rename(
291        &self,
292        _ctx: &OperationContext,
293        _from: &str,
294        _to: &str,
295        _args: OpRename,
296    ) -> Result<RpRename> {
297        Err(Error::new(
298            ErrorKind::Unsupported,
299            "operation is not supported",
300        ))
301    }
302
303    async fn presign(
304        &self,
305        _ctx: &OperationContext,
306        _path: &str,
307        _args: OpPresign,
308    ) -> Result<RpPresign> {
309        Err(Error::new(
310            ErrorKind::Unsupported,
311            "operation is not supported",
312        ))
313    }
314}