yesod/yesod-examples/synopsis/persistent.lhs
Michael Snoyman 41faf62094 Add 'yesod-examples/' from commit '851f928e55b3646f7790b6cc70968957cca04a4b'
git-subtree-dir: yesod-examples
git-subtree-mainline: 2dc10de435
git-subtree-split: 851f928e55
2011-07-22 08:59:56 +03:00

40 lines
1.1 KiB
Plaintext

This example uses the sqlite backend for Persistent, since it can run in-memory and has no external dependencies.
> {-# LANGUAGE TypeFamilies, GeneralizedNewtypeDeriving, QuasiQuotes, TemplateHaskell, OverloadedStrings #-}
>
> import Database.Persist.Sqlite
> import Database.Persist.TH
> import Control.Monad.IO.Class (liftIO)
>
> mkPersist [$persist|Person
> name String Eq
> age Int Update
> |]
>
> main :: IO ()
> main = withSqliteConn ":memory:" $ runSqlConn go
>
> go :: SqlPersist IO ()
> go = do
> runMigration $ migrate (undefined :: Person)
> key <- insert $ Person "Michael" 25
> liftIO $ print key
> p1 <- get key
> liftIO $ print p1
> update key [PersonAge 26]
> p2 <- get key
> liftIO $ print p2
> p3 <- selectList [PersonNameEq "Michael"] [] 0 0
> liftIO $ print p3
> delete key
> p4 <- selectList [PersonNameEq "Michael"] [] 0 0
> liftIO $ print p4
The output of the above is:
<code><pre>PersonId 1
Just (Person {personName = "Michael", personAge = 25})
Just (Person {personName = "Michael", personAge = 26})
[(PersonId 1,Person {personName = "Michael", personAge = 26})]
[]</pre></code>