Skip to main content

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