summaryrefslogtreecommitdiff
path: root/src/Database/InfluxDB/Encode.hs
blob: 8b5f9b4099de7aab0f40acd0cc1de0f36a957be2 (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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Database.InfluxDB.Encode
  ( ToSeries(..)
  , ToSeriesData(..), toSeriesData
  , ToValue(..)
  ) where
import Data.Int (Int8, Int16, Int32, Int64)
import Data.Proxy
import Data.Vector (Vector)
import Data.Word (Word8, Word16, Word32)
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL

import Database.InfluxDB.Types

-- | A type that can be converted to a 'Series'.
class ToSeries a where
  toSeries :: a -> Series

-- | A type that can be converted to a 'SeriesData'. A typical implementation is
-- as follows.
--
-- > import qualified Data.Vector as V
-- >
-- > data Event = Event Text EventType
-- > data EventType = Login | Logout
-- >
-- > instance ToSeriesData where
-- >   toSeriesColumn _ = V.fromList ["user", "type"]
-- >   toSeriesPoints (Event user ty) = V.fromList [toValue user, toValue ty]
-- >
-- > instance ToValue EventType
class ToSeriesData a where
  -- | Column names. You can safely ignore the proxy agument.
  toSeriesColumns :: Proxy a -> Vector Column
  -- | Data points.
  toSeriesPoints :: a -> Vector Value

toSeriesData :: forall a. ToSeriesData a => a -> SeriesData
toSeriesData a = SeriesData
  { seriesDataColumns = toSeriesColumns (Proxy :: Proxy a)
  , seriesDataPoints = [toSeriesPoints a]
  }

-- | A type that can be stored in InfluxDB.
class ToValue a where
  toValue :: a -> Value

instance ToValue Value where
  toValue = id

instance ToValue Bool where
  toValue = Bool

instance ToValue a => ToValue (Maybe a) where
  toValue Nothing = Null
  toValue (Just a) = toValue a

instance ToValue Int where
  toValue = Int . fromIntegral

instance ToValue Int8 where
  toValue = Int . fromIntegral

instance ToValue Int16 where
  toValue = Int . fromIntegral

instance ToValue Int32 where
  toValue = Int . fromIntegral

instance ToValue Int64 where
  toValue = Int

instance ToValue Word8 where
  toValue = Int . fromIntegral

instance ToValue Word16 where
  toValue = Int . fromIntegral

instance ToValue Word32 where
  toValue = Int . fromIntegral

instance ToValue Double where
  toValue = Float

instance ToValue T.Text where
  toValue = String

instance ToValue TL.Text where
  toValue = String . TL.toStrict

instance ToValue String where
  toValue = String . T.pack