首页 > 解决方案 > Postgres破坏继承?

问题描述

在父表上使用后DROP COLUMN column_name,子表中的某些列不会被删除。

如何重新分配具有此行为的列以便将来正确删除级联?

如何重现:有两个表:parentchild。子项是从父项继承的,并且具有相同的列。在子项中添加新列test。在父级中添加新列test。之后,test孩子从父母那里继承。尝试test从父级删除 - 期望级联test从子级删除。但它仍然存在。

CREATE TABLE parent (a INT);
CREATE TABLE child () INHERITS (parent);
ALTER TABLE child ADD COLUMN test_inherit VARCHAR;
ALTER TABLE parent ADD COLUMN test_inherit VARCHAR;
ALTER TABLE parent DROP COLUMN test_inherit;

标签: postgresql

解决方案


这里发生的是 table 上的列child未标记为继承列:

CREATE TABLE parent (a INT);
CREATE TABLE child (a INT) INHERITS (parent);
NOTICE:  merging column "a" with inherited definition
ALTER TABLE child ADD COLUMN test_inherit VARCHAR;
ALTER TABLE parent ADD COLUMN test_inherit VARCHAR;
NOTICE:  merging definition of column "test_inherit" for child "child"

SELECT attname, attnum, attislocal
FROM pg_attribute
WHERE attrelid = 'child'::regclass AND attnum > 0;

   attname    | attnum | attislocal 
--------------+--------+------------
 a            |      1 | t
 test_inherit |      2 | t
(2 rows)

attislocal意味着它是child直接定义的列,而不是由于从另一个表继承而自动创建的。

如果您定义没有任何列的子表,则这些列将是继承列:

DROP TABLE parent, child;
CREATE TABLE parent (a INT, test_inherit VARCHAR);
CREATE TABLE child () INHERITS (parent);

SELECT attname, attnum, attislocal
FROM pg_attribute
WHERE attrelid = 'child'::regclass AND attnum > 0;

   attname    | attnum | attislocal 
--------------+--------+------------
 a            |      1 | f
 test_inherit |      2 | f
(2 rows)

如果继承父级中的列被删除,则仅继承的列被删除:

ALTER TABLE parent DROP COLUMN test_inherit;

\d child
               Table "laurenz.child"
 Column |  Type   | Collation | Nullable | Default 
--------+---------+-----------+----------+---------
 a      | integer |           |          | 
Inherits: parent

推荐阅读