-- Hoogle documentation, generated by Haddock
-- See Hoogle, http://www.haskell.org/hoogle/


-- | Client driver for RethinkDB
--   
--   This is an alternative client driver for RethinkDB. It is not complete
--   yet, but the basic structure is in place and the driver can make
--   simple queries.
--   
--   Its main focus is on type safety, which it achieves quite well. It
--   also uses the new JSON protocol which should give it a speed boost
--   (and make the driver compatible with GHC 7.8).
--   
--   Note that the driver is neither thread-safe nor reentrant. If you have
--   a multi-threaded application, I recommend using 'resource-pool'.
@package rethinkdb-client-driver
@version 0.0.23


-- | Functions to mechanically derive <a>ToDatum</a> and <a>FromDatum</a>
--   instances. Note that you need to enable the <tt>TemplateHaskell</tt>
--   language extension in order to use this module.
--   
--   An example shows how instances are generated for arbitrary data types.
--   First we define a data type:
--   
--   <pre>
--   data D a = Nullary
--            | Unary Int
--            | Product String Char a
--            | Record { testOne   :: Double
--                     , testTwo   :: Bool
--                     , testThree :: D a
--                     } deriving Eq
--   </pre>
--   
--   Next we derive the necessary instances. Note that we make use of the
--   feature to change record field names. In this case we drop the first 4
--   characters of every field name. We also modify constructor names by
--   lower-casing them:
--   
--   <pre>
--   $(<a>deriveDatum</a> <a>defaultOptions</a>{<a>fieldLabelModifier</a> = <tt>drop</tt> 4, <a>constructorTagModifier</a> = map toLower} ''D)
--   </pre>
--   
--   Now we can use the newly created instances.
--   
--   <pre>
--   d :: D <a>Int</a>
--   d = Record { testOne = 3.14159
--              , testTwo = <a>True</a>
--              , testThree = Product "test" 'A' 123
--              }
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; fromDatum (toDatum d) == Success d
--   &gt; True
--   </pre>
--   
--   Please note that you can derive instances for tuples using the
--   following syntax:
--   
--   <pre>
--   -- FromDatum and ToDatum instances for 4-tuples.
--   $(<a>deriveDatum</a> <a>defaultOptions</a> ''(,,,))
--   </pre>
module Database.RethinkDB.TH

-- | Options that specify how to encode/decode your datatype to/from JSON.
data Options :: *
Options :: (String -> String) -> (String -> String) -> Bool -> Bool -> SumEncoding -> Bool -> Options

-- | Function applied to field labels. Handy for removing common record
--   prefixes for example.
[fieldLabelModifier] :: Options -> String -> String

-- | Function applied to constructor tags which could be handy for
--   lower-casing them for example.
[constructorTagModifier] :: Options -> String -> String

-- | If <a>True</a> the constructors of a datatype, with <i>all</i> nullary
--   constructors, will be encoded to just a string with the constructor
--   tag. If <a>False</a> the encoding will always follow the
--   <a>sumEncoding</a>.
[allNullaryToStringTag] :: Options -> Bool

-- | If <a>True</a> record fields with a <a>Nothing</a> value will be
--   omitted from the resulting object. If <a>False</a> the resulting
--   object will include those fields mapping to <tt>null</tt>.
[omitNothingFields] :: Options -> Bool

-- | Specifies how to encode constructors of a sum datatype.
[sumEncoding] :: Options -> SumEncoding

-- | Hide the field name when a record constructor has only one field, like
--   a newtype.
[unwrapUnaryRecords] :: Options -> Bool

-- | Specifies how to encode constructors of a sum datatype.
data SumEncoding :: *

-- | A constructor will be encoded to an object with a field
--   <a>tagFieldName</a> which specifies the constructor tag (modified by
--   the <a>constructorTagModifier</a>). If the constructor is a record the
--   encoded record fields will be unpacked into this object. So make sure
--   that your record doesn't have a field with the same label as the
--   <a>tagFieldName</a>. Otherwise the tag gets overwritten by the encoded
--   value of that field! If the constructor is not a record the encoded
--   constructor contents will be stored under the <a>contentsFieldName</a>
--   field.
TaggedObject :: String -> String -> SumEncoding
[tagFieldName] :: SumEncoding -> String
[contentsFieldName] :: SumEncoding -> String

