2.10. 依赖跟踪 #
当我们创建一个涉及到很多具有外键约束、视图、触发器、函数等的表的复杂数据库结构时,我们隐式地创建了一张对象之间的依赖关系网。例如,具有一个外键约束的表依赖于它所引用的表。
为了确保整个数据库结构的完整性,PostgreSQL makes sure that you cannot drop objects that other objects still depend on. For example, attempting to drop the products table we had considered in 第 2.4.5 节, with the orders table depending on it, would result in an error message such as this:
DROP TABLE products;
NOTICE: constraint $1 on table orders depends on table products
ERROR: Cannot drop table products because other objects depend on it
Use DROP ... CASCADE to drop the dependent objects tooThe error message contains a useful hint: If you don't want to bother deleting all the dependent objects individually, you can run
DROP TABLE products CASCADE;
and all the dependent objects will be removed. In this case, it
doesn't remove the orders table, it only removes the foreign key
constraint. (If you want to check what DROP ... CASCADE will do,
run DROP without CASCADE and read the NOTICE messages.)
PostgreSQL 的所有删除命令都支持指定 CASCADE。当然,可能的依赖的性质随对象的类型而不同。你也可以写 RESTRICT 来代替
CASCADE,以获得默认行为,即限制删除其他对象所依赖的对象。
注意
根据 SQL 标准,必须指定
RESTRICT 或 CASCADE
之一。实际上没有数据库系统按这种方式实现,但默认行为是 RESTRICT 还是
CASCADE 因系统而异。
注意
PostgreSQL 7.3 之前版本的外键约束依赖和 serial 列依赖在升级过程中不会被维护或创建。所有其他依赖类型在升级期间都会被正确创建。