25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(postgres): quote preserved search path identifiers
lcq928190277a35661
diff --git a/crates/dbx-driver-postgres/src/postgres.rs b/crates/dbx-driver-postgres/src/postgres.rsindex 051b170f63..0f1a9ec595 100644--- a/crates/dbx-driver-postgres/src/postgres.rs+++ b/crates/dbx-driver-postgres/src/postgres.rs@@ -8555,6 +8555,42 @@ fn is_postgres_user_placeholder(element: &str) -> bool {matches!(element, "$user" | "\"$user\"")}+fn postgres_quoted_search_path_elements(configured: &str) -> Vec<String> {+ let mut elements = Vec::new();+ // Match PostgreSQL's scanner_isspace; Unicode whitespace can be name data.+ let is_space = |ch| matches!(ch, ' ' | '\t' | '\n' | '\r' | '\u{b}' | '\u{c}');+ let mut remaining = configured.trim_matches(is_space);+ // The server has already validated this GUC list. Its unquoted names can+ // contain punctuation that SQL identifiers require us to quote.+ while !remaining.is_empty() {+ let quoted = remaining.starts_with('"');+ let mut end = remaining.len();+ if quoted {+ let mut chars = remaining.char_indices().skip(1).peekable();+ while let Some((index, ch)) = chars.next() {+ if ch == '"' {+ if chars.peek().is_some_and(|(_, next)| *next == '"') {+ chars.next();+ } else {+ end = index + 1;+ break;+ }+ }+ }+ } else if let Some(index) = remaining.find(',') {+ end = index;+ }+ let (element, rest) = remaining.split_at(end);+ elements.push(if quoted {+ element.to_string()+ } else {+ pg_quote_ident(&element.trim_matches(is_space).to_ascii_lowercase())+ });+ remaining = rest.trim_start_matches(is_space).strip_prefix(',').unwrap_or("").trim_start_matches(is_space);+ }+ elements+}+fn postgres_set_preserved_search_path_sql(schema: &str,context: PostgresSearchPathContext,@@ -8568,7 +8604,6 @@ fn postgres_set_preserved_search_path_sql(} else {""};- let configured = baseline.configured.trim();// Redshift rejects the "$user" placeholder inside `SET search_path` even// though `current_setting('search_path')` reports it, so any preserved-path// statement containing the element fails with a syntax error. Drop the@@ -8576,25 +8611,20 @@ fn postgres_set_preserved_search_path_sql(// also mangle ordinary identifiers containing that substring); keeping the// placeholder is pointless while switching schemas anyway because the// selected schema is already prepended first.- let configured_elements: Vec<&str> = configured.split(',').map(str::trim).collect();+ let configured_elements = postgres_quoted_search_path_elements(&baseline.configured);let drops_user_placeholder = configured_elements.iter().any(|element| is_postgres_user_placeholder(element));- let configured = if drops_user_placeholder {- configured_elements- .iter()- .filter(|element| !is_postgres_user_placeholder(element))- .copied()- .collect::<Vec<_>>()- .join(", ")- } else {- configured.to_string()- };+ let configured = configured_elements+ .iter()+ .filter(|element| !is_postgres_user_placeholder(element))+ .map(String::as_str)+ .collect::<Vec<_>>()+ .join(", ");let selected_schema = pg_quote_ident(schema);// The first resolved schema can come from "$user". Once that placeholder is// removed for compatible servers, the selected schema must replace it unless// the configured path also contains that schema explicitly.- let selected_schema_is_explicit = configured_elements- .iter()- .any(|element| !is_postgres_user_placeholder(element) && (*element == schema || *element == selected_schema));+ let selected_schema_is_explicit =+ configured_elements.iter().any(|element| !is_postgres_user_placeholder(element) && *element == selected_schema);let selected_schema_was_removed = drops_user_placeholder&& baseline.first_resolved_schema.as_deref() == Some(schema)&& !selected_schema_is_explicit;@@ -12221,10 +12251,68 @@ mod tests {};assert_eq!(postgres_set_preserved_search_path_sql("application", PostgresSearchPathContext::Query, &baseline),- "SET search_path TO application, extensions, public, pg_catalog"+ "SET search_path TO \"application\", \"extensions\", \"public\", pg_catalog");}+ #[test]+ fn postgres_search_path_quotes_preserved_identifiers() {+ for (configured, first_schema, selected_schema, expected_path) in [+ (+ "certification-lvpeng3, public",+ "certification-lvpeng3",+ "certification-lvpeng3",+ r#""certification-lvpeng3", "public", pg_catalog"#,+ ),+ (+ "certification-lvpeng3, public",+ "certification-lvpeng3",+ "other-schema",+ r#""other-schema", "certification-lvpeng3", "public", pg_catalog"#,+ ),+ (+ r#""tenant,alpha", "$user", public"#,+ "tenant,alpha",+ "tenant,alpha",+ r#""tenant,alpha", "public", pg_catalog"#,+ ),+ (r#""a""b", public"#, "a\"b", "a\"b", r#""a""b", "public", pg_catalog"#),+ (r#"foo"bar, public"#, "foo\"bar", "foo\"bar", r#""foo""bar", "public", pg_catalog"#),+ ("MiXeD-Name, public", "mixed-name", "mixed-name", r#""mixed-name", "public", pg_catalog"#),+ (r#""MiXeD Name", public"#, "MiXeD Name", "MiXeD Name", r#""MiXeD Name", "public", pg_catalog"#),+ ("select, public", "select", "select", r#""select", "public", pg_catalog"#),+ ("APPLICATION, $user, public", "application", "application", r#""application", "public", pg_catalog"#),+ ("$USER, public", "public", "application", r#""application", "public", pg_catalog"#),+ (r#""$USER", public"#, "$USER", "$USER", r#""$USER", "public", pg_catalog"#),+ ("\u{2003}tenant,public", "\u{2003}tenant", "\u{2003}tenant", "\"\u{2003}tenant\", \"public\", pg_catalog"),+ ("tenant\u{2003},public", "tenant\u{2003}", "tenant\u{2003}", "\"tenant\u{2003}\", \"public\", pg_catalog"),+ (+ "\u{b}application\u{b},\u{c}public\u{c}",+ "application",+ "application",+ r#""application", "public", pg_catalog"#,+ ),+ ] {+ let baseline = PostgresSearchPathBaseline {+ configured: configured.to_string(),+ first_resolved_schema: Some(first_schema.to_string()),+ has_explicit_pg_catalog: false,+ };+ for (context, scope) in [+ (PostgresSearchPathContext::Query, ""),+ (PostgresSearchPathContext::Transaction, ""),+ (PostgresSearchPathContext::LocalTransaction, " LOCAL"),+ (PostgresSearchPathContext::LocalQueryTransaction, " LOCAL"),+ ] {+ assert_eq!(+ postgres_set_preserved_search_path_sql(selected_schema, context, &baseline),+ format!("SET{scope} search_path TO {expected_path}"),+ "configured={configured:?}, selected={selected_schema:?}, context={context:?}"+ );+ }+ }+ }+#[test]fn postgres_search_path_prepends_selected_schema_without_dropping_configured_items() {let baseline = PostgresSearchPathBaseline {@@ -12234,7 +12322,7 @@ mod tests {};assert_eq!(postgres_set_preserved_search_path_sql("application", PostgresSearchPathContext::Query, &baseline),- "SET search_path TO \"application\", extensions, public, pg_catalog"+ "SET search_path TO \"application\", \"extensions\", \"public\", pg_catalog");assert_eq!(postgres_set_preserved_search_path_sql(@@ -12242,7 +12330,7 @@ mod tests {PostgresSearchPathContext::LocalQueryTransaction,&baseline,),- "SET LOCAL search_path TO \"application\", extensions, public, pg_catalog"+ "SET LOCAL search_path TO \"application\", \"extensions\", \"public\", pg_catalog");}@@ -12255,7 +12343,7 @@ mod tests {};assert_eq!(postgres_set_preserved_search_path_sql("dwd_views", PostgresSearchPathContext::Query, &baseline),- "SET search_path TO \"dwd_views\", public, pg_catalog"+ "SET search_path TO \"dwd_views\", \"public\", pg_catalog");let bare_baseline = PostgresSearchPathBaseline {@@ -12265,7 +12353,7 @@ mod tests {};assert_eq!(postgres_set_preserved_search_path_sql("dwd_views", PostgresSearchPathContext::Query, &bare_baseline),- "SET search_path TO \"dwd_views\", public, pg_catalog"+ "SET search_path TO \"dwd_views\", \"public\", pg_catalog");}@@ -12279,7 +12367,7 @@ mod tests {assert_eq!(postgres_set_preserved_search_path_sql("dbx_test", PostgresSearchPathContext::Query, &baseline),- "SET search_path TO \"dbx_test\", public, pg_catalog"+ "SET search_path TO \"dbx_test\", \"public\", pg_catalog");let explicit_baseline = PostgresSearchPathBaseline {@@ -12289,7 +12377,7 @@ mod tests {};assert_eq!(postgres_set_preserved_search_path_sql("dbx_test", PostgresSearchPathContext::Query, &explicit_baseline),- "SET search_path TO dbx_test, public, pg_catalog"+ "SET search_path TO \"dbx_test\", \"public\", pg_catalog");}@@ -12346,7 +12434,7 @@ mod tests {};assert_eq!(postgres_set_preserved_search_path_sql("dwd_views", PostgresSearchPathContext::Query, &baseline),- "SET search_path TO \"dwd_views\", my$user_schema, \"$user_backup\", public, pg_catalog"+ "SET search_path TO \"dwd_views\", \"my$user_schema\", \"$user_backup\", \"public\", pg_catalog");}@@ -12359,7 +12447,7 @@ mod tests {};assert_eq!(postgres_set_preserved_search_path_sql("application", PostgresSearchPathContext::Query, &baseline),- "SET search_path TO \"application\", extensions, pg_catalog, public"+ "SET search_path TO \"application\", \"extensions\", \"pg_catalog\", \"public\"");}diff --git a/crates/dbx-driver-postgres/tests/search_path_identifiers.rs b/crates/dbx-driver-postgres/tests/search_path_identifiers.rsnew file mode 100644index 0000000000..860781a58c--- /dev/null+++ b/crates/dbx-driver-postgres/tests/search_path_identifiers.rs@@ -0,0 +1,158 @@+use dbx_driver_postgres::{+ connect_with_max_connections, execute_query_with_schema, set_postgres_search_path, PostgresSearchPathContext,+};+use deadpool_postgres::Pool;+use percent_encoding::{percent_decode_str, utf8_percent_encode, NON_ALPHANUMERIC};+use std::time::Duration;++fn search_path_url(url: &str, search_path: &str) -> String {+ let (base, fragment) = url.split_once('#').map_or((url, None), |(base, fragment)| (base, Some(fragment)));+ let (prefix, query) = base.split_once('?').map_or((base, None), |(prefix, query)| (prefix, Some(query)));+ let mut params = Vec::new();+ let mut options = String::new();+ for param in query.into_iter().flat_map(|query| query.split('&')).filter(|param| !param.is_empty()) {+ let (key, value) = param.split_once('=').unwrap_or((param, ""));+ if percent_decode_str(key).decode_utf8_lossy() == "options" {+ options = percent_decode_str(value).decode_utf8_lossy().into_owned();+ } else {+ params.push(param.to_string());+ }+ }+ options.push_str(&format!(" -csearch_path={search_path}"));+ params.push(format!("options={}", utf8_percent_encode(options.trim(), NON_ALPHANUMERIC)));+ let mut url = format!("{prefix}?{}", params.join("&"));+ if let Some(fragment) = fragment {+ url.push('#');+ url.push_str(fragment);+ }+ url+}++async fn check_baseline(pool: &Pool, configured: &str, backend_pid: i32) -> Result<(), String> {+ let client = pool.get().await.map_err(|error| error.to_string())?;+ let row = client+ .query_one("SELECT current_setting('search_path'), pg_backend_pid()", &[])+ .await+ .map_err(|error| error.to_string())?;+ let actual: String = row.get(0);+ if actual != configured || row.get::<_, i32>(1) != backend_pid {+ return Err(format!("connection reuse must restore startup search_path {configured:?}; got {actual:?}"));+ }+ Ok(())+}++#[tokio::test]+#[ignore = "requires DBX_TEST_POSTGRES_URL pointing at a writable disposable PostgreSQL database"]+async fn postgres_search_path_identifiers_support_queries_comments_and_connection_reuse() {+ let url = std::env::var("DBX_TEST_POSTGRES_URL").expect("DBX_TEST_POSTGRES_URL");+ let timeout = Duration::from_secs(10);+ let admin_pool = connect_with_max_connections(&url, timeout, 1).await.expect("connect fixture database");+ let admin = admin_pool.get().await.expect("checkout fixture connection");+ let suffix = uuid::Uuid::new_v4().simple();+ let selected = format!("dbx-issue-13150-{suffix}");+ let other = format!("dbx_other_{suffix}");+ let comma = format!("dbx,search\"{suffix}");+ let comma_ident = comma.replace('"', "\"\"");+ let unicode = format!("\u{2003}dbx_unicode_{suffix}\u{2003}");+ // Startup GUC values accept a bare hyphenated name, even though replaying+ // that same value verbatim in a SET statement is invalid SQL.+ let baselines = [+ format!("{selected},public"),+ format!("{selected},\"{comma_ident}\",\"$user\",public"),+ format!("{selected},{unicode},public"),+ ];+ let result: Result<(), String> = async {+ admin+ .batch_execute(&format!(+ "CREATE SCHEMA \"{selected}\"; CREATE SCHEMA \"{other}\"; CREATE SCHEMA \"{comma_ident}\"; \+ CREATE SCHEMA \"{unicode}\";"+ ))+ .await+ .map_err(|error| error.to_string())?;+ for (index, configured) in baselines.iter().enumerate() {+ let pool = connect_with_max_connections(&search_path_url(&url, configured), timeout, 1).await?;+ let client = pool.get().await.map_err(|error| error.to_string())?;+ let backend_pid: i32 =+ client.query_one("SELECT pg_backend_pid()", &[]).await.map_err(|e| e.to_string())?.get(0);+ drop(client);+ check_baseline(&pool, configured, backend_pid).await?;++ for schema in [&selected, &other] {+ let preserved = match index {+ 0 => &selected,+ 1 => &comma,+ _ => &unicode,+ };+ let rows = execute_query_with_schema(+ &pool,+ schema,+ &format!(+ "SELECT now() IS NOT NULL, current_schema()::text, '{preserved}' = ANY(current_schemas(false))"+ ),+ )+ .await?;+ if rows.rows != vec![vec![serde_json::json!(true), serde_json::json!(schema), serde_json::json!(true)]]+ {+ return Err(format!("unexpected query result for schema {schema:?}: {:?}", rows.rows));+ }+ check_baseline(&pool, configured, backend_pid).await?;++ execute_query_with_schema(+ &pool,+ schema,+ &format!("COMMENT ON SCHEMA \"{selected}\" IS 'issue 13148 regression'"),+ )+ .await?;+ let comment: Option<String> = admin+ .query_one(+ "SELECT obj_description(oid, 'pg_namespace') FROM pg_namespace WHERE nspname = $1",+ &[&selected],+ )+ .await+ .map_err(|error| error.to_string())?+ .get(0);+ if comment.as_deref() != Some("issue 13148 regression") {+ return Err(format!("schema comment was not saved: {comment:?}"));+ }+ check_baseline(&pool, configured, backend_pid).await?;+ }++ if execute_query_with_schema(&pool, &other, "SELECT dbx_missing_search_path_regression()").await.is_ok() {+ return Err("the deliberately invalid query unexpectedly succeeded".to_string());+ }+ check_baseline(&pool, configured, backend_pid).await?;++ let client = pool.get().await.map_err(|error| error.to_string())?;+ client.batch_execute("BEGIN").await.map_err(|error| error.to_string())?;+ let local_result: Result<(), String> = async {+ set_postgres_search_path(&client, &other, PostgresSearchPathContext::LocalTransaction, timeout).await?;+ let actual: String = client+ .query_one("SELECT current_schema()::text", &[])+ .await+ .map_err(|error| error.to_string())?+ .get(0);+ if actual != other {+ return Err(format!("SET LOCAL selected {actual:?} instead of {other:?}"));+ }+ Ok(())+ }+ .await;+ let rollback = client.batch_execute("ROLLBACK").await.map_err(|error| error.to_string());+ drop(client);+ local_result?;+ rollback?;+ check_baseline(&pool, configured, backend_pid).await?;+ }+ Ok(())+ }+ .await;+ // Collect errors before asserting so fixtures are removed on regressions.+ let cleanup = admin+ .batch_execute(&format!(+ "DROP SCHEMA IF EXISTS \"{selected}\" CASCADE; DROP SCHEMA IF EXISTS \"{other}\" CASCADE; \+ DROP SCHEMA IF EXISTS \"{comma_ident}\" CASCADE; DROP SCHEMA IF EXISTS \"{unicode}\" CASCADE;"+ ))+ .await;+ assert!(cleanup.is_ok(), "fixture cleanup failed: {cleanup:?}");+ assert!(result.is_ok(), "search_path regression: {result:?}");+}