-- | Constructor names won't be encoded. Instead only the contents of the
--   constructor will be encoded as if the type had a single constructor.
--   JSON encodings have to be disjoint for decoding to work properly.
--   
--   When decoding, constructors are tried in the order of definition. If
--   some encodings overlap, the first one defined will succeed.
--   
--   <i>Note:</i> Nullary constructors are encoded as strings (using
--   <a>constructorTagModifier</a>). Having a nullary constructor alongside
--   a single field constructor that encodes to a string leads to
--   ambiguity.
--   
--   <i>Note:</i> Only the last error is kept when decoding, so in the case
--   of malformed JSON, only an error for the last constructor will be
--   reported.
UntaggedValue :: SumEncoding

-- | A constructor will be encoded to an object with a single field named
--   after the constructor tag (modified by the
--   <a>constructorTagModifier</a>) which maps to the encoded contents of
--   the constructor.
ObjectWithSingleField :: SumEncoding

-- | A constructor will be encoded to a 2-element array where the first
--   element is the tag of the constructor (modified by the
--   <a>constructorTagModifier</a>) and the second element the encoded
--   contents of the constructor.
TwoElemArray :: SumEncoding

-- | Default encoding <a>Options</a>:
--   
--   <pre>
--   <a>Options</a>
--   { <a>fieldLabelModifier</a>      = id
--   , <a>constructorTagModifier</a>  = id
--   , <a>allNullaryToStringTag</a>   = True
--   , <a>omitNothingFields</a>       = False
--   , <a>sumEncoding</a>             = <a>defaultTaggedObject</a>
--   , <a>unwrapUnaryRecords</a>      = False
--   }
--   </pre>
defaultOptions :: Options

-- | Default <a>TaggedObject</a> <a>SumEncoding</a> options:
--   
--   <pre>
--   defaultTaggedObject = <a>TaggedObject</a>
--                         { <a>tagFieldName</a>      = "tag"
--                         , <a>contentsFieldName</a> = "contents"
--                         }
--   </pre>
defaultTaggedObject :: SumEncoding

-- | Generates both <a>ToDatum</a> and <a>FromDatum</a> instance
--   declarations for the given data type.
--   
--   This is a convienience function which is equivalent to calling both
--   <a>deriveToDatum</a> and <a>deriveFromDatum</a>.
deriveDatum :: Options -> Name -> Q [Dec]

-- | Generates a <a>ToDatum</a> instance declaration for the given data
--   type.
deriveToDatum :: Options -> Name -> Q [Dec]

-- | Generates a <a>FromDatum</a> instance declaration for the given data
--   type.
deriveFromDatum :: Options -> Name -> Q [Dec]

-- | Generates a lambda expression which encodes the given data type as
--   Datum.
mkToDatum :: Options -> Name -> Q Exp

-- | Generates a lambda expression which parses the Datum encoding of the
--   given data type.
mkParseDatum :: Options -> Name -> Q Exp
instance Database.RethinkDB.Types.Datum.FromDatum a => Database.RethinkDB.TH.LookupField a
instance Database.RethinkDB.Types.Datum.FromDatum a => Database.RethinkDB.TH.LookupField (GHC.Base.Maybe a)

module Database.RethinkDB
data Handle

-- | The default port where RethinkDB accepts client driver connections.
defaultPort :: Int

-- | Create a new handle to the RethinkDB server.
newHandle :: Text -> Int -> Maybe Text -> Exp Database -> IO Handle

-- | The <a>Database</a> which some expressions will use when not
--   explicitly given one (eg. <a>Table</a>).
handleDatabase :: Handle -> Exp Database

