opendal/services/postgresql/
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::PostgresqlBuilder;
24
25/// Config for PostgreSQL services support.
26#[derive(Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
27#[serde(default)]
28#[non_exhaustive]
29pub struct PostgresqlConfig {
30    /// Root of this backend.
31    ///
32    /// All operations will happen under this root.
33    ///
34    /// Default to `/` if not set.
35    pub root: Option<String>,
36    /// The URL should be with a scheme of either `postgres://` or `postgresql://`.
37    ///
38    /// - `postgresql://user@localhost`
39    /// - `postgresql://user:password@%2Fvar%2Flib%2Fpostgresql/mydb?connect_timeout=10`
40    /// - `postgresql://user@host1:1234,host2,host3:5678?target_session_attrs=read-write`
41    /// - `postgresql:///mydb?user=user&host=/var/lib/postgresql`
42    ///
43    /// For more information, please visit <https://docs.rs/sqlx/latest/sqlx/postgres/struct.PgConnectOptions.html>.
44    pub connection_string: Option<String>,
45    /// the table of postgresql
46    pub table: Option<String>,
47    /// the key field of postgresql
48    pub key_field: Option<String>,
49    /// the value field of postgresql
50    pub value_field: Option<String>,
51}
52
53impl Debug for PostgresqlConfig {
54    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        f.debug_struct("PostgresqlConfig")
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 PostgresqlConfig {
65    type Builder = PostgresqlBuilder;
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!("postgresql://{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        PostgresqlBuilder { 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            "postgresql://db.example.com:5432/kv/cache",
113            Vec::<(String, String)>::new(),
114        )
115        .unwrap();
116
117        let cfg = PostgresqlConfig::from_uri(&uri).unwrap();
118        assert_eq!(
119            cfg.connection_string.as_deref(),
120            Some("postgresql://db.example.com:5432")
121        );
122        assert_eq!(cfg.table.as_deref(), Some("kv"));
123        assert_eq!(cfg.root.as_deref(), Some("cache"));
124    }
125}