Thread: Optimization of FK creation

Optimization of FK creation

From
Robert Ayrapetyan
Date:
Hello.

It's often neccessary to create empty table and FK to some existing
table from this newly created table.
However, even newly created (empty) table requires lock on parent
table it wants refer to.
On large production DBs with high load on parent table it's almost
neverending operation.

For example,

CREATE TABLE "table_foo" (
  ...
);

ALTER TABLE "table_foo"
  ADD CONSTRAINT "FK_table_foo_REF_table_parent"
  FOREIGN KEY ("ColName") REFERENCES "table_parent" ("ColName");

hangs forever because requires lock on "ColName" of table_parent with
billions of records,
which for empty table seems senseless.

I think it's very easy to check if "table_foo" is empty and therefore
not requires any locks on
"parent_table" and generate FK immediately without acquiring the lock
on "parent" table.

Similar problem raised here:
http://postgresql.1045698.n5.nabble.com/probelm-with-alter-table-add-constraint-td2072411.html

Please fix this issue asap.

regards,
--
Ayrapetyan Robert

Re: Optimization of FK creation

From
Tom Lane
Date:
Robert Ayrapetyan <robert.ayrapetyan@comodo.com> writes:
> I think it's very easy to check if "table_foo" is empty and therefore
> not requires any locks on
> "parent_table" and generate FK immediately without acquiring the lock
> on "parent" table.

Unfortunately, that's complete nonsense.  The reason for the lock on the
parent is so that DDL changes can be applied to it, namely addition of
triggers.

            regards, tom lane