summaryrefslogtreecommitdiff
path: root/haskell/src/SpaceTraders/Database/Contracts.hs
blob: 7cebc37051e9b17edb8a40fa423bf9396cccc3d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{-# LANGUAGE OverloadedStrings #-}

module SpaceTraders.Database.Contracts
  ( getContracts
  , setContract
  ) where

import           Control.Monad.Error.Class
import           Control.Monad.Reader
import           Data.Aeson
import qualified Database.SQLite.Simple      as S

import           SpaceTraders
import           SpaceTraders.Model.Contract
import           SpaceTraders.Utils

getContracts :: (HasDatabaseConn env, MonadIO m, MonadReader env m) => m [Contract]
getContracts = query_ "SELECT data FROM contracts;"

setContract :: (HasDatabaseConn env, MonadError e m, MonadIO m, MonadReader env m) => Contract -> m ()
setContract contract = updateContract `catchError` addContract
  where
    addContract _ = execute "INSERT INTO contracts(data) VALUES (json(?));" (S.Only (encode contract))
    updateContract = execute "UPDATE contracts SET data = json(?) WHERE data->>'contractId' = ?;" (encode contract, contractId contract)