-- | Close the given handle. You MUST NOT use the handle after this.
close :: Handle -> IO ()
serverInfo :: Handle -> IO (Either Error ServerInfo)

-- | Start a new query and wait for its (first) result. If the result is an
--   single value (<a>Datum</a>), then there will be no further results. If
--   it is a sequence, then you must consume results until the sequence
--   ends.
run :: (FromResponse (Result a)) => Handle -> Exp a -> IO (Res a)

-- | Get the next chunk of a sequence. It is an error to request the next
--   chunk if the sequence is already <a>Done</a>,
nextChunk :: (FromResponse (Sequence a)) => Handle -> Sequence a -> IO (Either Error (Sequence a))

-- | Collect all the values in a sequence and make them available as a
--   'Vector a'.
collect :: (FromDatum a) => Handle -> Sequence a -> IO (Either Error (Vector a))

-- | Start a new query. Returns the <a>Token</a> which can be used to track
--   its progress.
start :: Handle -> Exp a -> IO Token

-- | Let the server know that it can send the next response corresponding
--   to the given token.
continue :: Handle -> Token -> IO ()

-- | Stop (abort?) a query.
stop :: Handle -> Token -> IO ()

-- | Wait until a previous query (which was started with the
--   <tt>noreply</tt> option) finishes.
wait :: Handle -> Token -> IO ()
nextResult :: (FromResponse a) => Handle -> Token -> IO (Either Error a)

-- | A token is used to refer to queries and the corresponding responses.
--   This driver uses a monotonically increasing counter.
type Token = Word64

-- | Errors include a plain-text description which includes further
--   details. The RethinkDB protocol also includes a backtrace which we
--   currently don't parse.
data Error

-- | An error on the protocol level. Perhaps the socket was closed
--   unexpectedly, or the server sent a message which the driver could not
--   parse.
ProtocolError :: !Text -> Error

-- | Means the client is buggy. An example is if the client sends a
--   malformed protobuf, or tries to send [CONTINUE] for an unknown token.
ClientError :: !Text -> Error

-- | Means the query failed during parsing or type checking. For example,
--   if you pass too many arguments to a function.
CompileError :: !Text -> Error

-- | Means the query failed at runtime. An example is if you add together
--   two values from a table, but they turn out at runtime to be booleans
--   rather than numbers.
RuntimeError :: !Text -> Error
data Response
Response :: !Token -> !ResponseType -> !(Vector Value) -> !(Set ResponseNote) -> Response
[responseToken] :: Response -> !Token
[responseType] :: Response -> !ResponseType
[responseResult] :: Response -> !(Vector Value)
[responseNotes] :: Response -> !(Set ResponseNote)
data ChangeNotification
ChangeNotification :: !Datum -> !Datum -> ChangeNotification
[cnOldValue] :: ChangeNotification -> !Datum
[cnNewValue] :: ChangeNotification -> !Datum

-- | A sumtype covering all the primitive types which can appear in queries
--   or responses.
--   
--   It is similar to the aeson <a>Value</a> type, except that RethinkDB
--   has a few more types (like <a>Time</a>), which have a special encoding
--   in JSON.
data Datum
Null :: Datum
Bool :: !Bool -> Datum
Number :: !Double -> Datum
String :: !Text -> Datum
Array :: !(Array Datum) -> Datum
Object :: !Object -> Datum
Time :: !ZonedTime -> Datum

-- | Arrays are vectors of <a>Datum</a>.
type Array a = Vector a

-- | Objects are maps from <a>Text</a> to <a>Datum</a>. Like
--   <tt>Aeson</tt>, we're using a strict <a>HashMap</a>.
type Object = HashMap Text Datum

