Foreign key constraints in Yesod/Persistent? Foreign key constraints in Yesod/Persistent? sqlite sqlite

Foreign key constraints in Yesod/Persistent?


Persistent uses the Haskell type system to generate foreign keys. That’s why there is no specific field type to indicate a field references a record in another table.

You should use the key type that Persistent created automatically to indicate the key.

Say I have User and Article tables. Persistent will generate the UserId and ArticleId for you. You will then use them to indicate references like in this example:

User    username    Text    password    Text    email       Text    description Text Maybe    active      Bool    UniqueUser  username    UniqueEmail email    deriving    TypeableArticle    artname     Text    title       Text    keywords    Text Maybe    description Text Maybe    body        Markdown    parent      ArticleId Maybe   -- optional Foreign Key    user        UserId            -- required Foreign Key    lastUpdate  UTCTime    weight      Int    public      Bool    UniqueArt   artname    deriving    Typeable

This model says:

  • An Article may hold a reference to another Article with the parent field of type ArticleId Maybe.
  • An Article must hold a reference to a User with the user field of type UserId.

This example will generate the following article table in PostgreSQL:

                Table "public.article"   Column    |           Type           |    Modifiers-------------+--------------------------+---------------- id          | integer                  | not null (...) artname     | character varying        | not null title       | character varying        | not null body        | character varying        | not null parent      | bigint                   |  user        | bigint                   | not null last_update | timestamp with time zone | not null weight      | bigint                   | not null public      | boolean                  | not null keywords    | character varying        | description | character varying        |Indexes:    "article_pkey" PRIMARY KEY, btree (id)    "unique_art" UNIQUE CONSTRAINT, btree (artname)Foreign-key constraints:    "article_parent_fkey" FOREIGN KEY (parent)                          REFERENCES article(id)    "article_user_fkey" FOREIGN KEY ("user")                        REFERENCES "user"(id)Referenced by:    TABLE "article" CONSTRAINT "article_parent_fkey"                    FOREIGN KEY (parent)                    REFERENCES article(id)

Note: If you use SQLite, you must ensure that foreign keys support is enabled. See → SQLite Foreign Key Support: Enabling Foreign Key Support