sequelize / sequelize-auto

Automatically generate bare sequelize models from your database.
2.91k stars 529 forks source link

Postgresql 11 one to one relationship hasMany #513

Open divinebovine opened 3 years ago

divinebovine commented 3 years ago

I'm running into an issue where I believe an incorrect relationship is getting generated for postgresql 11. I have a one to one relationship that is getting modeled as one to many.

I have created a repository that recreates the issue here: https://github.com/divinebovine/OneToOneFailure

It contains instructions on how to run the test and its using a dockerized postgres, so it should be easy to replicate.

steveschmitt commented 3 years ago

Yes, with a unique constraint on bars.foo_id, each foo can only have one bar. It seems the constraint checking in sequelize-auto is not correct.

Tilogorn commented 2 years ago

Can confirm the same for mysql. In a Many-to-One, the foreign key in "Many" can occur multiple times.

In a One-to-One, the foreign key can occur only once. There seems to be no detection if a foreign key is unique in the wannabe-"Many" table. In my case it is unique because it is the primary key itself:

Table: UserBaseData

| id | username | password    |
|----|----------|-------------|
| 1  | foo      | 1e11db47671 |
| 2  | bar      | 1e11db47671 |

Table: UserExtendedData

| id | age | gender |
|----|-----|--------|
| 1  | 45  | M      |
| 2  | 62  | F      |
ALTER TABLE `UserBaseData` ADD PRIMARY KEY (`id`);
ALTER TABLE `UserExtendedData` ADD PRIMARY KEY (`id`);

ALTER TABLE `UserExtendedData`
  ADD CONSTRAINT `UserExtendedData_ibfk_1` FOREIGN KEY (`id`) REFERENCES `UserBaseData` (`id`) ... ;

This is a One-to-One relationship but sequelize-auto generates hasMany() and belongsTo() statements instead of hasOne() and belongsTo().