forked from commercialhaskell/stack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtil.hs
More file actions
69 lines (66 loc) · 2.14 KB
/
Util.hs
File metadata and controls
69 lines (66 loc) · 2.14 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeFamilies #-}
-- | Utils for the other Stack.Storage modules
module Stack.Storage.Util
( updateList
, updateSet
) where
import qualified Data.Set as Set
import Database.Persist
import Stack.Prelude hiding (MigrationFailure)
-- | Efficiently update a set of values stored in a database table
updateSet ::
( PersistEntityBackend record ~ BaseBackend backend
, PersistField parentid
, PersistField value
, Ord value
, PersistEntity record
, MonadIO m
, PersistQueryWrite backend
)
=> (parentid -> value -> record)
-> EntityField record parentid
-> parentid
-> EntityField record value
-> Set value
-> Set value
-> ReaderT backend m ()
updateSet recordCons parentFieldCons parentId valueFieldCons old new =
when (old /= new) $ do
deleteWhere
[ parentFieldCons ==. parentId
, valueFieldCons <-. Set.toList (Set.difference old new)
]
insertMany_ $
map (recordCons parentId) $ Set.toList (Set.difference new old)
-- | Efficiently update a list of values stored in a database table.
updateList ::
( PersistEntityBackend record ~ BaseBackend backend
, PersistField parentid
, Ord value
, PersistEntity record
, MonadIO m
, PersistQueryWrite backend
)
=> (parentid -> Int -> value -> record)
-> EntityField record parentid
-> parentid
-> EntityField record Int
-> [value]
-> [value]
-> ReaderT backend m ()
updateList recordCons parentFieldCons parentId indexFieldCons old new =
when (old /= new) $ do
let oldSet = Set.fromList (zip [0 ..] old)
newSet = Set.fromList (zip [0 ..] new)
deleteWhere
[ parentFieldCons ==. parentId
, indexFieldCons <-.
map fst (Set.toList $ Set.difference oldSet newSet)
]
insertMany_ $
map (uncurry $ recordCons parentId) $
Set.toList (Set.difference newSet oldSet)