cakephp/phinx

PostgreSQL UNIQUE constraint as table constraints

opya opened this issue · 4 comments

opya commented

Is there any support for this:

http://www.w3resource.com/PostgreSQL/unique.php

CREATE TABLE orders(
ord_no integer,
ord_date date,
item_name character(35),
item_grade character(1),
ord_qty numeric,
ord_amount numeric,
UNIQUE (ord_no)
);

this don't do what i expected:
->addIndex(array("ord_no"), array('unique' => true))

Working with Indexes covers making them unique.

I just finished researching this. In Postgres, currently, adding a unique index will enforce uniqueness. In fact that's how unique constraints are actually implemented behind the scenes. However, in 9.4 docs there was this cautionary note:

The preferred way to add a unique constraint to a table is ALTER TABLE ... ADD CONSTRAINT. The use of indexes to enforce unique constraints could be considered an implementation detail that should not be accessed directly.

This note does not appear in 9.5 and 9.6 docs, but neither is there guidance on how we should interpret its disappearance. Another wrinkle is the question of whether columns with unique indexes (but not unique constraints) can be referenced by foreign key constraints. Some people read the docs as saying they cannot:

A foreign key must reference columns that either are a primary key or form a unique constraint.

But, I have tested this with success.

Even with my working tests and the disappearance of the warning note, it seems best to create unique constraints when a constraint is your intent. Not only does that make your intent more obvious to other developers, but it sends a clearer signal to Postgres as well—whether or not Postgres reacts any differently at the present time.

So this seems to me to be a feature worthy of implementation discussion for Phinx.

This affects other database adapters as well, such as SQLite. While functionally identical as well, constraints are treated differently (different DDL syntax as well).
This has mostly repercussions for other means of access, such as SQLite Studio, which interprets and displays unique indices different from unique constraints, leading to possible confusion.

Are you able to provide a patch with your suggested changes as PR?