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 asyncband::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    type Composer = ();
199
200    fn info(&self) -> ServiceInfo {
201        self.info.clone()
202    }
203
204    fn capability(&self) -> Capability {
205        self.capability
206    }
207
208    async fn create_dir(
209        &self,
210        _ctx: &OperationContext,
211        _path: &str,
212        _args: OpCreateDir,
213    ) -> Result<RpCreateDir> {
214        Err(Error::new(
215            ErrorKind::Unsupported,
216            "operation is not supported",
217        ))
218    }
219
220    async fn stat(&self, _ctx: &OperationContext, path: &str, _: OpStat) -> Result<RpStat> {
221        let p = build_abs_path(&self.root, path);
222
223        if p == build_abs_path(&self.root, "") {
224            Ok(RpStat::new(MetadataBuilder::dir().build()))
225        } else {
226            match self.core.get_length(&p).await? {
227                Some(length) => Ok(RpStat::new({
228                    let metadata = MetadataBuilder::file(length as u64);
229                    metadata.build()
230                })),
231                None => Err(Error::new(ErrorKind::NotFound, "kv not found in mysql")),
232            }
233        }
234    }
235    fn read(&self, _ctx: &OperationContext, path: &str, args: OpRead) -> Result<Self::Reader> {
236        let output: oio::StreamReader<MysqlReader> = {
237            Ok(oio::StreamReader::new(MysqlReader::new(
238                self.clone(),
239                path,
240                args,
241            )))
242        }?;
243
244        Ok(output)
245    }
246
247    fn write(&self, _ctx: &OperationContext, path: &str, _: OpWrite) -> Result<Self::Writer> {
248        let output: MysqlWriter = {
249            let p = build_abs_path(&self.root, path);
250            Ok(MysqlWriter::new(self.core.clone(), p))
251        }?;
252
253        Ok(output)
254    }
255
256    fn delete(&self, _ctx: &OperationContext) -> Result<Self::Deleter> {
257        let output: oio::OneShotDeleter<MysqlDeleter> = {
258            Ok(oio::OneShotDeleter::new(MysqlDeleter::new(
259                self.core.clone(),
260                self.root.clone(),
261            )))
262        }?;
263
264        Ok(output)
265    }
266
267    fn list(&self, _ctx: &OperationContext, path: &str, args: OpList) -> Result<Self::Lister> {
268        let output: oio::HierarchyLister<MysqlLazyLister> = {
269            let lister =
270                MysqlLazyLister::new(self.core.clone(), self.root.clone(), path.to_string());
271            let lister = oio::HierarchyLister::new(lister, path, args.recursive());
272            Ok(lister)
273        }?;
274
275        Ok(output)
276    }
277
278    fn copy(
279        &self,
280        _ctx: &OperationContext,
281        _from: &str,
282        _to: &str,
283        _args: OpCopy,
284    ) -> Result<Self::Copier> {
285        Err(Error::new(
286            ErrorKind::Unsupported,
287            "operation is not supported",
288        ))
289    }
290
291    async fn rename(
292        &self,
293        _ctx: &OperationContext,
294        _from: &str,
295        _to: &str,
296        _args: OpRename,
297    ) -> Result<RpRename> {
298        Err(Error::new(
299            ErrorKind::Unsupported,
300            "operation is not supported",
301        ))
302    }
303
304    async fn presign(
305        &self,
306        _ctx: &OperationContext,
307        _path: &str,
308        _args: OpPresign,
309    ) -> Result<RpPresign> {
310        Err(Error::new(
311            ErrorKind::Unsupported,
312            "operation is not supported",
313        ))
314    }
315}