dolthub / go-mysql-server

A MySQL-compatible relational database with a storage agnostic query engine. Implemented in pure Go.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Missing index for foreign key error

twhiteman opened this issue · comments

Example schema:

CREATE TABLE `users` (
  `id` int(10) unsigned NOT NULL,
  `name` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE `managers` (
    `id` int(10) unsigned NOT NULL,
    `user_id` int(10) unsigned NOT NULL,
    PRIMARY KEY (`id`),
    FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Running this gives this error:

ERROR 1105 (HY000): missing index for foreign key `` on the referenced table `users`

Could be related to issue #1157.

This seems like an alias issue. Even in rave go-mysql-server (GMS) primary keys are indexes.

I'll tried the same in Dolt and made sure the issue is confined to the in-memory implementation of GMS:

PS C:\Users\timse\dolthub\dolt\test_fk_alias> dolt init
Successfully initialized dolt data repository.
PS C:\Users\timse\dolthub\dolt\test_fk_alias> dolt sql -q "CREATE TABLE `users` (
>>   `id` int(10) unsigned NOT NULL,
>>   `name` varchar(100) NOT NULL,
>>   PRIMARY KEY (`id`)
>> ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"
PS C:\Users\timse\dolthub\dolt\test_fk_alias> dolt sql -q "CREATE TABLE `managers` (
>>     `id` int(10) unsigned NOT NULL,
>>     `user_id` int(10) unsigned NOT NULL,
>>     PRIMARY KEY (`id`),
>>     FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
>> ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"
PS C:\Users\timse\dolthub\dolt\test_fk_alias> dolt schema show
managers @ working
CREATE TABLE `managers` (
  `id` int unsigned NOT NULL,
  `user_id` int unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`),
  CONSTRAINT `e4j585m5` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin;

users @ working
CREATE TABLE `users` (
  `id` int unsigned NOT NULL,
  `ame` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin;

PS C:\Users\timse\dolthub\dolt\test_fk_alias>

@Hydrocharged do you know why this is busted?

Seems like it should work. Just checked and we have engine tests that create a foreign key that references a single primary key, which is what we're doing here. I'd have to dig in and see what's different.

#1623
Issue was super simple. Logically, we're handling indexes and foreign keys perfectly fine, hence the confusion. The issue is that our example server didn't enable primary keys to be used as indexes, so it's just a setup issue. I'm not sure why we even allow primary keys to not be used as indexes (probably some legacy code we never removed), but we can investigate that later.

Thanks - and I'd agree that this would be nice to have as enabled by default :)

It's in the tip of main now!