module Data.HMemDb.TableVars
(TableVar, TableVarS(TableVar), deleteTV, forTV, insert, modifyTV, readTV) where
import Control.Applicative (Applicative)
import Control.Compose (Id(Id), unId)
import Control.Monad (mplus, mzero)
import Data.Foldable (Foldable, for_)
import Data.HMemDb.Binary (MS)
import Data.HMemDb.RefConverter (rcTo)
import Data.HMemDb.References (Ref, deRef)
import Data.HMemDb.Tables
(PreTable(tabConv), Table(Table), deleteFromTable, insertIntoTable, modifyInTable)
data TableVarS s a where
TableVar :: s (Ref r) -> PreTable r a -> TableVarS s a
type TableVar = TableVarS Id
readTV :: TableVar a -> MS a
readTV (TableVar iref pt) =
do let ref = unId iref
r <- deRef ref
rcTo (tabConv pt) r `mplus` (deleteFromTable ref pt >> mzero)
deleteTV :: TableVar a -> MS a
deleteTV (TableVar iref pt) = deleteFromTable (unId iref) pt
modifyTV :: a -> TableVar a -> MS a
modifyTV new (TableVar iref pt) = modifyInTable new (unId iref) pt
insert :: a -> Table a -> MS (TableVar a)
insert a (Table pt) =
do ref <- insertIntoTable a pt
return $ TableVar (Id ref) pt
forTV :: (Foldable s, Applicative f) => (TableVar a -> f b) -> TableVarS s a -> f ()
forTV h (TableVar s pt) = for_ s $ \ref -> h $ TableVar (Id ref) pt