Yesod: querying `persist` database with a custom primary key

491 views Asked by At

Supposing that I have a SQL table with persist, and that I have a custom Text as primary key instead of the auto-incrementing Int64 key.

For example, my database definition is thus:

share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
TorrentD
    infoHash Text
    ipAddr [Text]
    Primary infoHash
    deriving Show
|]

Supposing that I then have a plain Text value, what is the idiomatic way to query the database for a row with a primary key matching my Text value?

runDB $ get $ toSqlKey ("test" :: Text) doesn't work as toSqlKey doesn't support custom primary keys and thus expects expects an Int64.

Creating the key manually and running runDB $ get $ Key $ PersistText ("test" :: Text) doesn't work as it is giving me an error about Key not being in scope (although I do have Database.Persist.Class in my imports).

1

There are 1 answers

2
AudioBubble On

I've found (the?) (an?) answer. It's not very pretty, but:

get (TorrentDKey {unTorrentDKey = torrentPInfoHash torrent})

works.

The unTorrentDKey is something generated inside the template haskell.

It looks like i'll have to pepper

let primaryKey = TorrentDKey {unTorrentDKey = torrentPInfoHash torrent}

around in my code.