HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

ON DELETE CASCADE on pg_class in PostgreSQL does not work

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
postgresqldeletecascadeworkdoesnotpg_class

Problem

I added a foreign key on my table which references pg_class.

ALTER TABLE summary_table 
ADD FOREIGN KEY (table_oid_column) REFERENCES pg_class (oid) ON DELETE CASCADE;


I have a summary table which I keep some information about tables with their relational ids. When I drop a table I want to delete automatically related row from my summary table, so I added constraint above. But in my case, when I drop a table nothing happens.

I tried it with a test table, when I delete related row from test table, it works as expected. Such as with this foreign key constraint:

ALTER TABLE summary_table 
ADD FOREIGN KEY (table_oid_column) REFERENCES test (id) ON DELETE CASCADE;


What can be the problem? Can it be related with being a catalog table(pg_class) or a hidden system column(oid)?

Solution

Constraints are only checked when you execute SQL-level DML commands such as DELETE or UPDATE. They are not checked when you effect a system catalog data change using a DDL command such as DROP TABLE. Those take a different code path internally, even though they end up modifying the same data.

As a consequence, you currently cannot do what you are trying to do. In PostgreSQL 9.3, there will be event triggers, which will address the space your problem is in.

Context

StackExchange Database Administrators Q#29808, answer score: 5

Revisions (0)

No revisions yet.