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): sync traditional INHERITS parents in table structure transfer
Tara488504f63653
diff --git a/crates/dbx-core/src/schema/mod.rs b/crates/dbx-core/src/schema/mod.rsindex d35affe55d..6cfc5d6f93 100644--- a/crates/dbx-core/src/schema/mod.rs+++ b/crates/dbx-core/src/schema/mod.rs@@ -13423,6 +13423,122 @@ mod ddl_tests {assert!(!ddl.contains("CREATE TABLE \"public\".\"events_remote\""), "ddl: {ddl}");}+ #[test]+ fn postgres_table_ddl_emits_inherits_for_traditional_child() {+ // A traditional-inheritance child is neither a declarative partition+ // nor a foreign table: it renders as a plain `CREATE TABLE` with an+ // `INHERITS (parent...)` clause so the dependency survives a structure+ // transfer (issue #10803).+ let columns = vec![column("id", "integer"), column("name", "text")];+ let partition_info = db::postgres::PostgresTablePartitionInfo {+ inherits_parents: vec![db::postgres::PostgresInheritsParent {+ schema: "public".to_string(),+ table: "person".to_string(),+ }],+ ..Default::default()+ };+ let ddl = render_postgres_table_ddl_with_partition_info(+ "public",+ "employee",+ &columns,+ &[],+ &[],+ &[],+ None,+ &partition_info,+ &db::postgres::PostgresTablePartitionLocalObjects::default(),+ );+ assert!(ddl.contains("CREATE TABLE \"public\".\"employee\""), "ddl: {ddl}");+ assert!(ddl.contains(" INHERITS (\"public\".\"person\")"), "ddl: {ddl}");+ assert!(!ddl.contains("PARTITION OF"), "ddl: {ddl}");+ assert!(!ddl.contains("PARTITION BY"), "ddl: {ddl}");+ // The clause sits between the column list and the closing semicolon.+ let head = ddl.find("CREATE TABLE").unwrap();+ let inherits = ddl.find("INHERITS").unwrap();+ let semi = ddl.rfind(';').unwrap();+ assert!(head < inherits && inherits < semi, "INHERITS must follow columns and precede ';': {ddl}");+ }++ #[test]+ fn postgres_table_ddl_emits_inherits_with_multiple_parents() {+ let columns = vec![column("id", "integer")];+ let partition_info = db::postgres::PostgresTablePartitionInfo {+ inherits_parents: vec![+ db::postgres::PostgresInheritsParent { schema: "public".to_string(), table: "p1".to_string() },+ db::postgres::PostgresInheritsParent { schema: "public".to_string(), table: "p2".to_string() },+ ],+ ..Default::default()+ };+ let ddl = render_postgres_table_ddl_with_partition_info(+ "public",+ "child",+ &columns,+ &[],+ &[],+ &[],+ None,+ &partition_info,+ &db::postgres::PostgresTablePartitionLocalObjects::default(),+ );+ assert!(ddl.contains(" INHERITS (\"public\".\"p1\", \"public\".\"p2\")"), "ddl: {ddl}");+ }++ #[test]+ fn postgres_table_ddl_emits_inherits_with_cross_schema_parent() {+ // Cross-schema ancestry: the parent lives in a different schema, so+ // the `INHERITS` clause must schema-qualify it (issue #10803).+ let columns = vec![column("id", "integer")];+ let partition_info = db::postgres::PostgresTablePartitionInfo {+ inherits_parents: vec![db::postgres::PostgresInheritsParent {+ schema: "archive".to_string(),+ table: "person".to_string(),+ }],+ ..Default::default()+ };+ let ddl = render_postgres_table_ddl_with_partition_info(+ "public",+ "employee",+ &columns,+ &[],+ &[],+ &[],+ None,+ &partition_info,+ &db::postgres::PostgresTablePartitionLocalObjects::default(),+ );+ assert!(ddl.contains(" INHERITS (\"archive\".\"person\")"), "ddl: {ddl}");+ assert!(ddl.contains("CREATE TABLE \"public\".\"employee\""), "ddl: {ddl}");+ }++ #[test]+ fn postgres_table_ddl_skips_inherits_for_foreign_table() {+ // A foreign table never takes `INHERITS` (PostgreSQL rejects it); even+ // if inherits_parents were populated, the clause is suppressed.+ let columns = vec![column("id", "integer")];+ let partition_info = db::postgres::PostgresTablePartitionInfo {+ is_foreign: true,+ foreign_server: Some("loopback".to_string()),+ inherits_parents: vec![db::postgres::PostgresInheritsParent {+ schema: "public".to_string(),+ table: "person".to_string(),+ }],+ ..Default::default()+ };+ let ddl = render_postgres_table_ddl_with_partition_info(+ "public",+ "remote_emp",+ &columns,+ &[],+ &[],+ &[],+ None,+ &partition_info,+ &db::postgres::PostgresTablePartitionLocalObjects::default(),+ );+ assert!(ddl.starts_with("CREATE FOREIGN TABLE"), "ddl: {ddl}");+ assert!(!ddl.contains("INHERITS"), "ddl: {ddl}");+ }+#[test]fn postgres_table_ddl_keeps_composite_foreign_key_together() {let columns = vec![column("a", "integer"), column("b", "integer"), column("c", "integer")];@@ -15315,7 +15431,22 @@ fn render_postgres_table_ddl_with_constraints_and_partition_info(};format!("{create} {table_name} PARTITION OF {parent_name}{definitions} {bound}")} else {- format!("{create} {table_name} (\n{}\n)", definition_lines.join(",\n"))+ let mut head = format!("{create} {table_name} (\n{}\n)", definition_lines.join(",\n"));+ // A traditional-inheritance child is neither a declarative partition+ // nor a foreign table. Emit `INHERITS (parent...)` so the dependency+ // survives a structure transfer. The column list above still carries+ // the inherited columns; PostgreSQL merges them with the parents'+ // definitions (matching types/defaults merge, conflicting ones raise).+ if !partition_info.is_foreign && !partition_info.inherits_parents.is_empty() {+ let parents = partition_info+ .inherits_parents+ .iter()+ .map(|parent| format!("{}.{}", pg_ident(&parent.schema), pg_ident(&parent.table)))+ .collect::<Vec<_>>()+ .join(", ");+ head.push_str(&format!(" INHERITS ({parents})"));+ }+ head};if let Some(server) = partition_info.foreign_server.as_deref().filter(|server| !server.trim().is_empty()) {ddl.push_str(&format!(" SERVER {}", pg_ident(server)));diff --git a/crates/dbx-core/tests/live_postgres_schema_contracts.rs b/crates/dbx-core/tests/live_postgres_schema_contracts.rsindex 101c1848ad..6a1ded4faa 100644--- a/crates/dbx-core/tests/live_postgres_schema_contracts.rs+++ b/crates/dbx-core/tests/live_postgres_schema_contracts.rs@@ -225,7 +225,17 @@ async fn postgres_legacy_table_ddl_uses_compatible_partition_probe() {assert!(ddl.contains("FOREIGN KEY"), "ddl: {ddl}");assert!(ddl.contains("CREATE INDEX \"child_name_idx\""), "ddl: {ddl}");assert!(ddl.contains("CREATE TRIGGER child_bi"), "ddl: {ddl}");- assert_eq!(partition_info, PostgresTablePartitionInfo::default());+ // The 9.x child uses traditional `INHERITS`, so it is not a declarative+ // partition, but it must carry its parent in `inherits_parents` and the+ // rendered DDL must emit `INHERITS (parent)` (issue #10803).+ assert!(!partition_info.is_partition, "partition_info: {partition_info:?}");+ assert!(!partition_info.is_foreign, "partition_info: {partition_info:?}");+ assert_eq!(partition_info.inherits_parents.len(), 1, "partition_info: {partition_info:?}");+ assert_eq!(partition_info.inherits_parents[0].table, "parent", "partition_info: {partition_info:?}");+ assert!(partition_info.parent_schema.is_none(), "partition_info: {partition_info:?}");+ assert!(partition_info.bound.is_none(), "partition_info: {partition_info:?}");+ assert!(ddl.contains("INHERITS"), "ddl: {ddl}");+ assert!(ddl.contains("\"parent\""), "ddl: {ddl}");assert!(!ddl.contains("PARTITION OF"), "ddl: {ddl}");assert!(ddl_with_partitions.contains("CREATE TABLE"), "ddl_with_partitions: {ddl_with_partitions}");assert!(!ddl_with_partitions.contains("PARTITION OF"), "ddl_with_partitions: {ddl_with_partitions}");diff --git a/crates/dbx-driver-postgres/src/postgres.rs b/crates/dbx-driver-postgres/src/postgres.rsindex c1d020f1e6..a87a82c19d 100644--- a/crates/dbx-driver-postgres/src/postgres.rs+++ b/crates/dbx-driver-postgres/src/postgres.rs@@ -89,6 +89,12 @@ pub struct PostgresTableAccessInfo {pub privileges: Vec<PostgresTablePrivilegeInfo>,}+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct PostgresInheritsParent {+ pub schema: String,+ pub table: String,+}+#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct PostgresTablePartitionInfo {pub is_partition: bool,@@ -103,6 +109,14 @@ pub struct PostgresTablePartitionInfo {pub is_foreign: bool,pub foreign_server: Option<String>,pub foreign_options: Vec<(String, String)>,+ /// Traditional `INHERITS` parent tables (relkind ≠ 'p'), in+ /// `inhseqno` order. A relation is either a declarative partition+ /// (`is_partition = true`, single parent of relkind 'p') or a+ /// traditional-inheritance child (one or more `INHERITS` parents of+ /// relkind 'r'), never both. Empty for plain tables and declarative+ /// partitions. Used by table sync to emit `CREATE TABLE ... INHERITS+ /// (parent...)` so the dependency survives a structure transfer.+ pub inherits_parents: Vec<PostgresInheritsParent>,}/// The state of a partition-local column DEFAULT relative to the parent's@@ -4065,8 +4079,9 @@ pub async fn get_table_partition_info(};let relkind = relation.try_get::<_, String>(0).unwrap_or_default();let is_partition = relation.try_get::<_, bool>(1).unwrap_or(false);+ let has_inherits_parent = relation.try_get::<_, bool>(2).unwrap_or(false);let is_foreign = relkind == "f";- if relkind != "p" && !is_foreign && !is_partition {+ if relkind != "p" && !is_foreign && !is_partition && !has_inherits_parent {return Ok(PostgresTablePartitionInfo::default());}@@ -4078,7 +4093,12 @@ pub async fn get_table_partition_info().await?;let Some(row) = rows.first() else {- return Ok(PostgresTablePartitionInfo { is_partition, is_foreign, ..Default::default() });+ let inherits_parents = if has_inherits_parent {+ get_table_inherits_parents_inner(&client, schema, table).await?+ } else {+ Vec::new()+ };+ return Ok(PostgresTablePartitionInfo { is_partition, is_foreign, inherits_parents, ..Default::default() });};let foreign_options = row.try_get::<_, Option<Vec<String>>>(5)@@ -4088,6 +4108,12 @@ pub async fn get_table_partition_info(.into_iter().filter_map(|option| option.split_once('=').map(|(key, value)| (key.to_string(), value.to_string()))).collect();+ // `postgres_table_partition_info_sql` only carries the single declarative+ // partition parent (a partition has exactly one). A traditional-inheritance+ // child can have several `INHERITS` parents, fetched separately so the+ // declarative-partition path stays untouched.+ let inherits_parents =+ if has_inherits_parent { get_table_inherits_parents_inner(&client, schema, table).await? } else { Vec::new() };Ok(PostgresTablePartitionInfo {is_partition,parent_schema: row.try_get::<_, Option<String>>(0).ok().flatten().filter(|value| !value.is_empty()),@@ -4097,6 +4123,7 @@ pub async fn get_table_partition_info(is_foreign,foreign_server: row.try_get::<_, Option<String>>(4).ok().flatten().filter(|value| !value.is_empty()),foreign_options,+ inherits_parents,})}@@ -4104,6 +4131,41 @@ pub async fn get_table_partition_key(pool: &Pool, schema: &str, table: &str) ->Ok(get_table_partition_info(pool, schema, table).await?.key)}+/// The traditional `INHERITS` parents of a relation (relkind ≠ 'p'), in+/// `inhseqno` order. Used by table sync to emit+/// `CREATE TABLE ... INHERITS (parent...)`. Returns an empty vector for+/// plain tables and declarative partitions. Unlike+/// `get_table_partition_info` this never hits the declarative-partition+/// catalog (`relispartition` / `pg_partitioned_table`), so it runs on+/// 9.x servers where `INHERITS` is the only inheritance form.+pub async fn get_table_inherits_parents(+ pool: &Pool,+ schema: &str,+ table: &str,+) -> Result<Vec<PostgresInheritsParent>, String> {+ let schema = if schema.is_empty() { "public" } else { schema };+ let client = checkout_postgres_client(pool, None, super::connection_timeout()).await?;+ get_table_inherits_parents_inner(&client, schema, table).await+}++async fn get_table_inherits_parents_inner(+ client: &deadpool_postgres::Client,+ schema: &str,+ table: &str,+) -> Result<Vec<PostgresInheritsParent>, String> {+ let rows = postgres_query_cached(client, postgres_table_inherits_parents_sql(), &[&schema, &table])+ .await+ .map_err(|e| e.to_string())?;+ Ok(rows+ .iter()+ .map(|row| PostgresInheritsParent {+ schema: row.try_get::<_, String>(0).unwrap_or_default(),+ table: row.try_get::<_, String>(1).unwrap_or_default(),+ })+ .filter(|parent| !parent.schema.is_empty() && !parent.table.is_empty())+ .collect())+}+/// The partitioning strategy of a single PostgreSQL partitioned parent, read/// from `pg_partitioned_table` so expression keys and multi-column keys come/// back structured instead of as concatenated `pg_get_partkeydef` text.@@ -4659,6 +4721,10 @@ pub async fn fetch_postgres_partition_tree(is_foreign,foreign_server: row.try_get::<_, Option<String>>(9).ok().flatten().filter(|value| !value.is_empty()),foreign_options,+ // This tree only walks declarative partitions (the query+ // filters `c.relispartition`); traditional-inheritance+ // children are not tree nodes, so they carry no parents here.+ inherits_parents: Vec::new(),};Some(PostgresPartitionTreeNode {oid,@@ -5721,7 +5787,12 @@ fn postgres_table_partition_relation_sql() -> &'static str {SELECT 1 FROM pg_catalog.pg_inherits i \WHERE i.inhrelid = c.oid \AND (SELECT parent.relkind FROM pg_catalog.pg_class parent WHERE parent.oid = i.inhparent) = 'p' \- ) AS is_partition \+ ) AS is_partition, \+ EXISTS ( \+ SELECT 1 FROM pg_catalog.pg_inherits i \+ WHERE i.inhrelid = c.oid \+ AND COALESCE((SELECT parent.relkind FROM pg_catalog.pg_class parent WHERE parent.oid = i.inhparent), 'r') <> 'p' \+ ) AS has_inherits_parent \FROM pg_catalog.pg_class c \JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \WHERE n.nspname = $1 AND c.relname = $2 AND c.relkind IN ('r','p','f') \@@ -5765,6 +5836,23 @@ fn postgres_table_partition_info_compat_sql() -> &'static str {LIMIT 1"}+fn postgres_table_inherits_parents_sql() -> &'static str {+ // Traditional-inheritance parents only: a declarative partition child+ // is also a `pg_inherits` row, but its parent has relkind 'p', which we+ // exclude here so partitions stay owned by `get_table_partition_info`.+ // Uses no 10+ catalog columns (`relispartition`/`pg_partitioned_table`),+ // so it runs unchanged on 9.x where `INHERITS` is the only form.+ "SELECT pn.nspname AS parent_schema, pc.relname AS parent_table \+ FROM pg_catalog.pg_inherits i \+ JOIN pg_catalog.pg_class pc ON pc.oid = i.inhparent \+ JOIN pg_catalog.pg_namespace pn ON pn.oid = pc.relnamespace \+ JOIN pg_catalog.pg_class c ON c.oid = i.inhrelid \+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \+ WHERE n.nspname = $1 AND c.relname = $2 \+ AND COALESCE(pc.relkind, 'r') <> 'p' \+ ORDER BY i.inhseqno"+}+fn postgres_table_partition_local_objects_sql() -> &'static str {"SELECT 'constraint'::text AS object_kind, con.conname AS object_name, con.contype::text AS object_type \FROM pg_catalog.pg_constraint con \@@ -9527,9 +9615,12 @@ fn opengauss_foreign_keys_sql() -> &'static str {}fn postgres_table_dependencies_sql() -> &'static str {- // Foreign keys aren't the only ordering constraint on export/replay: a- // partition must be created after its parent table exists too, so union- // in `pg_inherits` partition-of edges alongside the FK edges.+ // Foreign keys aren't the only ordering constraint on export/replay:+ // a child relation must be created after its parent exists too. The+ // `pg_inherits` union covers both declarative partitions (parent+ // relkind 'p') and traditional `INHERITS` children (parent relkind+ // 'r'); both need the parent first, so no `relispartition` filter is+ // applied here (matching the 9.x compat path)."SELECT child.relname AS table_name, parent.relname AS ref_table \FROM pg_catalog.pg_constraint con \JOIN pg_catalog.pg_class child ON child.oid = con.conrelid \@@ -9542,7 +9633,7 @@ fn postgres_table_dependencies_sql() -> &'static str {UNION \SELECT child.relname AS table_name, parent.relname AS ref_table \FROM pg_catalog.pg_inherits i \- JOIN pg_catalog.pg_class child ON child.oid = i.inhrelid AND child.relispartition \+ JOIN pg_catalog.pg_class child ON child.oid = i.inhrelid \JOIN pg_catalog.pg_namespace child_schema ON child_schema.oid = child.relnamespace \JOIN pg_catalog.pg_class parent ON parent.oid = i.inhparent \JOIN pg_catalog.pg_namespace parent_schema ON parent_schema.oid = parent.relnamespace \@@ -12610,7 +12701,11 @@ mod tests {assert!(sql.contains("parent_schema.nspname = $1"));assert!(!sql.contains("information_schema"));assert!(sql.contains("pg_catalog.pg_inherits"));- assert!(sql.contains("child.relispartition"));+ // Both declarative partitions and traditional `INHERITS` children need+ // their parent created first, so the dependency edge covers every+ // `pg_inherits` row (no `relispartition` filter) — matching the 9.x+ // compat path which never had the column to filter on.+ assert!(!sql.contains("relispartition"));// 兼容版面向 9.x:不能引用 relispartition,但 INHERITS 边要保留// (旧式子表同样要先建父表)。assert!(!compat_sql.contains("relispartition"));@@ -12619,6 +12714,31 @@ mod tests {assert!(compat_sql.contains("ORDER BY table_name, ref_table"));}+ #[test]+ fn postgres_table_inherits_parents_sql_targets_traditional_parents() {+ let sql = postgres_table_inherits_parents_sql();+ // Resolves parents via pg_inherits, excludes the declarative-partition+ // 'p' relkind so partition parents stay owned by partition_info.+ assert!(sql.contains("pg_catalog.pg_inherits"));+ assert!(sql.contains("i.inhrelid"));+ assert!(sql.contains("COALESCE(pc.relkind, 'r') <> 'p'"));+ // Order is stable across DB restarts.+ assert!(sql.contains("ORDER BY i.inhseqno"));+ // No 10+-only columns, so it runs unchanged on 9.x.+ assert!(!sql.contains("relispartition"));+ assert!(!sql.contains("pg_partitioned_table"));+ }++ #[test]+ fn postgres_table_partition_relation_sql_flags_inherits_parent() {+ let sql = postgres_table_partition_relation_sql();+ assert!(sql.contains("AS is_partition"));+ assert!(sql.contains("AS has_inherits_parent"));+ // The INHERITS flag selects parents whose relkind is not 'p'+ // (declarative partitions are excluded so they stay is_partition).+ assert!(sql.contains("<> 'p'"));+ }+#[test]fn decodes_tsvector_binary_output() {let raw = [