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): preserve foreign key actions and deferral in backups
lcq928282a2742d16b
diff --git a/crates/dbx-core/src/schema/mod.rs b/crates/dbx-core/src/schema/mod.rsindex c712d66ebe..3f1d87b62b 100644--- a/crates/dbx-core/src/schema/mod.rs+++ b/crates/dbx-core/src/schema/mod.rs@@ -15355,6 +15355,24 @@ mod ddl_tests {assert_eq!(ddl.matches("CONSTRAINT \"aaa_1\" FOREIGN KEY").count(), 1);}+ #[test]+ fn postgres_table_ddl_preserves_foreign_key_actions_without_native_definition() {+ let foreign_key = db::ForeignKeyInfo {+ name: "fk_parent".to_string(),+ column: "parent_id".to_string(),+ ref_schema: Some("other".to_string()),+ ref_table: "parent".to_string(),+ ref_column: "id".to_string(),+ on_update: Some("RESTRICT".to_string()),+ on_delete: Some("CASCADE".to_string()),+ };+ let ddl = render_postgres_table_ddl("public", "child", &[], &[], &[foreign_key], None);+ assert!(+ ddl.contains("REFERENCES \"other\".\"parent\"(\"id\") ON UPDATE RESTRICT ON DELETE CASCADE"),+ "ddl: {ddl}"+ );+ }+#[test]fn postgres_table_ddl_appends_trigger_definitions() {let ddl = append_postgres_trigger_definitions(@@ -17206,6 +17224,7 @@ fn render_postgres_table_ddl_with_constraints_and_partition_info(}definition_lines.push(format!(" CONSTRAINT {} {}", pg_ident(&constraint.name), constraint.definition.trim()));}+ let mut not_valid_foreign_keys = Vec::new();for fk_group in group_foreign_keys_by_name(fkeys) {let Some(first_fk) = fk_group.first() else {continue;@@ -17218,13 +17237,36 @@ fn render_postgres_table_ddl_with_constraints_and_partition_info(let referenced_schema =first_fk.ref_schema.as_deref().filter(|value| !value.trim().is_empty()).unwrap_or(schema);let referenced_table = format!("{}.{}", pg_ident(referenced_schema), pg_ident(&first_fk.ref_table));- definition_lines.push(format!(- " CONSTRAINT {} FOREIGN KEY ({}) REFERENCES {}({})",- pg_ident(&first_fk.name),- columns,- referenced_table,- ref_columns- ));+ let native_definition = constraints+ .iter()+ .find(|constraint| constraint.constraint_type == "FOREIGN KEY" && constraint.name == first_fk.name)+ .map(|constraint| constraint.definition.as_str())+ .or_else(|| partition_local_objects.foreign_key_definitions.get(&first_fk.name).map(String::as_str));+ // Keep our schema-qualified relation and ordered column pairs, but+ // preserve every native option after REFERENCES (...). The scanner+ // also handles parentheses inside quoted identifiers.+ let suffix = native_definition+ .and_then(|definition| {+ let columns_end = db::ddl_scan::find_top_level_paren_close(definition, 0)?;+ let references_end = db::ddl_scan::find_top_level_paren_close(definition, columns_end)?;+ Some(definition[references_end..].trim_end().to_string())+ })+ .unwrap_or_else(|| {+ let mut suffix = String::new();+ if let Some(action) = first_fk.on_update.as_deref() {+ suffix.push_str(&format!(" ON UPDATE {action}"));+ }+ if let Some(action) = first_fk.on_delete.as_deref() {+ suffix.push_str(&format!(" ON DELETE {action}"));+ }+ suffix+ });+ let definition = format!("FOREIGN KEY ({columns}) REFERENCES {referenced_table}({ref_columns}){suffix}");+ if is_not_valid_constraintdef(&definition) {+ not_valid_foreign_keys.push((first_fk.name.as_str(), definition));+ } else {+ definition_lines.push(format!(" CONSTRAINT {} {definition}", pg_ident(&first_fk.name)));+ }}// `pg_get_constraintdef` appends ` NOT VALID` for an unvalidated CHECK// constraint, but that suffix is only legal after `ALTER TABLE ADD@@ -17305,6 +17347,9 @@ fn render_postgres_table_ddl_with_constraints_and_partition_info(}ddl.push_str(";\n");+ for (name, definition) in ¬_valid_foreign_keys {+ ddl.push_str(&format!("\nALTER TABLE {table_name} ADD CONSTRAINT {} {};", pg_ident(name), definition));+ }for (name, definition) in ¬_valid_check_constraints {ddl.push_str(&format!("\nALTER TABLE {table_name} ADD CONSTRAINT {} {};", pg_ident(name), definition));}diff --git a/crates/dbx-core/tests/live_postgres_export_foreign_key_attributes.rs b/crates/dbx-core/tests/live_postgres_export_foreign_key_attributes.rsnew file mode 100644index 0000000000..2a29910295--- /dev/null+++ b/crates/dbx-core/tests/live_postgres_export_foreign_key_attributes.rs@@ -0,0 +1,182 @@+//! Issue #13517: preserve PostgreSQL foreign key actions and deferral on backup/restore.+//! Uses the DBX_LIVE_POSTGRES_EXPORT_* variables documented by the sibling export tests.+//! Run with RUST_MIN_STACK=67108864 for the database export future.++use dbx_core::connection::AppState;+use dbx_core::database_export::{export_database_sql_core, DatabaseExportRequest};+use dbx_core::models::connection::{ConnectionConfig, DatabaseType};+use dbx_core::query::execute_sql_statement;+use dbx_core::sql::SqlFileRequest;+use std::sync::Arc;++fn config(id: &str, database: &str) -> ConnectionConfig {+ serde_json::from_value(serde_json::json!({+ "id": id, "name": id, "db_type": DatabaseType::Postgres,+ "host": std::env::var("DBX_LIVE_POSTGRES_EXPORT_HOST").unwrap(),+ "port": std::env::var("DBX_LIVE_POSTGRES_EXPORT_PORT").unwrap().parse::<u16>().unwrap(),+ "username": std::env::var("DBX_LIVE_POSTGRES_EXPORT_USER").unwrap(),+ "password": std::env::var("DBX_LIVE_POSTGRES_EXPORT_PASSWORD").unwrap_or_default(),+ "database": database, "ssl": false,+ "connect_timeout_secs": 10, "query_timeout_secs": 30,+ "idle_timeout_secs": 60, "keepalive_interval_secs": 0+ }))+ .unwrap()+}++async fn child_before_parent(database: &str) -> Result<(), String> {+ let mut connection = tokio_postgres::Config::new();+ connection+ .host(std::env::var("DBX_LIVE_POSTGRES_EXPORT_HOST").unwrap())+ .port(std::env::var("DBX_LIVE_POSTGRES_EXPORT_PORT").unwrap().parse().unwrap())+ .user(std::env::var("DBX_LIVE_POSTGRES_EXPORT_USER").unwrap())+ .password(std::env::var("DBX_LIVE_POSTGRES_EXPORT_PASSWORD").unwrap_or_default())+ .dbname(database);+ let (client, driver) = connection.connect(tokio_postgres::NoTls).await.unwrap();+ let driver = tokio::spawn(driver);+ let child = uuid::Uuid::new_v4();+ let parent = uuid::Uuid::new_v4();+ let version = uuid::Uuid::new_v4();+ let result = client+ .batch_execute(&format!(+ "BEGIN; \+ INSERT INTO public.child_table VALUES ('{child}', '{parent}', '{version}'); \+ INSERT INTO public.parent_table VALUES ('{parent}', '{version}'); COMMIT;"+ ))+ .await+ .map_err(|error| format!("{error:?}"));+ drop(client);+ driver.await.unwrap().unwrap();+ result+}++#[tokio::test]+#[ignore = "requires a disposable PostgreSQL endpoint; detects issue #13517"]+async fn live_postgres_export_preserves_foreign_key_actions_and_deferral() {+ let suffix = uuid::Uuid::new_v4().simple().to_string();+ let source = format!("dbx_13517_src_{}", &suffix[..10]);+ let target = format!("dbx_13517_dst_{}", &suffix[..10]);+ let storage_dir = tempfile::tempdir().unwrap();+ let output = std::env::var_os("DBX_ISSUE_13517_OUTPUT_DIR")+ .map(std::path::PathBuf::from)+ .unwrap_or_else(|| storage_dir.path().to_path_buf());+ std::fs::create_dir_all(&output).unwrap();+ let storage = dbx_core::persistence::test_storage::open(&storage_dir.path().join("storage.db")).await.unwrap();+ let state = Arc::new(AppState::new(storage));+ for (id, database) in [("admin", "postgres"), ("source", &source), ("target", &target)] {+ state.configs.write().await.insert(id.to_string(), config(id, database));+ }+ for database in [&source, &target] {+ execute_sql_statement(&state, "admin", "postgres", &format!("CREATE DATABASE \"{database}\""), None, None)+ .await+ .unwrap();+ }+ for statement in [+ "CREATE TABLE public.parent_table (id uuid NOT NULL, version_id uuid NOT NULL, \+ PRIMARY KEY (id), UNIQUE (id, version_id))",+ "CREATE TABLE public.child_table (id uuid PRIMARY KEY, parent_id uuid NOT NULL, \+ parent_version_id uuid NOT NULL, CONSTRAINT fk_child_parent \+ FOREIGN KEY (parent_id, parent_version_id) REFERENCES public.parent_table (id, version_id) \+ ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED)",+ ] {+ execute_sql_statement(&state, "source", &source, statement, None, None).await.unwrap();+ }+ let source_transaction = child_before_parent(&source).await;+ assert!(source_transaction.is_ok(), "source transaction: {source_transaction:?}");+ let catalog_sql = "SELECT condeferrable, condeferred, confupdtype::text, confdeltype::text, \+ pg_get_constraintdef(oid) AS definition FROM pg_catalog.pg_constraint \+ WHERE conrelid = 'public.child_table'::regclass AND conname = 'fk_child_parent'";+ let source_catalog = execute_sql_statement(&state, "source", &source, catalog_sql, None, None).await.unwrap();+ let constraints =+ dbx_core::schema::list_constraints_core(&state, "source", &source, "public", "child_table").await.unwrap();+ let foreign_keys =+ dbx_core::schema::list_foreign_keys_core(&state, "source", &source, "public", "child_table").await.unwrap();+ let ddl =+ dbx_core::schema::get_table_ddl_core(&state, "source", &source, "public", "child_table", None).await.unwrap();+ std::fs::write(output.join("source-dbx-ddl.sql"), &ddl).unwrap();+ let export_path = output.join("backup.sql");+ export_database_sql_core(+ &state,+ &DatabaseExportRequest {+ export_id: format!("issue-13517-{suffix}"),+ connection_id: "source".to_string(),+ database: source.clone(),+ schema: "public".to_string(),+ file_path: export_path.display().to_string(),+ selected_tables: Vec::new(),+ excluded_tables: Vec::new(),+ include_structure: true,+ include_data: true,+ include_objects: false,+ include_create_database: false,+ drop_table_if_exists: false,+ omit_auto_increment: false,+ preserve_original_language: false,+ fail_on_error: true,+ prevent_overwrite: false,+ output_compression: Default::default(),+ insert_dialect: Default::default(),+ insert_mode: Default::default(),+ snapshot_session_id: None,+ batch_size: 1000,+ split_max_mb: None,+ },+ |_| {},+ )+ .await+ .unwrap();+ let restore_request = SqlFileRequest {+ txn_session_id: None,+ execution_id: format!("issue-13517-restore-{suffix}"),+ connection_id: "target".to_string(),+ database: target.clone(),+ schema: Some("public".to_string()),+ file_path: export_path.display().to_string(),+ continue_on_error: false,+ selected_tables: None,+ part_cooldown_ms: 0,+ skip_relational_constraints: false,+ failure_log_enabled: true,+ resolve_includes: false,+ encoding: Default::default(),+ };+ dbx_core::sql_file_import::execute_sql_file_path(+ &state,+ &restore_request,+ &export_path,+ tokio_util::sync::CancellationToken::new(),+ std::time::Instant::now(),+ |_| {},+ )+ .await+ .unwrap();+ let target_catalog = execute_sql_statement(&state, "target", &target, catalog_sql, None, None).await.unwrap();+ let target_transaction = child_before_parent(&target).await;++ let report = serde_json::json!({+ "source_catalog": source_catalog.rows,+ "restored_catalog": target_catalog.rows,+ "source_constraint_metadata": constraints,+ "source_foreign_key_metadata": foreign_keys,+ "source_transaction": source_transaction,+ "restored_transaction": target_transaction,+ "source_dbx_ddl": ddl,+ "export_path": export_path+ });+ let report = serde_json::to_string_pretty(&report).unwrap();+ println!("{report}");+ std::fs::write(output.join("result.json"), report).unwrap();+ for database in [&source, &target] {+ execute_sql_statement(+ &state,+ "admin",+ "postgres",+ &format!("DROP DATABASE \"{database}\" WITH (FORCE)"),+ None,+ None,+ )+ .await+ .unwrap();+ }+ assert_eq!(source_catalog.rows, target_catalog.rows, "backup/restore changed foreign key attributes");+ assert!(target_transaction.is_ok(), "restored transaction: {target_transaction:?}");+}diff --git a/crates/dbx-core/tests/live_postgres_schema_contracts.rs b/crates/dbx-core/tests/live_postgres_schema_contracts.rsindex 6a1ded4faa..b9201cfa22 100644--- a/crates/dbx-core/tests/live_postgres_schema_contracts.rs+++ b/crates/dbx-core/tests/live_postgres_schema_contracts.rs@@ -386,6 +386,77 @@ async fn postgres_legacy_batched_ddl_metadata_preserves_relation_pairs_across_coassert!(!without_fk_ddl.contains("FOREIGN KEY"), "without-fk ddl: {without_fk_ddl}");}+#[tokio::test]+#[ignore = "requires DBX_TEST_POSTGRES_URL pointing at a writable PostgreSQL 15+ database"]+async fn postgres_foreign_key_options_round_trip_through_single_and_partition_tree_ddl() {+ let url = std::env::var("DBX_TEST_POSTGRES_URL").expect("DBX_TEST_POSTGRES_URL");+ let pool = connect(&url, Duration::from_secs(5)).await.expect("connect postgres");+ let suffix = uuid::Uuid::new_v4().simple().to_string();+ let source = format!("dbx_fk_options_{}", &suffix[..10]);+ let references = format!("{source}_refs");+ let source_ident = pg_quote_ident(&source);+ let references_ident = pg_quote_ident(&references);+ let client = pool.get().await.expect("get postgres client");+ client.batch_execute(&format!(+ "CREATE SCHEMA {source_ident}; CREATE SCHEMA {references_ident};+ CREATE TABLE {references_ident}.\"parent(table\" (\"id)\" integer, version integer, PRIMARY KEY (\"id)\", version));+ CREATE TABLE {source_ident}.children (+ id integer, \"parent)a\" integer, \"parent\"\"b\" integer,+ CONSTRAINT fk_parent FOREIGN KEY (\"parent)a\", \"parent\"\"b\")+ REFERENCES {references_ident}.\"parent(table\" (\"id)\", version)+ MATCH FULL ON UPDATE RESTRICT ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED+ ) PARTITION BY RANGE (id);+ CREATE TABLE {source_ident}.children_default PARTITION OF {source_ident}.children DEFAULT;+ ALTER TABLE {source_ident}.children_default ADD CONSTRAINT fk_local+ FOREIGN KEY (\"parent)a\", \"parent\"\"b\") REFERENCES {references_ident}.\"parent(table\" (\"id)\", version)+ ON UPDATE CASCADE ON DELETE SET NULL (\"parent)a\") DEFERRABLE INITIALLY IMMEDIATE NOT VALID;"+ )).await.expect("create foreign key option fixtures");++ for include_tree in [false, true] {+ let replay = format!("{source}_{}", if include_tree { "tree" } else { "single" });+ let replay_ident = pg_quote_ident(&replay);+ let ddl = if include_tree {+ dbx_core::schema::pg_ddl_with_partitions(&pool, &source, "children").await+ } else {+ dbx_core::schema::pg_ddl(&pool, &source, "children").await+ }+ .expect("read foreign key DDL");+ client+ .batch_execute(&format!("CREATE SCHEMA {replay_ident}; {}", ddl.replace(&source_ident, &replay_ident)))+ .await+ .unwrap_or_else(|error| panic!("replay foreign key DDL: {error:?}; DDL: {ddl}"));+ let mut snapshots = Vec::new();+ for schema in [&source, &replay] {+ let result = execute_query(+ &pool,+ &format!(+ "SELECT c.relname::text, con.conname::text, con.condeferrable, con.condeferred,+ con.confupdtype::text, con.confdeltype::text, con.convalidated,+ pg_catalog.pg_get_constraintdef(con.oid, true) AS definition+ FROM pg_catalog.pg_constraint con+ JOIN pg_catalog.pg_class c ON c.oid = con.conrelid+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = {} AND con.contype = 'f'+ AND (c.relname = 'children' OR {})+ ORDER BY c.relname, con.conname",+ pg_quote_literal(schema),+ include_tree+ ),+ )+ .await+ .expect("snapshot restored constraint properties");+ assert!(!result.rows.is_empty());+ snapshots.push(result.rows);+ }+ assert_eq!(snapshots[0], snapshots[1], "foreign key options changed; DDL: {ddl}");+ client.batch_execute(&format!("DROP SCHEMA {replay_ident} CASCADE")).await.expect("drop replay schema");+ }+ client+ .batch_execute(&format!("DROP SCHEMA {source_ident} CASCADE; DROP SCHEMA {references_ident} CASCADE"))+ .await+ .expect("drop fixture schemas");+}+#[tokio::test]#[ignore = "requires DBX_TEST_POSTGRES_URL pointing at a writable PostgreSQL database"]async fn postgres_ddl_emits_not_valid_check_constraints_as_separate_replayable_alter() {diff --git a/crates/dbx-driver-postgres/src/postgres.rs b/crates/dbx-driver-postgres/src/postgres.rsindex eced772474..c14b6f0a59 100644--- a/crates/dbx-driver-postgres/src/postgres.rs+++ b/crates/dbx-driver-postgres/src/postgres.rs@@ -142,6 +142,8 @@ pub struct PostgresTablePartitionLocalObjects {pub has_primary_key: bool,pub unique_constraints: BTreeSet<String>,pub foreign_keys: BTreeSet<String>,+ /// Native definitions retained by the batched partition-tree DDL path.+ pub foreign_key_definitions: BTreeMap<String, String>,pub indexes: BTreeSet<String>,/// CHECK constraints with a local definition on this partition, as/// reported by pg_constraint.conislocal. A merged constraint may remain@@ -5774,7 +5776,13 @@ pub async fn get_table_partition_local_objects_for_relations_with_sql(let object_kind = row.try_get::<_, String>(1).unwrap_or_default();let object_name = row.try_get::<_, String>(2).unwrap_or_default();let object_type = row.try_get::<_, Option<String>>(3).ok().flatten().unwrap_or_default();- apply_partition_local_object_row(result.entry(relid).or_default(), &object_kind, object_name, &object_type);+ let entry = result.entry(relid).or_default();+ if object_kind == "constraint" && object_type == "f" {+ if let Some(definition) = pg_row_try_optional_text(row, 4) {+ entry.foreign_key_definitions.insert(object_name.clone(), definition);+ }+ }+ apply_partition_local_object_row(entry, &object_kind, object_name, &object_type);}Ok(result)}@@ -5787,23 +5795,24 @@ fn postgres_table_partition_local_objects_for_relations_query_tiers() -> [&'stat}pub fn postgres_table_partition_local_objects_for_relations_sql() -> &'static str {- "SELECT con.conrelid::bigint AS relid, 'constraint'::text AS object_kind, con.conname AS object_name, con.contype::text AS object_type \+ "SELECT con.conrelid::bigint AS relid, 'constraint'::text AS object_kind, con.conname AS object_name, con.contype::text AS object_type, \+ CASE WHEN con.contype = 'f' THEN pg_catalog.pg_get_constraintdef(con.oid, true) END AS definition \FROM pg_catalog.pg_constraint con \WHERE con.conrelid = ANY($1::bigint[]) AND con.contype IN ('p','u','f') \AND COALESCE(NULLIF(pg_catalog.row_to_json(con)->>'conparentid', '')::oid, 0) = 0 \UNION ALL \- SELECT con.conrelid::bigint, 'check'::text AS object_kind, con.conname AS object_name, NULL::text AS object_type \+ SELECT con.conrelid::bigint, 'check'::text AS object_kind, con.conname AS object_name, NULL::text AS object_type, NULL::text \FROM pg_catalog.pg_constraint con \WHERE con.conrelid = ANY($1::bigint[]) AND con.contype = 'c' AND con.conislocal \UNION ALL \- SELECT ix.indrelid::bigint, 'index'::text AS object_kind, idx.relname AS object_name, NULL::text AS object_type \+ SELECT ix.indrelid::bigint, 'index'::text AS object_kind, idx.relname AS object_name, NULL::text AS object_type, NULL::text \FROM pg_catalog.pg_index ix \JOIN pg_catalog.pg_class idx ON idx.oid = ix.indexrelid \WHERE ix.indrelid = ANY($1::bigint[]) \AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_inherits i WHERE i.inhrelid = idx.oid) \UNION ALL \SELECT a.attrelid::bigint, 'column_default'::text AS object_kind, a.attname AS object_name, \- CASE WHEN ad.oid IS NOT NULL THEN 'overridden' ELSE 'dropped' END AS object_type \+ CASE WHEN ad.oid IS NOT NULL THEN 'overridden' ELSE 'dropped' END AS object_type, NULL::text \FROM pg_catalog.pg_attribute a \JOIN pg_catalog.pg_inherits i ON i.inhrelid = a.attrelid \JOIN pg_catalog.pg_attribute pa \@@ -5826,22 +5835,23 @@ pub fn postgres_table_partition_local_objects_for_relations_sql() -> &'static st// compatibility tier can omit only that filter and keep the same batched// result shape.pub fn postgres_table_partition_local_objects_for_relations_compat_sql() -> &'static str {- "SELECT con.conrelid::bigint AS relid, 'constraint'::text AS object_kind, con.conname AS object_name, con.contype::text AS object_type \+ "SELECT con.conrelid::bigint AS relid, 'constraint'::text AS object_kind, con.conname AS object_name, con.contype::text AS object_type, \+ CASE WHEN con.contype = 'f' THEN pg_catalog.pg_get_constraintdef(con.oid, true) END AS definition \FROM pg_catalog.pg_constraint con \WHERE con.conrelid = ANY($1::bigint[]) AND con.contype IN ('p','u','f') \UNION ALL \- SELECT con.conrelid::bigint, 'check'::text AS object_kind, con.conname AS object_name, NULL::text AS object_type \+ SELECT con.conrelid::bigint, 'check'::text AS object_kind, con.conname AS object_name, NULL::text AS object_type, NULL::text \FROM pg_catalog.pg_constraint con \WHERE con.conrelid = ANY($1::bigint[]) AND con.contype = 'c' AND con.conislocal \UNION ALL \- SELECT ix.indrelid::bigint, 'index'::text AS object_kind, idx.relname AS object_name, NULL::text AS object_type \+ SELECT ix.indrelid::bigint, 'index'::text AS object_kind, idx.relname AS object_name, NULL::text AS object_type, NULL::text \FROM pg_catalog.pg_index ix \JOIN pg_catalog.pg_class idx ON idx.oid = ix.indexrelid \WHERE ix.indrelid = ANY($1::bigint[]) \AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_inherits i WHERE i.inhrelid = idx.oid) \UNION ALL \SELECT a.attrelid::bigint, 'column_default'::text AS object_kind, a.attname AS object_name, \- CASE WHEN ad.oid IS NOT NULL THEN 'overridden' ELSE 'dropped' END AS object_type \+ CASE WHEN ad.oid IS NOT NULL THEN 'overridden' ELSE 'dropped' END AS object_type, NULL::text \FROM pg_catalog.pg_attribute a \JOIN pg_catalog.pg_inherits i ON i.inhrelid = a.attrelid \JOIN pg_catalog.pg_attribute pa \