Relax FK index requirements for Postgres compatibility
- Dominant language
- Go
- Stars
- 2.1k
- Forks
- 73
- Avg merge
- 1d 11h
- Merged PRs (30d)
- 152
Description
Both MySQL and Postgres require that the referenced table in a foreign key has a compatible index to ensure fast lookups. Additionally, MySQL also requires the referencing table to have a compatible index on it. Postgres encourages this index on the referencing table, but does not require it.
GMS currently implements the MySQL requirements and assumes this index on the referencing table must exist. This means some valid foreign key configurations in Postgres won't work in Doltgres. Customers can work around this limitation by creating a compatible index on the referencing table.
**Doltgres Repro:**
```sql
CREATE TABLE webhooks (
id varchar primary key
);
CREATE TABLE delivery_attempts (
id varchar not null,
webhook_id_fk varchar not null,
primary key (webhook_id_fk, id)
);
-- When we add the foreign key, the columns match up with the
-- referencing table's primary key. This compatible index
-- existing is required by MySQL/GMS, but NOT by Postgres.
alter table delivery_attempts add foreign key (webhook_id_fk) references webhooks(id);
-- When we remove the primary key, GMS is not able to find a
-- compatible index anymore and all updates to the table fail.
alter table delivery_attempts drop constraint delivery_attempts_pkey;
update webhooks set id='asdf' where id='asdfasd';
```
Returns:
```
ERROR: cannot add or update a child row: a foreign key constraint fails (`postgres`.`delivery_attempts`, CONSTRAINT `delivery_attempts_webhook_id_fk_fkey` FOREIGN KEY (`webhook_id_fk`) REFERENCES `webhooks` (`id`)) (errno 1105) (sqlstate HY000)
```
Discovered as part of testing DoltHub's Postgres schema dump import.
Contributor guide
Assessment
This issue has not been assessed yet.