opendal/services/postgresql/
config.rs1use std::fmt::Debug;
19
20use serde::Deserialize;
21use serde::Serialize;
22
23use super::backend::PostgresqlBuilder;
24
25#[derive(Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
27#[serde(default)]
28#[non_exhaustive]
29pub struct PostgresqlConfig {
30 pub root: Option<String>,
36 pub connection_string: Option<String>,
45 pub table: Option<String>,
47 pub key_field: Option<String>,
49 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}