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): legacy sequence object sources without pg_sequence
弈秋2c4892893615
diff --git a/crates/dbx-core/src/schema/mod.rs b/crates/dbx-core/src/schema/mod.rsindex 2b153919c8..d35affe55d 100644--- a/crates/dbx-core/src/schema/mod.rs+++ b/crates/dbx-core/src/schema/mod.rs@@ -10131,7 +10131,7 @@ pub fn postgres_object_source_sql(kind: &db::ObjectSourceKind,signature: Option<&str>,) -> String {- postgres_object_source_sql_inner(schema, name, kind, signature, true, false, true, true)+ postgres_object_source_sql_inner(schema, name, kind, signature, true, false, true, PostgresCatalogCaps::default())}fn postgres_trigger_object_source_sql(schema: &str, name: &str, relation_name: Option<&str>) -> String {@@ -10157,9 +10157,9 @@ fn opengauss_object_source_sql(name: &str,kind: &db::ObjectSourceKind,signature: Option<&str>,- has_proc_prokind: bool,+ caps: PostgresCatalogCaps,) -> String {- postgres_object_source_sql_inner(schema, name, kind, signature, true, true, false, has_proc_prokind)+ postgres_object_source_sql_inner(schema, name, kind, signature, true, true, false, caps)}fn opengauss_sequence_object_source_sql(schema: &str, name: &str, include_cache: bool) -> String {@@ -10297,7 +10297,7 @@ fn postgres_object_source_sql_inner(include_relispopulated: bool,unwrap_opengauss_record: bool,isolate_view_search_path: bool,- has_proc_prokind: bool,+ caps: PostgresCatalogCaps,) -> String {match kind {db::ObjectSourceKind::View | db::ObjectSourceKind::MaterializedView => {@@ -10355,7 +10355,7 @@ fn postgres_object_source_sql_inner(// servers (and some Gauss-family kernels) only have proisagg and// proiswindow, so a hardcoded prokind reference fails before the// query even runs (#11161). Probe the catalog and pick the filter.- let kind_filter = if has_proc_prokind {+ let kind_filter = if caps.has_proc_prokind {format!(" AND p.prokind = '{}'", prokind)} else {// Procedures were introduced together with prokind, so on legacy@@ -10378,6 +10378,31 @@ fn postgres_object_source_sql_inner(if unwrap_opengauss_record {return opengauss_sequence_object_source_sql(schema, name, true);}+ // `pg_sequence` (and `CREATE SEQUENCE ... AS`) are PostgreSQL 10+ // additions; legacy servers get the plain pre-10 DDL instead+ // (found while verifying #11161 on a real 9.6 server).+ if !caps.has_pg_sequence {+ return format!(+ "SELECT concat_ws(E'\\n\\n', \+ '-- auto-generated definition' || E'\\n' || \+ 'create sequence ' || quote_ident(c.relname) || ';', \+ 'alter sequence ' || quote_ident(c.relname) || ' owner to ' || quote_ident(pg_get_userbyid(c.relowner)) || ';', \+ CASE WHEN owned.relname IS NOT NULL AND a.attname IS NOT NULL \+ THEN 'alter sequence ' || quote_ident(c.relname) || ' owned by ' || quote_ident(owned.relname) || '.' || quote_ident(a.attname) || ';' \+ END \+ ) \+ FROM pg_catalog.pg_class c \+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \+ LEFT JOIN pg_catalog.pg_depend d \+ ON d.classid = 'pg_class'::regclass AND d.objid = c.oid AND d.deptype = 'a' \+ LEFT JOIN pg_catalog.pg_class owned ON owned.oid = d.refobjid \+ LEFT JOIN pg_catalog.pg_attribute a ON a.attrelid = d.refobjid AND a.attnum = d.refobjsubid \+ WHERE n.nspname = {} AND c.relname = {} AND c.relkind = 'S' \+ ORDER BY c.oid LIMIT 1",+ sql_string(schema),+ sql_string(name)+ );+ }format!("SELECT concat_ws(E'\\n\\n', \'-- auto-generated definition' || E'\\n' || \@@ -11476,26 +11501,48 @@ fn postgres_view_source_uses_isolated_search_path(database_type: Option<&Databasdatabase_type == Some(&DatabaseType::Postgres)}-/// `pg_proc.prokind` exists from PostgreSQL 11 onwards; legacy servers filter-/// routines with `proisagg`/`proiswindow` instead. Probe the catalog so the-/// object-source query matches the server regardless of the locale it reports-/// errors in (#11161 — the old error-message gate missed localized servers).-fn postgres_proc_has_prokind_catalog_sql() -> &'static str {- "SELECT EXISTS ( \+/// Catalog features the routine/sequence object-source queries branch on.+/// Probing the catalog (rather than gating on error messages or versions)+/// keeps the object-source queries correct regardless of the locale the+/// server reports errors in (#11161 — the old error-message gate missed+/// localized servers).+#[derive(Clone, Copy)]+struct PostgresCatalogCaps {+ /// `pg_proc.prokind` exists from PostgreSQL 11 onwards; legacy servers+ /// filter routines with `proisagg`/`proiswindow` instead (#11161).+ has_proc_prokind: bool,+ /// The `pg_sequence` catalog view (and `pg_sequence_last_value`) are also+ /// PostgreSQL 10 additions; the pre-10 sequence DDL must not join them.+ has_pg_sequence: bool,+}++impl Default for PostgresCatalogCaps {+ fn default() -> Self {+ Self { has_proc_prokind: true, has_pg_sequence: true }+ }+}++/// Probe the catalog features once per object-source fetch. A failed probe+/// (permissions, proxies) stays on the modern queries and lets the existing+/// error-triggered fallbacks handle legacy servers.+async fn postgres_object_source_catalog_caps(pool: &deadpool_postgres::Pool) -> PostgresCatalogCaps {+ const PROBE_SQL: &str = "SELECT EXISTS ( \SELECT 1 \FROM pg_catalog.pg_attribute \WHERE attrelid = 'pg_catalog.pg_proc'::regclass \AND attname = 'prokind' \AND NOT attisdropped \- )"-}--async fn postgres_object_source_has_proc_prokind(pool: &deadpool_postgres::Pool) -> bool {- match db::postgres::execute_query(pool, postgres_proc_has_prokind_catalog_sql()).await {- Ok(result) => result.rows.first().and_then(|row| row.first()).and_then(|value| value.as_bool()).unwrap_or(true),- // If even the probe fails (permissions, proxies), stay on the modern- // query and let the existing missing-prokind fallback handle legacy servers.- Err(_) => true,+ ), \+ to_regclass('pg_catalog.pg_sequence') IS NOT NULL";+ match db::postgres::execute_query(pool, PROBE_SQL).await {+ Ok(result) => {+ let values = result.rows.first().cloned().unwrap_or_default();+ PostgresCatalogCaps {+ has_proc_prokind: values.first().and_then(|value| value.as_bool()).unwrap_or(true),+ has_pg_sequence: values.get(1).and_then(|value| value.as_bool()).unwrap_or(true),+ }+ }+ Err(_) => PostgresCatalogCaps::default(),}}@@ -11509,19 +11556,22 @@ async fn postgres_object_source(unwrap_opengauss_record: bool,isolate_view_search_path: bool,) -> Result<String, String> {- let has_proc_prokind = if matches!(object_type, db::ObjectSourceKind::Procedure | db::ObjectSourceKind::Function) {- postgres_object_source_has_proc_prokind(pool).await+ let caps = if matches!(+ object_type,+ db::ObjectSourceKind::Procedure | db::ObjectSourceKind::Function | db::ObjectSourceKind::Sequence+ ) {+ postgres_object_source_catalog_caps(pool).await} else {- true+ PostgresCatalogCaps::default()};let sql = if matches!(object_type, db::ObjectSourceKind::Trigger) {postgres_trigger_object_source_sql(schema, name, relation_name)} else if unwrap_opengauss_record {- opengauss_object_source_sql(schema, name, object_type, signature, has_proc_prokind)+ opengauss_object_source_sql(schema, name, object_type, signature, caps)} else if isolate_view_search_path {- postgres_object_source_sql_inner(schema, name, object_type, signature, true, false, true, has_proc_prokind)+ postgres_object_source_sql_inner(schema, name, object_type, signature, true, false, true, caps)} else {- postgres_object_source_sql_inner(schema, name, object_type, signature, true, false, false, has_proc_prokind)+ postgres_object_source_sql_inner(schema, name, object_type, signature, true, false, false, caps)};match db::postgres::execute_query(pool, &sql).await.and_then(first_string_cell) {Ok(source) => Ok(source),@@ -11537,7 +11587,7 @@ async fn postgres_object_source(false,false,isolate_view_search_path,- has_proc_prokind,+ caps,);db::postgres::execute_query(pool, &fallback_sql).await@@ -11591,7 +11641,7 @@ async fn postgres_object_source(name,object_type,signature,- has_proc_prokind,+ caps.has_proc_prokind,);db::postgres::execute_query(pool, &fallback_sql).await@@ -11788,8 +11838,13 @@ mod object_source_tests {"SELECT pg_get_functiondef(p.oid) FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = 'public' AND p.proname = 'recalc_score' AND p.prokind = 'p' AND pg_get_function_arguments(p.oid) = 'i_id numeric DEFAULT 0, OUT o_code integer' ORDER BY p.oid LIMIT 1");- let opengauss_view_sql =- opengauss_object_source_sql("public", "active_users", &ObjectSourceKind::View, None, true);+ let opengauss_view_sql = opengauss_object_source_sql(+ "public",+ "active_users",+ &ObjectSourceKind::View,+ None,+ PostgresCatalogCaps::default(),+ );assert!(!opengauss_view_sql.contains("set_config('search_path'"));let compatible_view_sql = postgres_object_source_sql_inner(@@ -11800,7 +11855,7 @@ mod object_source_tests {true,false,false,- true,+ PostgresCatalogCaps::default(),);assert!(!compatible_view_sql.contains("set_config('search_path'"));}@@ -11835,7 +11890,7 @@ mod object_source_tests {false,false,true,- true,+ PostgresCatalogCaps::default(),);assert!(sql.contains("CREATE MATERIALIZED VIEW"));@@ -11855,7 +11910,7 @@ mod object_source_tests {true,false,true,- true,+ PostgresCatalogCaps::default(),);assert!(modern.contains("p.prokind = 'f'"));assert!(!modern.contains("proisagg"));@@ -11871,7 +11926,7 @@ mod object_source_tests {true,false,true,- false,+ PostgresCatalogCaps { has_proc_prokind: false, has_pg_sequence: true },);assert!(legacy.contains("NOT p.proisagg AND NOT p.proiswindow"));assert!(!legacy.contains("prokind"));@@ -11884,13 +11939,47 @@ mod object_source_tests {true,false,true,- false,+ PostgresCatalogCaps { has_proc_prokind: false, has_pg_sequence: true },);assert!(legacy_procedure.contains("NOT p.proisagg AND NOT p.proiswindow"));assert!(legacy_procedure.contains("pg_get_function_identity_arguments(p.oid) = 'integer'"));assert!(!legacy_procedure.contains("prokind"));}+ #[test]+ fn postgres_sequence_source_skips_pg_sequence_catalog_on_legacy_servers() {+ let modern = postgres_object_source_sql_inner(+ "public",+ "order_id_seq",+ &ObjectSourceKind::Sequence,+ None,+ true,+ false,+ true,+ PostgresCatalogCaps::default(),+ );+ assert!(modern.contains("JOIN pg_catalog.pg_sequence s ON s.seqrelid = c.oid"));+ assert!(modern.contains("' as ' || pg_catalog.format_type(s.seqtypid, NULL)"));++ // PostgreSQL 9.6 has neither the pg_sequence catalog view nor the+ // CREATE SEQUENCE ... AS syntax (#11161).+ let legacy = postgres_object_source_sql_inner(+ "public",+ "order_id_seq",+ &ObjectSourceKind::Sequence,+ None,+ true,+ false,+ true,+ PostgresCatalogCaps { has_proc_prokind: false, has_pg_sequence: false },+ );+ assert!(!legacy.contains("pg_sequence"));+ assert!(!legacy.contains("seqtypid"));+ assert!(legacy.contains("'create sequence ' || quote_ident(c.relname) || ';'"));+ assert!(legacy.contains("pg_get_userbyid(c.relowner)"));+ assert!(legacy.contains("owned by ' || quote_ident(owned.relname)"));+ }+#[test]fn missing_prokind_gate_matches_localized_undefined_column_errors() {// The exact strings from #11161: PostgreSQL reports undefined-column@@ -11927,7 +12016,7 @@ mod object_source_tests {#[test]fn builds_opengauss_routine_source_sql_from_record_definition() {assert_eq!(- opengauss_object_source_sql("public", "recalc_score", &ObjectSourceKind::Function, None, true),+ opengauss_object_source_sql("public", "recalc_score", &ObjectSourceKind::Function, None, PostgresCatalogCaps::default()),"SELECT (pg_get_functiondef(p.oid)).definition FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = 'public' AND p.proname = 'recalc_score' AND p.prokind = 'f' ORDER BY p.oid LIMIT 1");assert_eq!(@@ -11936,7 +12025,7 @@ mod object_source_tests {"refresh_cache",&ObjectSourceKind::Procedure,Some("integer"),- true,+ PostgresCatalogCaps::default(),),"SELECT (pg_get_functiondef(p.oid)).definition FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = 'public' AND p.proname = 'refresh_cache' AND p.prokind = 'p' AND pg_get_function_identity_arguments(p.oid) = 'integer' ORDER BY p.oid LIMIT 1");@@ -11983,7 +12072,13 @@ mod object_source_tests {#[test]fn builds_opengauss_sequence_source_without_pg_sequence_catalog() {- let sql = opengauss_object_source_sql("public", "order_id_seq", &ObjectSourceKind::Sequence, None, true);+ let sql = opengauss_object_source_sql(+ "public",+ "order_id_seq",+ &ObjectSourceKind::Sequence,+ None,+ PostgresCatalogCaps::default(),+ );assert!(sql.contains("information_schema.sequences"));assert!(sql.contains("s.sequence_schema = n.nspname"));