-- | Types which can be converted to or from a <a>Datum</a>.
class ToDatum a
toDatum :: ToDatum a => a -> Datum
class FromDatum a
parseDatum :: FromDatum a => Datum -> Parser a
(.=) :: ToDatum a => Text -> a -> (Text, Datum)
(.:) :: FromDatum a => HashMap Text Datum -> Text -> Parser a
(.:?) :: FromDatum a => HashMap Text Datum -> Text -> Parser (Maybe a)
object :: [(Text, Datum)] -> Datum
data Exp a
[Constant] :: (ToDatum a) => a -> Exp a
[MkArray] :: [Exp a] -> Exp (Array a)
[ListDatabases] :: Exp (Array Text)
[CreateDatabase] :: Exp Text -> Exp Object
[DropDatabase] :: Exp Text -> Exp Object
[WaitDatabase] :: Exp Database -> Exp Object
[ListTables] :: Exp Database -> Exp (Array Text)
[CreateTable] :: Exp Database -> Exp Text -> Exp Object
[DropTable] :: Exp Database -> Exp Text -> Exp Object
[WaitTable] :: Exp Table -> Exp Object
[ListIndices] :: Exp Table -> Exp (Array Text)
[CreateIndex] :: (IsDatum a) => Exp Table -> Exp Text -> (Exp Object -> Exp a) -> Exp Object
[DropIndex] :: Exp Table -> Exp Text -> Exp Object
[IndexStatus] :: Exp Table -> [Exp Text] -> Exp (Array Object)
[WaitIndex] :: Exp Table -> [Exp Text] -> Exp (Array Object)
[Database] :: Exp Text -> Exp Database
[Table] :: Maybe (Exp Database) -> Exp Text -> Exp Table
[Coerce] :: Exp a -> Exp Text -> Exp b
[Eq] :: (IsDatum a, IsDatum b) => Exp a -> Exp b -> Exp Bool
[Ne] :: (IsDatum a, IsDatum b) => Exp a -> Exp b -> Exp Bool
[Not] :: Exp Bool -> Exp Bool
[Match] :: Exp Text -> Exp Text -> Exp Datum
[Get] :: Exp Table -> Exp Text -> Exp SingleSelection
[GetAll] :: (IsDatum a) => Exp Table -> [Exp a] -> Exp (Array Datum)
[GetAllIndexed] :: (IsDatum a) => Exp Table -> [Exp a] -> Text -> Exp (Sequence Datum)
[Add] :: (Num a) => [Exp a] -> Exp a
[Sub] :: (Num a) => [Exp a] -> Exp a
[Multiply] :: (Num a) => [Exp a] -> Exp a
[All] :: [Exp Bool] -> Exp Bool
[Any] :: [Exp Bool] -> Exp Bool
[GetField] :: (IsObject a, IsDatum r) => Exp Text -> Exp a -> Exp r
[HasFields] :: (IsObject a) => [Text] -> Exp a -> Exp Bool
[Take] :: (IsSequence s) => Exp Double -> Exp s -> Exp s
[Append] :: (IsDatum a) => Exp (Array a) -> Exp a -> Exp (Array a)
[Prepend] :: (IsDatum a) => Exp (Array a) -> Exp a -> Exp (Array a)
[IsEmpty] :: (IsSequence a) => Exp a -> Exp Bool
[Delete] :: Exp a -> Exp Object
[InsertObject] :: ConflictResolutionStrategy -> Exp Table -> Object -> Exp Object
[InsertSequence] :: (IsSequence s) => Exp Table -> Exp s -> Exp Object
[Filter] :: (IsSequence s) => (Exp a -> Exp Bool) -> Exp s -> Exp s
[Map] :: (IsSequence s) => (Exp a -> Exp b) -> Exp s -> Exp (Sequence b)
[Between] :: (IsSequence s) => (Bound, Bound) -> Exp s -> Exp s
[BetweenIndexed] :: (IsSequence s) => Text -> (Bound, Bound) -> Exp s -> Exp s
[OrderBy] :: (IsSequence s) => [Order] -> Exp s -> Exp s
[OrderByIndexed] :: (IsSequence s) => Order -> Exp s -> Exp s
[Keys] :: (IsObject a) => Exp a -> Exp (Array Text)
[Var] :: Int -> Exp a
[Function] :: State Context ([Int], Exp a) -> Exp f
[Call] :: Exp f -> [SomeExp] -> Exp r
[Limit] :: (IsSequence s) => Double -> Exp s -> Exp s
[Nth] :: (IsSequence s, IsDatum r) => Double -> Exp s -> Exp r
[UUID] :: Exp Text
[Now] :: Exp ZonedTime
[Timezone] :: Exp ZonedTime -> Exp Text
[RandomInteger] :: Exp Int -> Exp Int -> Exp Int
[RandomFloat] :: Exp Double -> Exp Double -> Exp Double
[Info] :: Exp a -> Exp Object
[Default] :: Exp a -> Exp a -> Exp a
[Error] :: Exp Text -> Exp a
[SequenceChanges] :: (IsSequence s) => Exp s -> Exp (Sequence ChangeNotification)
[SingleSelectionChanges] :: (IsDatum a) => Exp a -> Exp (Sequence ChangeNotification)

