sqlhaskellpersistenthaskell-persistent

Using an SQL table without an ID column in Haskell/Persistent


I want to use an existing database with Persistent using this simplified schema:

share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Entity sql=entities
  deriving Show

EntityLink sql=entity_links
  sourceId EntityId
  targetId EntityId
  deriving Show
|]

The entities table has an id column, which is just fine. However, the entity_links table does not have one and I do not want to add one. Instead, it has the primary key (source_id, target_id). Whenever I want insert an EntityLink, I get this runtime error:

SqlError {sqlState = "42703", sqlExecStatus = FatalError, sqlErrorMsg = "column \"id\" does not exist", sqlErrorDetail = "", sqlErrorHint = ""}

Here's how I insert an EntityLink in the code, given valid sourceId and targetId:

      insert $ EntityLink { entityLinkSourceId = sourceId
                          , entityLinkTargetId = targetId
                          }

How can I disable the id column in Persistent for the type EntityLink?


Solution

  • You can use Primary and specify the columns that belong to the primary key. Like:

    EntityLink sql=entity_links
      sourceId EntityId
      targetId EntityId
      Primary sourceId targetId
      deriving Show