Last active
February 26, 2019 23:40
-
-
Save bspaulding/dee7082c8cac70d6c2c881642c820856 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE DeriveGeneric, OverloadedStrings, OverloadedLabels #-} | |
module Main where | |
import Database.Selda | |
import Database.Selda.SQLite | |
import Database.Selda.Backend | |
data Pet = Dog | Horse | Dragon | |
deriving (Show, Read, Bounded, Enum) | |
instance SqlType Pet | |
data Person = Person | |
{ pid :: ID Person | |
, name :: Text | |
, age :: Int | |
, pet :: Maybe Pet | |
} deriving (Generic, Show) | |
instance SqlRow Person | |
people :: Table Person | |
people = table "people" [#pid :- autoPrimary] | |
insertAndPrintPK :: SeldaM () | |
insertAndPrintPK = do | |
pk <- insertWithPK people [Person def "Sara" 14 Nothing] | |
liftIO (print pk) | |
petsForEveryone :: SeldaM Int | |
petsForEveryone = do | |
update people | |
(\person -> isNull (person ! #pet)) | |
(\person -> person `with` [#pet := just (literal Dog)]) | |
compiledPetsForEveryone = compileUpdate defPPConfig | |
people | |
(\person -> person `with` [#pet := just (literal Dog)]) | |
(\person -> isNull (person ! #pet)) | |
getAdultsAndTheirPets = do | |
person <- select people | |
restrict (person ! #age .>= 18) | |
return (person ! #name :*: person ! #pet) | |
-- main :: SeldaM () | |
main = withSQLite "people-2.sqlite" $ do | |
dropTable people | |
createTable people | |
insert_ people | |
[ Person def "Velvet" 19 (Just Dog) | |
, Person def "Kobayashi" 23 (Just Dragon) | |
, Person def "Miyu" 10 Nothing | |
, Person { pid = def, name = "Brad", age = 31, pet = Nothing } | |
] | |
adultsAndTheirPets <- query $ getAdultsAndTheirPets | |
liftIO $ print adultsAndTheirPets -- ["Velvet" :*: Just Dog,"Kobayashi" :*: Just Dragon,"Brad" :*: Nothing] | |
liftIO $ print compiledPetsForEveryone -- ("UPDATE \"people\" SET \"pet\" = CAST($1 AS TEXT) WHERE (\"pet\") IS NULL",[Param "Dog"]) | |
numUpdates <- petsForEveryone | |
liftIO $ print numUpdates -- 2 | |
adultsAndTheirPets <- query $ getAdultsAndTheirPets | |
liftIO $ print adultsAndTheirPets -- ["Velvet" :*: Just Dog,"Kobayashi" :*: Just Dragon,"Brad" :*: Just Dog] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment