aboutsummaryrefslogtreecommitdiff
path: root/src/server/Job/Model.hs
blob: e1a3c773a502307455e0e575594fad097a3271d7 (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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
{-# LANGUAGE OverloadedStrings #-}

module Job.Model
  ( Job(..)
  , getLastExecution
  , actualizeLastExecution
  , actualizeLastCheck
  ) where

import Data.Maybe (isJust)
import Data.Time.Clock (UTCTime, getCurrentTime)
import Database.SQLite.Simple (Only(Only))
import qualified Database.SQLite.Simple as SQLite
import Prelude hiding (id)

import Job.Kind
import Model.Query (Query(Query))

data Job = Job
  { id :: String
  , kind :: Kind
  , lastExecution :: Maybe UTCTime
  , lastCheck :: Maybe UTCTime
  } deriving (Show)

getLastExecution :: Kind -> Query (Maybe UTCTime)
getLastExecution jobKind =
  Query (\conn -> do
    [Only time] <- SQLite.query conn "SELECT last_execution FROM job WHERE kind = ?" (Only jobKind) :: IO [Only (Maybe UTCTime)]
    return time
  )

actualizeLastExecution :: Kind -> UTCTime -> Query ()
actualizeLastExecution jobKind time =
  Query (\conn -> do
    [Only result] <- SQLite.query conn "SELECT 1 FROM job WHERE kind = ?" (Only jobKind) :: IO [Only (Maybe Int)]
    if isJust result
      then SQLite.execute conn "UPDATE job SET last_execution = ? WHERE kind = ?" (time, jobKind)
      else SQLite.execute conn "INSERT INTO job (kind, last_execution, last_check) VALUES (?, ?, ?)" (jobKind, time, time)
  )

actualizeLastCheck :: Kind -> Query ()
actualizeLastCheck jobKind =
  Query (\conn -> do
    now <- getCurrentTime
    SQLite.execute conn "UPDATE job SET kind = ? WHERE last_check = ?" (jobKind, now)
  )