-- | Because the arguments to functions are polymorphic (the individual
--   arguments can, and often have, different types).
data SomeExp
[SomeExp] :: Exp a -> SomeExp

-- | Bounds are used in <a>Between</a>.
data Bound
Open :: !Datum -> Bound
Closed :: !Datum -> Bound

-- | Used in <a>OrderBy</a>.
data Order
Ascending :: !Text -> Order
Descending :: !Text -> Order

-- | Sequences are a bounded list of items. The server may split the
--   sequence into multiple chunks when sending it to the client. When the
--   response is a partial sequence, the client may request additional
--   chunks until it gets a <a>Done</a>.
data Sequence a
Done :: !(Vector a) -> Sequence a
Partial :: !Token -> !(Vector a) -> Sequence a

-- | Tables are something you can select objects from.
--   
--   This type is not exported, and merely serves as a sort of phantom
--   type. On the client tables are converted to a <a>Sequence</a>.
data Table

-- | A <a>Database</a> is something which contains tables. It is a
--   server-only type.
data Database

-- | <a>SingleSelection</a> is essentially a 'Maybe Object', where
--   <a>Nothing</a> is represented with <a>Null</a> in the network
--   protocol.
data SingleSelection

-- | The result of a query. It is either an error or a result (which
--   depends on the type of the query expression). This type is named to be
--   symmetrical to <a>Exp</a>, so we get this nice type for <tt>run</tt>.
--   
--   <pre>
--   run :: Handle -&gt; Exp a -&gt; IO (Res a)
--   </pre>
type Res a = Either Error (Result a)

-- | The type of result you get when executing a query of 'Exp a'.

-- | A value which can be converted from a <a>Response</a>. All types which
--   are defined as being a 'Result a' should have a 'FromResponse a'.
--   Because, uhm.. you really want to be able to extract the result from
--   the response.
--   
--   There are two parsers defined here, one for atoms and the other for
--   sequences. These are the only two implementations of parseResponse
--   which should be used.
class FromResponse a

-- | ConflictResolutionStrategy
--   
--   How conflicts should be resolved.
data ConflictResolutionStrategy

-- | Do not insert the new document and record the conflict as an error.
--   This is the default.
CRError :: ConflictResolutionStrategy

-- | Replace the old document in its entirety with the new one.
CRReplace :: ConflictResolutionStrategy

-- | Update fields of the old document with fields from the new one.
CRUpdate :: ConflictResolutionStrategy
emptyOptions :: Object
lift :: Lift c e => e -> c (Simplified e)

-- | Call an unary function with the given argument.
call1 :: (Exp a -> Exp r) -> Exp a -> Exp r

-- | Call an binary function with the given arguments.
call2 :: (Exp a -> Exp b -> Exp r) -> Exp a -> Exp b -> Exp r
class IsDatum a

-- | Objects are maps from <a>Text</a> to <a>Datum</a>. Like
--   <tt>Aeson</tt>, we're using <a>HashMap</a>.
class (IsDatum a) => IsObject a
class IsSequence a
