Skip to content

Foreign key constraint not included when model definitions separated #1084

@brandon-leapyear

Description

@brandon-leapyear

We had our persistent model definitions in one file, but now we're trying to split them up into multiple files. But when we run migrations after compiling the multiple files, we notice that the database doesn't include foreign key constraints between models in different files. Specifically, the model1_model2_fkey constraint in PostgreSQL is created when the persistent model definitions are in one file, but not when they are in different files.

In debugging this, I built the following modules with -ddump-splices:

{- User.hs -}
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
  User
    name String
|]

{- Photo.hs -}
import User

share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
  Photo
    owner UserId
|]

{- Both.hs -}
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
  User
    name String

  Photo
    owner UserId
|]

Looking at the splices, the FieldDef for the owner column in Photo.hs is incorrectly marked as NoReference, whereas the FieldDef for the owner column in Both.hs is correctly marked as ForeignRef "User". I believe this discrepancy causes the migration code to not set the fkey constraint in the database.

# separate files
CREATe TABLE "photo"("id" SERIAL8  PRIMARY KEY UNIQUE,"owner" INT8 NOT NULL);
CREATe TABLE "user"("id" SERIAL8  PRIMARY KEY UNIQUE,"name" VARCHAR NOT NULL);

# same file
CREATe TABLE "user"("id" SERIAL8  PRIMARY KEY UNIQUE,"name" VARCHAR NOT NULL);
CREATe TABLE "photo"("id" SERIAL8  PRIMARY KEY UNIQUE,"owner" INT8 NOT NULL);
ALTER TABLE "photo" ADD CONSTRAINT "photo_owner_fkey" FOREIGN KEY("owner") REFERENCES "user"("id");

repro.zip

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions