1
0
mirror of https://github.com/postgres/postgres.git synced 2025-11-03 09:13:20 +03:00

Fix timing issue with ALTER TABLE's validate constraint

An ALTER TABLE to validate a foreign key in which another subcommand
already caused a pending table rewrite could fail due to ALTER TABLE
attempting to validate the foreign key before the actual table rewrite
takes place.  This situation could result in an error such as:

ERROR:  could not read block 0 in file "base/nnnnn/nnnnn": read only 0 of 8192 bytes

The failure here was due to the SPI call which validates the foreign key
trying to access an index which is yet to be rebuilt.

Similarly, we also incorrectly tried to validate CHECK constraints before
the heap had been rewritten.

The fix for both is to delay constraint validation until phase 3, after
the table has been rewritten.  For CHECK constraints this means a slight
behavioral change.  Previously ALTER TABLE VALIDATE CONSTRAINT on
inheritance tables would be validated from the bottom up.  This was
different from the order of evaluation when a new CHECK constraint was
added.  The changes made here aligns the VALIDATE CONSTRAINT evaluation
order for inheritance tables to be the same as ADD CONSTRAINT, which is
generally top-down.

Reported-by: Nazli Ugur Koyluoglu, using SQLancer
Discussion: https://postgr.es/m/CAApHDvp%3DZXv8wiRyk_0rWr00skhGkt8vXDrHJYXRMft3TjkxCA%40mail.gmail.com
Backpatch-through: 9.5 (all supported versions)
This commit is contained in:
David Rowley
2020-07-14 16:54:47 +12:00
parent b8401c32ba
commit f1fcf2d3b2
3 changed files with 93 additions and 106 deletions

View File

@@ -757,6 +757,28 @@ alter table atacc1
add primary key(a);
drop table atacc1;
-- additionally, we've seen issues with foreign key validation not being
-- properly delayed until after a table rewrite. Check that works ok.
create table atacc1 (a int primary key);
alter table atacc1 add constraint atacc1_fkey foreign key (a) references atacc1 (a) not valid;
alter table atacc1 validate constraint atacc1_fkey, alter a type bigint;
drop table atacc1;
-- we've also seen issues with check constraints being validated at the wrong
-- time when there's a pending table rewrite.
create table atacc1 (a bigint, b int);
insert into atacc1 values(1,1);
alter table atacc1 add constraint atacc1_chk check(b = 1) not valid;
alter table atacc1 validate constraint atacc1_chk, alter a type int;
drop table atacc1;
-- same as above, but ensure the constraint violation is detected
create table atacc1 (a bigint, b int);
insert into atacc1 values(1,2);
alter table atacc1 add constraint atacc1_chk check(b = 1) not valid;
alter table atacc1 validate constraint atacc1_chk, alter a type int;
drop table atacc1;
-- something a little more complicated
create table atacc1 ( test int, test2 int);
-- add a primary key constraint