This is an automated email from the ASF dual-hosted git repository.

Xuanwo pushed a commit to branch xuanwo/fix-postgresql-uri-and-config-validation
in repository https://gitbox.apache.org/repos/asf/opendal.git

commit 103ef9cffec271a7234a47849b2f4f431761c06f
Author: Xuanwo <[email protected]>
AuthorDate: Tue Nov 24 02:01:49 2026 +0100

    fix(services/postgresql): preserve URI credentials, respect explicit root, 
and validate config
---
 core/services/postgresql/src/backend.rs | 137 ++++++++++++++++++++++++++++-
 core/services/postgresql/src/config.rs  | 149 +++++++++++++++++++++++++++++++-
 2 files changed, 282 insertions(+), 4 deletions(-)

diff --git a/core/services/postgresql/src/backend.rs 
b/core/services/postgresql/src/backend.rs
index cdaa5f72fe..18b650f21a 100644
--- a/core/services/postgresql/src/backend.rs
+++ b/core/services/postgresql/src/backend.rs
@@ -95,13 +95,30 @@ impl PostgresqlBuilder {
     }
 }
 
+fn validate_identifier(name: &str, value: &str) -> Result<()> {
+    if value.is_empty() {
+        return Err(
+            Error::new(ErrorKind::ConfigInvalid, format!("{name} is empty"))
+                .with_context("service", POSTGRESQL_SCHEME),
+        );
+    }
+    if value.contains('\0') {
+        return Err(Error::new(
+            ErrorKind::ConfigInvalid,
+            format!("{name} must not contain NUL bytes"),
+        )
+        .with_context("service", POSTGRESQL_SCHEME));
+    }
+    Ok(())
+}
+
 impl Builder for PostgresqlBuilder {
     type Config = PostgresqlConfig;
 
     fn build(self) -> Result<impl Service> {
         let conn = match self.config.connection_string {
-            Some(v) => v,
-            None => {
+            Some(v) if !v.trim().is_empty() => v,
+            _ => {
                 return Err(
                     Error::new(ErrorKind::ConfigInvalid, "connection_string is 
empty")
                         .with_context("service", POSTGRESQL_SCHEME),
@@ -122,13 +139,16 @@ impl Builder for PostgresqlBuilder {
                     .with_context("service", POSTGRESQL_SCHEME));
             }
         };
+        validate_identifier("table", &table)?;
 
         let key_field = self.config.key_field.unwrap_or_else(|| 
"key".to_string());
+        validate_identifier("key_field", &key_field)?;
 
         let value_field = self
             .config
             .value_field
             .unwrap_or_else(|| "value".to_string());
+        validate_identifier("value_field", &value_field)?;
 
         let root = normalize_root(self.config.root.unwrap_or_else(|| 
"/".to_string()).as_str());
 
@@ -305,3 +325,116 @@ impl Service for PostgresqlBackend {
         ))
     }
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    fn valid_config() -> PostgresqlConfig {
+        PostgresqlConfig {
+            connection_string: 
Some("postgresql://user:[email protected]:5432/testdb".to_string()),
+            table: Some("data".to_string()),
+            ..Default::default()
+        }
+    }
+
+    #[test]
+    fn build_rejects_empty_and_whitespace_connection_string() {
+        for config in [
+            PostgresqlConfig {
+                connection_string: None,
+                ..valid_config()
+            },
+            PostgresqlConfig {
+                connection_string: Some(String::new()),
+                ..valid_config()
+            },
+            PostgresqlConfig {
+                connection_string: Some("   \t\n ".to_string()),
+                ..valid_config()
+            },
+        ] {
+            let err = config.into_builder().build().unwrap_err();
+            assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
+        }
+
+        for builder in [
+            PostgresqlBuilder::default()
+                .connection_string("")
+                .table("data"),
+            PostgresqlBuilder::default()
+                .connection_string("   ")
+                .table("data"),
+        ] {
+            let err = builder.build().unwrap_err();
+            assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
+        }
+    }
+
+    #[test]
+    fn build_rejects_empty_and_nul_identifiers() {
+        for config in [
+            PostgresqlConfig {
+                table: None,
+                ..valid_config()
+            },
+            PostgresqlConfig {
+                table: Some(String::new()),
+                ..valid_config()
+            },
+            PostgresqlConfig {
+                key_field: Some(String::new()),
+                ..valid_config()
+            },
+            PostgresqlConfig {
+                value_field: Some(String::new()),
+                ..valid_config()
+            },
+            PostgresqlConfig {
+                table: Some("data\0bad".to_string()),
+                ..valid_config()
+            },
+            PostgresqlConfig {
+                key_field: Some("key\0bad".to_string()),
+                ..valid_config()
+            },
+            PostgresqlConfig {
+                value_field: Some("val\0bad".to_string()),
+                ..valid_config()
+            },
+        ] {
+            let err = config.into_builder().build().unwrap_err();
+            assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
+        }
+
+        for builder in [
+            PostgresqlBuilder::default()
+                
.connection_string("postgresql://user:[email protected]:5432/testdb")
+                .table(""),
+            PostgresqlBuilder::default()
+                
.connection_string("postgresql://user:[email protected]:5432/testdb")
+                .table("data\0bad"),
+            PostgresqlBuilder::default()
+                
.connection_string("postgresql://user:[email protected]:5432/testdb")
+                .table("data")
+                .key_field("key\0bad"),
+            PostgresqlBuilder::default()
+                
.connection_string("postgresql://user:[email protected]:5432/testdb")
+                .table("data")
+                .value_field("val\0bad"),
+        ] {
+            let err = builder.build().unwrap_err();
+            assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
+        }
+    }
+
+    #[test]
+    fn build_preserves_unquoted_table_name_in_service_info() {
+        let config = PostgresqlConfig {
+            table: Some("my\"table".to_string()),
+            ..valid_config()
+        };
+        let service = config.into_builder().build().unwrap();
+        assert_eq!(service.info().name().as_ref(), "my\"table");
+    }
+}
diff --git a/core/services/postgresql/src/config.rs 
b/core/services/postgresql/src/config.rs
index d9e5072af6..1ce6c61d1a 100644
--- a/core/services/postgresql/src/config.rs
+++ b/core/services/postgresql/src/config.rs
@@ -23,6 +23,14 @@ use serde::Serialize;
 use super::backend::PostgresqlBuilder;
 
 /// Config for PostgreSQL services support.
+///
+/// When built from an [`opendal_core::OperatorUri`] 
(`postgresql://[user[:password]@]host[:port]/table[/root]`),
+/// OpenDAL synthesizes `connection_string` from the URI authority and 
percent-encoded
+/// credentials without a database path segment, while the URI path maps to 
`table` and
+/// optional `root`. Explicit `connection_string`, `table`, and `root` options 
take precedence
+/// over values derived from the URI. Without a database path in 
`connection_string`,
+/// PostgreSQL connects to `PGDATABASE` if set or to the database matching the 
connecting
+/// username; provide an explicit `connection_string` option to select a 
different database.
 #[derive(Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
 #[serde(default)]
 #[non_exhaustive]
@@ -61,6 +69,40 @@ impl Debug for PostgresqlConfig {
     }
 }
 
+fn percent_encode_userinfo(input: &str) -> String {
+    use std::fmt::Write;
+
+    let mut encoded = String::with_capacity(input.len());
+    for byte in input.bytes() {
+        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | 
b'~') {
+            encoded.push(byte as char);
+        } else {
+            let _ = write!(encoded, "%{byte:02X}");
+        }
+    }
+    encoded
+}
+
+fn format_connection_string(
+    authority: &str,
+    username: Option<&str>,
+    password: Option<&str>,
+) -> String {
+    match (username, password) {
+        (Some(user), Some(pass)) => format!(
+            "postgresql://{}:{}@{authority}",
+            percent_encode_userinfo(user),
+            percent_encode_userinfo(pass)
+        ),
+        (Some(user), None) => format!("postgresql://{}@{authority}", 
percent_encode_userinfo(user)),
+        (None, Some(pass)) => format!(
+            "postgresql://:{}@{authority}",
+            percent_encode_userinfo(pass)
+        ),
+        (None, None) => format!("postgresql://{authority}"),
+    }
+}
+
 impl opendal_core::Configurator for PostgresqlConfig {
     type Builder = PostgresqlBuilder;
 
@@ -69,7 +111,9 @@ impl opendal_core::Configurator for PostgresqlConfig {
 
         if let Some(authority) = uri.authority() {
             map.entry("connection_string".to_string())
-                .or_insert_with(|| format!("postgresql://{authority}"));
+                .or_insert_with(|| {
+                    format_connection_string(authority, uri.username(), 
uri.password())
+                });
         }
 
         if let Some(path) = uri.root()
@@ -88,7 +132,8 @@ impl opendal_core::Configurator for PostgresqlConfig {
             if let Some(root) = rest
                 && !root.is_empty()
             {
-                map.insert("root".to_string(), root.to_string());
+                map.entry("root".to_string())
+                    .or_insert_with(|| root.to_string());
             }
         }
 
@@ -103,8 +148,10 @@ impl opendal_core::Configurator for PostgresqlConfig {
 #[cfg(test)]
 mod tests {
     use super::*;
+    use opendal_core::Builder;
     use opendal_core::Configurator;
     use opendal_core::OperatorUri;
+    use sqlx::postgres::PgConnectOptions;
 
     #[test]
     fn from_uri_sets_connection_string_table_and_root() {
@@ -122,4 +169,102 @@ mod tests {
         assert_eq!(cfg.table.as_deref(), Some("kv"));
         assert_eq!(cfg.root.as_deref(), Some("cache"));
     }
+
+    #[test]
+    fn from_uri_preserves_credentials_and_builds() {
+        let uri = OperatorUri::new(
+            
"postgresql://alice%40corp.com:p%3aa%2fs%25s%[email protected]:5432/kv/cache",
+            Vec::<(String, String)>::new(),
+        )
+        .unwrap();
+
+        let cfg = PostgresqlConfig::from_uri(&uri).unwrap();
+        assert_eq!(
+            cfg.connection_string.as_deref(),
+            
Some("postgresql://alice%40corp.com:p%3aa%2fs%25s%[email protected]:5432")
+        );
+        assert_eq!(cfg.table.as_deref(), Some("kv"));
+        assert_eq!(cfg.root.as_deref(), Some("cache"));
+        let opts: PgConnectOptions = 
cfg.connection_string.as_deref().unwrap().parse().unwrap();
+        assert_eq!(opts.get_username(), "[email protected]");
+        cfg.into_builder().build().unwrap();
+
+        let user_only = OperatorUri::new(
+            "postgresql://postgres@[::1]:5432/kv",
+            Vec::<(String, String)>::new(),
+        )
+        .unwrap();
+        let cfg = PostgresqlConfig::from_uri(&user_only).unwrap();
+        assert_eq!(
+            cfg.connection_string.as_deref(),
+            Some("postgresql://postgres@[::1]:5432")
+        );
+        assert_eq!(cfg.table.as_deref(), Some("kv"));
+        assert_eq!(cfg.root, None);
+        cfg.into_builder().build().unwrap();
+
+        let pass_only = OperatorUri::new(
+            "postgresql://:p%3ass%[email protected]:5432/kv",
+            Vec::<(String, String)>::new(),
+        )
+        .unwrap();
+        let cfg = PostgresqlConfig::from_uri(&pass_only).unwrap();
+        assert_eq!(
+            cfg.connection_string.as_deref(),
+            Some("postgresql://:p%3ass%[email protected]:5432")
+        );
+        cfg.into_builder().build().unwrap();
+    }
+
+    #[test]
+    fn from_uri_respects_explicit_root_table_and_connection_string_options() {
+        let uri = OperatorUri::new(
+            "postgresql://user:[email protected]:5432/kv/path?root=override",
+            Vec::<(String, String)>::new(),
+        )
+        .unwrap();
+        let cfg = PostgresqlConfig::from_uri(&uri).unwrap();
+        assert_eq!(
+            cfg.connection_string.as_deref(),
+            Some("postgresql://user:[email protected]:5432")
+        );
+        assert_eq!(cfg.table.as_deref(), Some("kv"));
+        assert_eq!(cfg.root.as_deref(), Some("override"));
+
+        let explicit_table = OperatorUri::new(
+            
"postgresql://user:[email protected]:5432/kv/path?table=custom_table",
+            Vec::<(String, String)>::new(),
+        )
+        .unwrap();
+        let cfg = PostgresqlConfig::from_uri(&explicit_table).unwrap();
+        assert_eq!(cfg.table.as_deref(), Some("custom_table"));
+        assert_eq!(cfg.root.as_deref(), Some("path"));
+
+        let explicit_conn = OperatorUri::new(
+            "postgresql://user:[email protected]:5432/kv/path",
+            [(
+                "connection_string".to_string(),
+                "postgresql://other:[email protected]:5432/testdb".to_string(),
+            )],
+        )
+        .unwrap();
+        let cfg = PostgresqlConfig::from_uri(&explicit_conn).unwrap();
+        assert_eq!(
+            cfg.connection_string.as_deref(),
+            Some("postgresql://other:[email protected]:5432/testdb")
+        );
+        assert_eq!(cfg.table.as_deref(), Some("kv"));
+        assert_eq!(cfg.root.as_deref(), Some("path"));
+
+        let query_conn = OperatorUri::new(
+            
"postgresql://user:[email protected]:5432/kv/path?connection_string=postgresql%3A%2F%2Fother%3Apw%40127.0.0.1%3A5432%2Ftestdb",
+            Vec::<(String, String)>::new(),
+        )
+        .unwrap();
+        let cfg = PostgresqlConfig::from_uri(&query_conn).unwrap();
+        assert_eq!(
+            cfg.connection_string.as_deref(),
+            Some("postgresql://other:[email protected]:5432/testdb")
+        );
+    }
 }

Reply via email to