Skip to content

Cannot create two-way BelongsTo association in PostgresSQL #15285

Description

@JamieREvans

Issue Creation Checklist

  • I understand that my issue will be automatically closed if I don't fill in the requested information
  • I have read the contribution guidelines

Bug Description

We have a couple cases where having mutual belongs to relationships makes sense for us (foreign keys on each table). However, as soon as you have a BelongsTo relationship on each table that points to the other table, strange issues start popping up; in our case, our ENUM fields failed when syncing the database.

Reproducible Example

import {
	Model,
	PrimaryKey,
	Column,
	Table,
	IsUUID,
} from 'sequelize-typescript';
import {
	BelongsTo,
	ForeignKey,
	HasMany,
} from 'sequelize-typescript';

@Table({
	tableName: 'ModelB',
})
export default class ModelB extends Model {
	@IsUUID(4)
	@PrimaryKey
	@Column
	id: string;

	@ForeignKey(() => ModelA)
	@Column
	modelAId: string;

	// Associations

	// Plans can have many shortlisted properties.
	// One directional association using ShortlistedProperty join table
	@HasMany(() => ModelA, 'modelBId')
	ModelAs: ModelA[];

	@BelongsTo(() => ModelA)
	PrimaryModelA: ModelA;
}

@Table({
	tableName: 'ModelA',
})
export default class ModelA extends Model {
	@IsUUID(4)
	@PrimaryKey
	@Column
	id: string;
	
	@Column({
		type: DataType.ENUM('First', 'Second'),
	})
	type: string;

	@ForeignKey(() => ModelB)
	@Column
	modelBId: string;

	// Associations

	@BelongsTo(() => ModelB)
	ModelB: ModelB;
}

What do you expect to happen?

I should be able to have mutual BelongsTo associations between models.

What is actually happening?

Error

If you comment out one of the BelongsTo associations, then the error goes away (but I need the association, so that's not a reasonable solution unfortunately). The same thing occurs with BelongsToMany.

Environment

  • Sequelize version: 6.25.3
  • Node.js version: v14.18.2
  • If TypeScript related: TypeScript version: 4.8.3
  • Database & Version: PostgreSQL Image: postgis/postgis:14-3.3
  • Connector library & Version: [email protected]

Would you be willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time and I know how to start.
  • Yes, I have the time but I will need guidance.
  • No, I don't have the time, but my company or I are supporting Sequelize through donations on OpenCollective.
  • No, I don't have the time, and I understand that I will need to wait until someone from the community or maintainers is interested in resolving my issue.

Indicate your interest in the resolution of this issue by adding the 👍 reaction. Comments such as "+1" will be removed.

Activity

  1. ephys commented on Nov 15, 2022

    @ephys
    Member

    I just ran this and it worked as expected. If you can replicate your issue using https://github.com/sequelize/sequelize-sscce I could help you further

    Nevermind I forgot the enum, I can confirm that the bug is present using this minimal sscce:

    class ModelB extends Model {}
    class ModelA extends Model {}
    
    ModelB.init({}, { sequelize });
    ModelA.init({
      type: {
        type: DataTypes.ENUM('First', 'Second'),
        comment: 'abc'
      }
    }, { sequelize });
    
    ModelA.belongsTo(ModelB);
    ModelB.belongsTo(ModelA);
    
    await sequelize.sync({ logging: console.log, force: true });

    Using both an enum and the comment is important to replicate this issue: together they produce COMMENT ON COLUMN "ModelAs"."type" IS 'abc' USING ("type"::"public"."enum_ModelAs_type"); which is not valid SQL.

    ALTER TABLE "ModelAs" ALTER COLUMN "type" DROP NOT NULL;ALTER TABLE "ModelAs" ALTER COLUMN "type" DROP DEFAULT;CREATE TYPE "public"."enum_ModelAs_type" AS ENUM('First', 'Second');ALTER TABLE "ModelAs" ALTER COLUMN "type" TYPE "public"."enum_ModelAs_type"; COMMENT ON COLUMN "ModelAs"."type" IS 'abc' USING ("type"::"public"."enum_ModelAs_type");

    But another issue is present if no comment is specified: it's going to try to create the enum twice due to the ALTER TABLE, which will result in error: type "enum_ModelAs_type" already exists

    This issue is closely related to #7649 and is already being worked on in #14687

  2. added
    type: bug
    on Nov 15, 2022
  3. JamieREvans commented on Nov 18, 2022

    @JamieREvans
    Author

    Interesting. @ephys can I help with this in any way? Also, is that branch usable at this point? I see that linting is blocking unit tests from running.

  4. ephys commented on Nov 18, 2022

    @ephys
    Member

    I'd love help, but I don't think much can be done to speed up the development of that PR. It's one of those features that are slow to rewrite because we support 8 dialects and each of them use a completely different syntax for their ALTER TABLE statement 😅

    The CI is red due to us making // !TODO cause a lint error (as a way to remind ourselves of important tasks that must be handled in that PR). The unit & integration tests are actually pretty green for postgres, mysql and mariadb. Only 5 dialects to go.

    I wouldn't use the PR's branch until the CI is at least green for the dialects you use. I also have potentially bad news if you're using Sequelize 6. Due to a breaking change, this PR will land in Sequelize 7 and can't be backported. If you don't need any third party tools, know that we only publish Sequelize 7 alphas that we consider stable

  5. added theissue type on Mar 9, 2025
  6. removed
    type: bug
    on Mar 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions