Skip to content

Instantly share code, notes, and snippets.

@grauwoelfchen
Created November 16, 2015 20:33
Show Gist options
  • Save grauwoelfchen/d2bfa9db252ec94388e7 to your computer and use it in GitHub Desktop.
Save grauwoelfchen/d2bfa9db252ec94388e7 to your computer and use it in GitHub Desktop.
Postgresql backend in Yesod
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Logger (runStderrLoggingT)
import Database.Persist
import Database.Persist.Postgresql
import Database.Persist.TH
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Person
name String
age Int Maybe
deriving Show
BlogPost
title String
authorId PersonId
deriving Show
|]
connStr :: ConnectionString
connStr = "host=localhost dbname=test port=5432\
\ user=postgres password=postgres"
main :: IO ()
main = runStderrLoggingT $ withPostgresqlPool connStr 10 $
\pool -> liftIO $ do
flip runSqlPersistMPool pool $ do
runMigration migrateAll
johnId <- insert $ Person "John Doe" $ Just 35
janeId <- insert $ Person "Jane Doe" Nothing
_ <- insert $ BlogPost "My first p0st" johnId
_ <- insert $ BlogPost "One more p0st" johnId
oneJohnPost <- selectList [BlogPostAuthorId ==. johnId] [LimitTo 1]
liftIO $ print (oneJohnPost :: [Entity BlogPost])
john <- get johnId
liftIO $ print (john :: Maybe Person)
delete janeId
deleteWhere [BlogPostAuthorId ==. johnId]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment