10

I use Persistent orm with scotty web framework.

I want to get value from db by id. These id are coming to me from GET request

There are "get" function that takes "Key Entity" variable and returns "Maybe Entity".

I use following code to get value from db

k <- keyFromValues $ [(PersistInt64 myOwnIntVarFromRequest)]
case k of
    Left _ -> {-some processing-}
    Right x -> do
    t <- liftIO . runDb $ get (x::Key Post) --Post is one of my models
    case t of
        Nothing -> {-processing-}
        Just x -> {-processing-}

These code is extremly ugly. But i don't know how to do it better

So my question is how obtain variable of type "Key Entity" without calling keyFromValues.

PS Sorry for my poor English

Chris Stryczynski
  • 30,145
  • 48
  • 175
  • 286
Daiver
  • 1,488
  • 3
  • 18
  • 47

1 Answers1

16

You can use toSqlKey for that.

Michael Snoyman
  • 31,100
  • 3
  • 48
  • 77
  • @michael-snoyman: What if the key has some type other than `Int64`? – snøreven Apr 27 '16 at 11:38
  • I'm actually not familiar with the more flexible primary key mechanism in persistent, so I can't advise on how to handle that case. – Michael Snoyman Apr 27 '16 at 15:39
  • 5
    For the next person googling: the quasiquoter creates a declaration of the form `newtype Key TypeName = TypeNameKey {unTypeNameKey :: Int32 }` from the quote `persistLowerCase| TypeName Id Int32` – bergey Mar 21 '18 at 00:01
  • @snøreven You can actually just use the constructor. If you have an entity named `Company`, then constructing a key for this entity from some integer `n` is a case of doing `CompanyKey n`. – Jezen Thomas Nov 29 '21 at 20:13