-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | A driver for MongoDB -- -- This module lets you connect to MongoDB (www.mongodb.org) and do -- inserts, queries, updates, etc. @package mongoDB @version 0.9 -- | Miscellaneous general functions and Show, Eq, and Ord instances for -- PortID module Database.MongoDB.Internal.Util -- | bit-or all numbers together bitOr :: Bits a => [a] -> a -- | Concat first and second together with period in between. Eg. -- "hello" <.> "world" = "hello.world" (<.>) :: UString -> UString -> UString -- | Is field's value a 1 or True (MongoDB use both Int and Bools for truth -- values). Error if field not in document or field not a Num or Bool. true1 :: Label -> Document -> Bool -- | Read N bytes from hande, blocking until all N bytes are read. If EOF -- is reached before N bytes then raise EOF exception. hGetN :: Handle -> Int -> IO ByteString instance Ord PortID instance Eq PortID instance Show PortID -- | Generalize a network connection to a sink and source module Network.Abstract type IOE = ErrorT IOError IO type Server = (HostName, PortID) -- | A network controls connections to other hosts. It may want to overide -- to log messages or play them back. A server in the network accepts -- messages of type i and generates messages of type o. class Network n i o connect :: Network n i o => n -> Server -> IOE (Connection i o) data Connection i o Connection :: (i -> IOE ()) -> IOE o -> IO () -> Connection i o send :: Connection i o -> i -> IOE () receive :: Connection i o -> IOE o close :: Connection i o -> IO () data ANetwork i o ANetwork :: n -> ANetwork i o instance Network (ANetwork i o) i o -- | Extra monad functions and instances module Control.Monad.Util -- | MonadIO with extra Applicative and Functor superclasses class (MonadIO m, Applicative m, Functor m) => MonadIO' m -- | Repeatedy execute action, collecting results, until it returns Nothing loop :: (Functor m, Monad m) => m (Maybe a) -> m [a] -- | Apply action to elements one at a time until one returns Just. Return -- Nothing if all return Nothing. untilJust :: Monad m => (a -> m (Maybe b)) -> [a] -> m (Maybe b) -- | Apply action to elements one at a time until one succeeds. Throw last -- error if all fail. Throw strMsg error if list is empty. untilSuccess :: (MonadError e m, Error e) => (a -> m b) -> [a] -> m b -- | Apply action to elements one at a time until one succeeds. Throw last -- error if all fail. Throw given error if list is empty untilSuccess' :: MonadError e m => e -> (a -> m b) -> [a] -> m b -- | Convert error type thrown mapError :: Functor m => (e' -> e) -> ErrorT e' m a -> ErrorT e m a whenJust :: Monad m => Maybe a -> (a -> m ()) -> m () instance (MonadIO m, Applicative m, Functor m) => MonadIO' m -- | This is just like Control.Monad.Error.Class except you can -- throw/catch the error of any ErrorT in the monad stack instead of just -- the top one as long as the error types are different. If two or more -- ErrorTs in the stack have the same error type you get the error of the -- top one. module Control.Monad.Throw -- | Same as MonadError but without functional dependency so the -- same monad can have multiple errors with different types class Monad m => Throw e m throw :: Throw e m => e -> m a catch :: Throw e m => m a -> (e -> m a) -> m a -- | Execute action and throw exception if result is Left, otherwise return -- the Right result throwLeft :: Throw e m => m (Either e a) -> m a -- | Execute action and throw transformed exception if result is Left, -- otherwise return Right result throwLeft' :: Throw e m => (x -> e) -> m (Either x a) -> m a -- | If first action throws an exception then run second action then -- re-throw onException :: Throw e m => m a -> (e -> m b) -> m a -- | Convert error type mapError :: Functor m => (e -> e') -> ErrorT e m a -> ErrorT e' m a instance [overlap ok] Throw e m => Throw e (ReaderT x m) instance [overlap ok] (Error e, Throw e m, Error x) => Throw e (ErrorT x m) instance [overlap ok] (Error e, Monad m) => Throw e (ErrorT e m) instance [overlap ok] Error e => Throw e (Either e) -- | Lift MVar operations so you can do them within monads stacked on top -- of IO. Analogous to MonadIO module Control.Monad.MVar -- | An MVar (pronounced "em-var") is a synchronising variable, used -- for communication between concurrent threads. It can be thought of as -- a a box, which may be empty or full. data MVar a :: * -> * newEmptyMVar :: MonadIO m => m (MVar a) newMVar :: MonadIO m => a -> m (MVar a) takeMVar :: MonadIO m => MVar a -> m a putMVar :: MonadIO m => MVar a -> a -> m () readMVar :: MonadIO m => MVar a -> m a swapMVar :: MonadIO m => MVar a -> a -> m a tryTakeMVar :: MonadIO m => MVar a -> m (Maybe a) tryPutMVar :: MonadIO m => MVar a -> a -> m Bool isEmptyMVar :: MonadIO m => MVar a -> m Bool class MonadIO m => MonadMVar m modifyMVar :: MonadMVar m => MVar a -> (a -> m (a, b)) -> m b addMVarFinalizer :: MonadMVar m => MVar a -> m () -> m () modifyMVar_ :: MonadMVar m => MVar a -> (a -> m a) -> m () withMVar :: MonadMVar m => MVar a -> (a -> m b) -> m b -- | Lift a computation from the IO monad. liftIO :: MonadIO m => forall a. IO a -> m a instance MonadMVar m => MonadMVar (StateT s m) instance MonadMVar m => MonadMVar (ReaderT r m) instance (MonadMVar m, Error e) => MonadMVar (ErrorT e m) instance MonadMVar IO -- | Pipelining is sending multiple requests over a socket and receiving -- the responses later, in the same order. This is faster than sending -- one request, waiting for the response, then sending the next request, -- and so on. This implementation returns a promise (future) -- response for each request that when invoked waits for the response if -- not already arrived. Multiple threads can send on the same pipeline -- (and get promises back); it will pipeline each thread's request right -- away without waiting. -- -- A pipeline closes itself when a read or write causes an error, so you -- can detect a broken pipeline by checking isClosed. It also closes -- itself when garbage collected, or you can close it explicitly. module Control.Pipeline -- | Thread-safe and pipelined connection data Pipeline i o -- | Create new Pipeline on given connection. You should close -- pipeline when finished, which will also close connection. If pipeline -- is not closed but eventually garbage collected, it will be closed -- along with connection. newPipeline :: MonadIO m => Connection i o -> m (Pipeline i o) -- | Send message to destination; the destination must not response -- (otherwise future calls will get these responses instead of -- their own). Throw IOError and close pipeline if send fails send :: Pipeline i o -> i -> IOE () -- | Send message to destination and return promise of response from -- one message only. The destination must reply to the message (otherwise -- promises will have the wrong responses in them). Throw IOError and -- closes pipeline if send fails, likewise for promised response. call :: Pipeline i o -> i -> IOE (IOE o) close :: MonadIO m => Pipeline i o -> m () -- | Close pipe and underlying connection isClosed :: MonadIO m => Pipeline i o -> m Bool -- | Low-level messaging between this client and the MongoDB server, see -- Mongo Wire Protocol -- (http://www.mongodb.org/display/DOCS/Mongo+Wire+Protocol). -- -- This module is not intended for direct use. Use the high-level -- interface at Database.MongoDB.Query and -- Database.MongoDB.Connection instead. module Database.MongoDB.Internal.Protocol class Network n Message Response => Network' n type ANetwork' = ANetwork Message Response -- | Normal Network instance, i.e. no logging or replay data Internet Internet :: Internet -- | Thread-safe TCP connection with pipelined requests type Pipe = Pipeline Message Response -- | Send notices as a contiguous batch to server with no reply. Throw -- IOError if connection fails. send :: Pipe -> [Notice] -> IOE () -- | Send notices and request as a contiguous batch to server and return -- reply promise, which will block when invoked until reply arrives. This -- call and resulting promise will throw IOError if connection fails. call :: Pipe -> [Notice] -> Request -> IOE (IOE Reply) -- | Database name and collection name with period (.) in between. Eg. -- "myDb.myCollection" type FullCollection = UString -- | A notice is a message that is sent with no reply data Notice Insert :: FullCollection -> [Document] -> Notice iFullCollection :: Notice -> FullCollection iDocuments :: Notice -> [Document] Update :: FullCollection -> [UpdateOption] -> Document -> Document -> Notice uFullCollection :: Notice -> FullCollection uOptions :: Notice -> [UpdateOption] uSelector :: Notice -> Document uUpdater :: Notice -> Document Delete :: FullCollection -> [DeleteOption] -> Document -> Notice dFullCollection :: Notice -> FullCollection dOptions :: Notice -> [DeleteOption] dSelector :: Notice -> Document KillCursors :: [CursorId] -> Notice kCursorIds :: Notice -> [CursorId] data UpdateOption -- | If set, the database will insert the supplied object into the -- collection if no matching document is found Upsert :: UpdateOption -- | If set, the database will update all matching objects in the -- collection. Otherwise only updates first matching doc MultiUpdate :: UpdateOption data DeleteOption -- | If set, the database will remove only the first matching document in -- the collection. Otherwise all matching documents will be removed SingleRemove :: DeleteOption type CursorId = Int64 -- | A request is a message that is sent with a Reply returned data Request Query :: [QueryOption] -> FullCollection -> Int32 -> Int32 -> Document -> Document -> Request qOptions :: Request -> [QueryOption] qFullCollection :: Request -> FullCollection -- | Number of initial matching documents to skip qSkip :: Request -> Int32 -- | The number of document to return in each batch response from the -- server. 0 means use Mongo default. Negative means close cursor after -- first batch and use absolute value as batch size. qBatchSize :: Request -> Int32 -- | [] = return all documents in collection qSelector :: Request -> Document -- | [] = return whole document qProjector :: Request -> Document GetMore :: FullCollection -> Int32 -> CursorId -> Request gFullCollection :: Request -> FullCollection gBatchSize :: Request -> Int32 gCursorId :: Request -> CursorId data QueryOption -- | Tailable means cursor is not closed when the last data is retrieved. -- Rather, the cursor marks the final object's position. You can resume -- using the cursor later, from where it was located, if more data were -- received. Like any latent cursor, the cursor may become invalid -- at some point for example if the final object it references were -- deleted. Thus, you should be prepared to requery on CursorNotFound -- exception. TailableCursor :: QueryOption -- | Allow query of replica slave. Normally these return an error except -- for namespace local. SlaveOK :: QueryOption NoCursorTimeout :: QueryOption -- | Use with TailableCursor. If we are at the end of the data, block for a -- while rather than returning no data. After a timeout period, we do -- return as normal. | Exhaust -- ^ Stream the data down full blast in -- multiple more packages, on the assumption that the client will -- fully read all data queried. Faster when you are pulling a lot of data -- and know you want to pull it all down. Note: the client is not allowed -- to not read all the data unless it closes the connection. AwaitData :: QueryOption -- | A reply is a message received in response to a Request data Reply Reply :: [ResponseFlag] -> CursorId -> Int32 -> [Document] -> Reply rResponseFlags :: Reply -> [ResponseFlag] -- | 0 = cursor finished rCursorId :: Reply -> CursorId rStartingFrom :: Reply -> Int32 rDocuments :: Reply -> [Document] data ResponseFlag -- | Set when getMore is called but the cursor id is not valid at the -- server. Returned with zero results. CursorNotFound :: ResponseFlag -- | Query error. Returned with one document containing an $err -- field holding the error message. QueryError :: ResponseFlag -- | For backward compatability: Set when the server supports the AwaitData -- query option. if it doesn't, a replica slave client should sleep a -- little between getMore's AwaitCapable :: ResponseFlag type Username = UString type Password = UString type Nonce = UString pwHash :: Username -> Password -> UString pwKey :: Nonce -> Username -> Password -> UString instance Show ResponseFlag instance Eq ResponseFlag instance Enum ResponseFlag instance Show Reply instance Eq Reply instance Show QueryOption instance Eq QueryOption instance Show Request instance Eq Request instance Show DeleteOption instance Eq DeleteOption instance Show UpdateOption instance Eq UpdateOption instance Show Notice instance Eq Notice instance Network Internet Message Response instance Network n Message Response => Network' n -- | Cycle through a set of resources (randomly), recreating them when they -- expire module Var.Pool -- | Creator, destroyer, and checker of resources of type r. Creator may -- throw error or type e. data Factory e r Factory :: ErrorT e IO r -> (r -> IO ()) -> (r -> IO Bool) -> Factory e r newResource :: Factory e r -> ErrorT e IO r killResource :: Factory e r -> r -> IO () isExpired :: Factory e r -> r -> IO Bool -- | Create new pool of initial max size, which must be >= 1 newPool :: Factory e r -> Int -> IO (Pool e r) -- | Pool of maximum N resources. Resources may expire on their own or be -- killed. Resources will initially be created on demand up N resources -- then recycled in random fashion. N may be changed by resizing the -- pool. Random is preferred to round-robin to distribute effect of -- pathological use cases that use every Xth resource the most and N is a -- multiple of X. Resources *must* close/kill themselves when garbage -- collected (resize relies on this). data Pool e r Pool :: Factory e r -> MVar (IOArray Int (Maybe r)) -> Pool e r factory :: Pool e r -> Factory e r resources :: Pool e r -> MVar (IOArray Int (Maybe r)) -- | Return a random live resource in pool or create new one if expired or -- not yet created aResource :: Error e => Pool e r -> ErrorT e IO r -- | current max size of pool poolSize :: Pool e r -> IO Int -- | resize max size of pool. When shrinking some resource will be dropped -- without closing since they may still be in use. They are expected to -- close themselves when garbage collected. resize :: Pool e r -> Int -> IO () -- | Kill all resources in pool so subsequent access creates new ones killAll :: Pool e r -> IO () -- | This is just like Control.Monad.Reader.Class except you can -- access the context of any Reader in the monad stack instead of just -- the top one as long as the context types are different. If two or more -- readers in the stack have the same context type you get the context of -- the top one. module Control.Monad.Context -- | Same as MonadReader but without functional dependency so the -- same monad can have multiple contexts with different types class Monad m => Context x m context :: Context x m => m x push :: Context x m => (x -> x) -> m a -> m a instance [overlap ok] (Context x m, Error e) => Context x (ErrorT e m) instance [overlap ok] Context x m => Context x (ReaderT r m) instance [overlap ok] Monad m => Context x (ReaderT x m) -- | A pool of TCP connections to a single server or a replica set of -- servers. module Database.MongoDB.Connection class Network n Message Response => Network' n type ANetwork' = ANetwork Message Response -- | Normal Network instance, i.e. no logging or replay data Internet Internet :: Internet data Host Host :: HostName -> PortID -> Host data PortID :: * Service :: String -> PortID PortNumber :: PortNumber -> PortID UnixSocket :: String -> PortID -- | Host on default MongoDB port host :: HostName -> Host -- | Display host as "host:port" showHostPort :: Host -> String -- | Read string "hostname:port" as Host hostname port or -- "hostname" as host hostname (default port). Error if string -- does not match either syntax. readHostPort :: String -> Host -- | Read string "hostname:port" as Host hosthame port or -- "hostname" as host hostname (default port). Fail if string -- does not match either syntax. readHostPortM :: Monad m => String -> m Host -- | Replica set of hosts identified by set name. At least one of the seed -- hosts must be an active member of the set. However, this list is not -- used to identify the set, just the set name. data ReplicaSet ReplicaSet :: Name -> [Host] -> ReplicaSet setName :: ReplicaSet -> Name seedHosts :: ReplicaSet -> [Host] type Name = UString data MasterOrSlaveOk -- | connect to master only Master :: MasterOrSlaveOk -- | connect to a slave, or master if no slave available SlaveOk :: MasterOrSlaveOk -- | A Server is a single server (Host) or a replica set of servers -- (ReplicaSet) class Server t where { data family ConnPool t; } newConnPool :: (Server t, Network' n, MonadIO' m) => n -> Int -> t -> m (ConnPool t) getPipe :: Server t => MasterOrSlaveOk -> ConnPool t -> IOE Pipe killPipes :: Server t => ConnPool t -> IO () newConnPool' :: (Server t, MonadIO' m, Context ANetwork' m) => Int -> t -> m (ConnPool t) connHost :: ConnPool Host -> Host -- | Return replicas set name with current members as seed list replicaSet :: MonadIO' m => ConnPool ReplicaSet -> m ReplicaSet instance Show MasterOrSlaveOk instance Eq MasterOrSlaveOk instance Show ReplicaSet instance Show Host instance Eq Host instance Ord Host instance Show (ConnPool ReplicaSet) instance Server ReplicaSet instance Show (ConnPool Host) instance Server Host instance Eq ReplicaSet -- | Query and update documents module Database.MongoDB.Query -- | Run action under given write and read mode against the server or -- replicaSet behind given connection pool. Return Left Failure if there -- is a connection failure or read/write error. access :: (Server s, MonadIO m) => WriteMode -> MasterOrSlaveOk -> ConnPool s -> Action m a -> m (Either Failure a) -- | A monad with access to a Pipe, MasterOrSlaveOk, and -- WriteMode, and throws Failure on read, write, or pipe -- failure class (Context Pipe m, Context MasterOrSlaveOk m, Context WriteMode m, Throw Failure m, MonadIO' m, MonadMVar m) => Access m -- | Monad with access to a Pipe, MasterOrSlaveOk, and -- WriteMode, and throws a Failure on read, write or pipe -- failure data Action m a -- | Run action with given write mode and read mode (master or slave-ok) -- against given pipe (TCP connection). Return Left Failure if read/write -- error or connection failure. access calls runAction. Use this -- directly if you want to use the same connection and not take from the -- pool again. However, the connection may still be used by other threads -- at the same time. For instance, the pool will still hand this -- connection out. runAction :: Action m a -> WriteMode -> MasterOrSlaveOk -> Pipe -> m (Either Failure a) -- | A connection failure, or a read or write exception like cursor expired -- or inserting a duplicate key. Note, unexpected data from the server is -- not a Failure, rather it is a programming error (you should call -- error in this case) because the client and server are -- incompatible and requires a programming change. data Failure -- | TCP connection (Pipe) failed. Make work if you try again on the -- same Mongo Connection which will create a new Pipe. ConnectionFailure :: IOError -> Failure -- | Cursor expired because it wasn't accessed for over 10 minutes, or this -- cursor came from a different server that the one you are currently -- connected to (perhaps a fail over happen between servers in a replica -- set) CursorNotFoundFailure :: CursorId -> Failure -- | Query failed for some reason as described in the string QueryFailure :: String -> Failure -- | Error observed by getLastError after a write, error description is in -- string WriteFailure :: ErrorCode -> String -> Failure -- | Database name newtype Database Database :: UString -> Database databaseName :: Database -> UString -- | List all databases residing on server allDatabases :: Access m => m [Database] -- | Access monad with a particular Database in context class (Context Database m, Access m) => DbAccess m -- | Run action against given database use :: Database -> ReaderT Database m a -> m a -- | Current database in use thisDatabase :: DbAccess m => m Database type Username = UString type Password = UString -- | Authenticate with the database (if server is running in secure mode). -- Return whether authentication was successful or not. Reauthentication -- is required for every new pipe. auth :: DbAccess m => Username -> Password -> m Bool -- | Collection name (not prefixed with database) type Collection = UString -- | List all collections in this database allCollections :: DbAccess m => m [Collection] -- | Selects documents in collection that match selector data Selection Select :: Selector -> Collection -> Selection selector :: Selection -> Selector coll :: Selection -> Collection -- | Filter for a query, analogous to the where clause in SQL. [] -- matches all documents in collection. [x =: a, y =: b] is -- analogous to where x = a and y = b in SQL. See -- http://www.mongodb.org/display/DOCS/Querying for full selector -- syntax. type Selector = Document -- | Add Javascript predicate to selector, in which case a document must -- match both selector and predicate whereJS :: Selector -> Javascript -> Selector class Select aQueryOrSelection select :: Select aQueryOrSelection => Selector -> Collection -> aQueryOrSelection -- | Default write-mode is Unsafe data WriteMode -- | Submit writes without receiving acknowledgments. Fast. Assumes writes -- succeed even though they may not. Unsafe :: WriteMode -- | Receive an acknowledgment after every write, and raise exception if -- one says the write failed. This is acomplished by sending the -- getLastError command, with given GetLastError parameters, after -- every write. Safe :: GetLastError -> WriteMode -- | Safe [] safe :: WriteMode type GetLastError = Document -- | Run action with given WriteMode writeMode :: Access m => WriteMode -> m a -> m a -- | Insert document into collection and return its "_id" value, which is -- created automatically if not supplied insert :: DbAccess m => Collection -> Document -> m Value -- | Same as insert except don't return _id insert_ :: DbAccess m => Collection -> Document -> m () -- | Insert documents into collection and return their "_id" values, which -- are created automatically if not supplied insertMany :: DbAccess m => Collection -> [Document] -> m [Value] -- | Same as insertMany except don't return _ids insertMany_ :: DbAccess m => Collection -> [Document] -> m () -- | Save document to collection, meaning insert it if its new (has no -- "_id" field) or update it if its not new (has "_id" field) save :: DbAccess m => Collection -> Document -> m () -- | Replace first document in selection with given document replace :: DbAccess m => Selection -> Document -> m () -- | Replace first document in selection with given document, or insert -- document if selection is empty repsert :: DbAccess m => Selection -> Document -> m () -- | Update operations on fields in a document. See -- http://www.mongodb.org/display/DOCS/Updating#Updating-ModifierOperations type Modifier = Document -- | Update all documents in selection using given modifier modify :: DbAccess m => Selection -> Modifier -> m () -- | Delete all documents in selection delete :: DbAccess m => Selection -> m () -- | Delete first document in selection deleteOne :: DbAccess m => Selection -> m () -- | Execute action using given read mode. Master = consistent reads, -- SlaveOk = eventually consistent reads. readMode :: Access m => MasterOrSlaveOk -> m a -> m a -- | Use select to create a basic query with defaults, then modify -- if desired. For example, (select sel col) {limit = 10} data Query Query :: [QueryOption] -> Selection -> Projector -> Word32 -> Limit -> Order -> Bool -> BatchSize -> Order -> Query -- | Default = [] options :: Query -> [QueryOption] selection :: Query -> Selection -- | [] = all fields. Default = [] project :: Query -> Projector -- | Number of initial matching documents to skip. Default = 0 skip :: Query -> Word32 -- | Maximum number of documents to return, 0 = no limit. Default = 0 limit :: Query -> Limit -- | Sort results by this order, [] = no sort. Default = [] sort :: Query -> Order -- | If true assures no duplicates are returned, or objects missed, which -- were present at both the start and end of the query's execution (even -- if the object were updated). If an object is new during the query, or -- deleted during the query, it may or may not be returned, even with -- snapshot mode. Note that short query responses (less than 1MB) are -- always effectively snapshotted. Default = False snapshot :: Query -> Bool -- | The number of document to return in each batch response from the -- server. 0 means use Mongo default. Default = 0 batchSize :: Query -> BatchSize -- | Force MongoDB to use this index, [] = no hint. Default = [] hint :: Query -> Order data QueryOption -- | Tailable means cursor is not closed when the last data is retrieved. -- Rather, the cursor marks the final object's position. You can resume -- using the cursor later, from where it was located, if more data were -- received. Like any latent cursor, the cursor may become invalid -- at some point for example if the final object it references were -- deleted. Thus, you should be prepared to requery on CursorNotFound -- exception. TailableCursor :: QueryOption NoCursorTimeout :: QueryOption -- | Use with TailableCursor. If we are at the end of the data, block for a -- while rather than returning no data. After a timeout period, we do -- return as normal. AwaitData :: QueryOption -- | Fields to return, analogous to the select clause in SQL. [] -- means return whole document (analogous to * in SQL). [x =: 1, y =: -- 1] means return only x and y fields of each -- document. [x =: 0] means return all fields except x. type Projector = Document -- | Maximum number of documents to return, i.e. cursor will close after -- iterating over this number of documents. 0 means no limit. type Limit = Word32 -- | Fields to sort by. Each one is associated with 1 or -1. Eg. [x =: -- 1, y =: -1] means sort by x ascending then y -- descending type Order = Document -- | The number of document to return in each batch response from the -- server. 0 means use Mongo default. type BatchSize = Word32 -- | Return performance stats of query execution explain :: DbAccess m => Query -> m Document -- | Fetch documents satisfying query find :: DbAccess m => Query -> m Cursor -- | Fetch first document satisfying query or Nothing if none satisfy it findOne :: DbAccess m => Query -> m (Maybe Document) -- | Fetch number of documents satisfying query (including effect of skip -- and/or limit if present) count :: DbAccess m => Query -> m Int -- | Fetch distinct values of field in selected documents distinct :: DbAccess m => Label -> Selection -> m [Value] -- | Iterator over results of a query. Use next to iterate or -- rest to get all results. A cursor is closed when it is -- explicitly closed, all results have been read from it, garbage -- collected, or not used for over 10 minutes (unless -- NoCursorTimeout option was specified in Query). Reading -- from a closed cursor raises a CursorNotFoundFailure. Note, a -- cursor is not closed when the pipe is closed, so you can open another -- pipe to the same server and continue using the cursor. data Cursor -- | Return next document in query result, or Nothing if finished. next :: Access m => Cursor -> m (Maybe Document) -- | Return next N documents or less if end is reached nextN :: Access m => Int -> Cursor -> m [Document] -- | Return remaining documents in query result rest :: Access m => Cursor -> m [Document] closeCursor :: Access m => Cursor -> m () isCursorClosed :: Access m => Cursor -> m Bool -- | Groups documents in collection by key then reduces (aggregates) each -- group data Group Group :: Collection -> GroupKey -> Javascript -> Document -> Selector -> Maybe Javascript -> Group gColl :: Group -> Collection -- | Fields to group by gKey :: Group -> GroupKey -- | (doc, agg) -> (). The reduce function reduces (aggregates) -- the objects iterated. Typical operations of a reduce function include -- summing and counting. It takes two arguments, the current document -- being iterated over and the aggregation value, and updates the -- aggregate value. gReduce :: Group -> Javascript -- | agg. Initial aggregation value supplied to reduce gInitial :: Group -> Document -- | Condition that must be true for a row to be considered. [] means -- always true. gCond :: Group -> Selector -- | agg -> () | result. An optional function to be run on each -- item in the result set just before the item is returned. Can either -- modify the item (e.g., add an average field given a count and a total) -- or return a replacement object (returning a new object with just _id -- and average fields). gFinalize :: Group -> Maybe Javascript -- | Fields to group by, or function (doc -> key) returning a -- key object to be used as the grouping key. Use KeyF instead of -- Key to specify a key that is not an existing member of the object (or, -- to access embedded members). data GroupKey Key :: [Label] -> GroupKey KeyF :: Javascript -> GroupKey -- | Execute group query and return resulting aggregate value for each -- distinct key group :: DbAccess m => Group -> m [Document] -- | Maps every document in collection to a list of (key, value) pairs, -- then for each unique key reduces all its associated values to a single -- result. There are additional parameters that may be set to tweak this -- basic operation. data MapReduce MapReduce :: Collection -> MapFun -> ReduceFun -> Selector -> Order -> Limit -> Maybe Collection -> Bool -> Maybe FinalizeFun -> Document -> Bool -> MapReduce rColl :: MapReduce -> Collection rMap :: MapReduce -> MapFun rReduce :: MapReduce -> ReduceFun -- | Operate on only those documents selected. Default is [] meaning all -- documents. rSelect :: MapReduce -> Selector -- | Default is [] meaning no sort rSort :: MapReduce -> Order -- | Default is 0 meaning no limit rLimit :: MapReduce -> Limit -- | Output to given permanent collection, otherwise output to a new -- temporary collection whose name is returned. rOut :: MapReduce -> Maybe Collection -- | If True, the temporary output collection is made permanent. If False, -- the temporary output collection persists for the life of the current -- pipe only, however, other pipes may read from it while the original -- one is still alive. Note, reading from a temporary collection after -- its original pipe dies returns an empty result (not an error). The -- default for this attribute is False, unless rOut is specified, -- then the collection permanent. rKeepTemp :: MapReduce -> Bool -- | Function to apply to all the results when finished. Default is -- Nothing. rFinalize :: MapReduce -> Maybe FinalizeFun -- | Variables (environment) that can be accessed from -- mapreducefinalize. Default is []. rScope :: MapReduce -> Document -- | Provide statistics on job execution time. Default is False. rVerbose :: MapReduce -> Bool -- | () -> void. The map function references the variable -- this to inspect the current object under consideration. The -- function must call emit(key,value) at least once, but may be -- invoked any number of times, as may be appropriate. type MapFun = Javascript -- | (key, [value]) -> value. The reduce function receives a -- key and an array of values and returns an aggregate result value. The -- MapReduce engine may invoke reduce functions iteratively; thus, these -- functions must be idempotent. That is, the following must hold for -- your reduce function: reduce(k, [reduce(k,vs)]) == -- reduce(k,vs). If you need to perform an operation only once, use -- a finalize function. The output of emit (the 2nd param) and reduce -- should be the same format to make iterative reduce possible. type ReduceFun = Javascript -- | (key, value) -> final_value. A finalize function may be -- run after reduction. Such a function is optional and is not necessary -- for many map/reduce cases. The finalize function takes a key and a -- value, and returns a finalized value. type FinalizeFun = Javascript -- | MapReduce on collection with given map and reduce functions. Remaining -- attributes are set to their defaults, which are stated in their -- comments. mapReduce :: Collection -> MapFun -> ReduceFun -> MapReduce -- | Run MapReduce and return cursor of results. Error if map/reduce fails -- (because of bad Javascript) TODO: Delete temp result collection when -- cursor closes. Until then, it will be deleted by the server when pipe -- closes. runMR :: DbAccess m => MapReduce -> m Cursor -- | Run MapReduce and return a result document containing a result -- field holding the output Collection and additional statistic fields. -- Error if the map/reduce failed (because of bad Javascript). runMR' :: DbAccess m => MapReduce -> m Document -- | A command is a special query or action against the database. See -- http://www.mongodb.org/display/DOCS/Commands for details. type Command = Document -- | Run command against the database and return its result runCommand :: DbAccess m => Command -> m Document -- |
-- runCommand1 foo = runCommand [foo =: 1] --runCommand1 :: DbAccess m => UString -> m Document -- | Run code on server eval :: DbAccess m => Javascript -> m Document instance Show MapReduce instance Eq MapReduce instance Show GroupKey instance Eq GroupKey instance Show Group instance Eq Group instance Show QueryOption instance Eq QueryOption instance Show Query instance Eq Query instance Show WriteMode instance Eq WriteMode instance Show Selection instance Eq Selection instance Eq Database instance Ord Database instance Show Failure instance Eq Failure instance Monad m => Context Pipe (Action m) instance Monad m => Context MasterOrSlaveOk (Action m) instance Monad m => Context WriteMode (Action m) instance Monad m => Throw Failure (Action m) instance MonadIO m => MonadIO (Action m) instance MonadMVar m => MonadMVar (Action m) instance Monad m => Monad (Action m) instance (Monad m, Functor m) => Applicative (Action m) instance Functor m => Functor (Action m) instance Select Query instance Select Selection instance (Context Database m, Access m) => DbAccess m instance Show Database instance Error Failure instance MonadTrans Action instance (Context Pipe m, Context MasterOrSlaveOk m, Context WriteMode m, Throw Failure m, MonadIO' m, MonadMVar m) => Access m -- | Database administrative functions module Database.MongoDB.Admin data CollectionOption Capped :: CollectionOption MaxByteSize :: Int -> CollectionOption MaxItems :: Int -> CollectionOption -- | Create collection with given options. You only need to call this to -- set options, otherwise a collection is created automatically on first -- use with no options. createCollection :: DbAccess m => [CollectionOption] -> Collection -> m Document -- | Rename first collection to second collection renameCollection :: DbAccess m => Collection -> Collection -> m Document -- | Delete the given collection! Return True if collection existed (and -- was deleted); return False if collection did not exist (and no -- action). dropCollection :: DbAccess m => Collection -> m Bool -- | This operation takes a while validateCollection :: DbAccess m => Collection -> m Document data Index Index :: Collection -> Order -> IndexName -> Bool -> Bool -> Index iColl :: Index -> Collection iKey :: Index -> Order iName :: Index -> IndexName iUnique :: Index -> Bool iDropDups :: Index -> Bool type IndexName = UString -- | Spec of index of ordered keys on collection. Name is generated from -- keys. Unique and dropDups are False. index :: Collection -> Order -> Index -- | Create index if we did not already create one. May be called -- repeatedly with practically no performance hit, because we remember if -- we already called this for the same index (although this memory gets -- wiped out every 15 minutes, in case another client drops the index and -- we want to create it again). ensureIndex :: DbAccess m => Index -> m () -- | Create index on the server. This call goes to the server every time. createIndex :: DbAccess m => Index -> m () -- | Remove the index dropIndex :: DbAccess m => Collection -> IndexName -> m Document -- | Get all indexes on this collection getIndexes :: DbAccess m => Collection -> m [Document] -- | Drop all indexes on this collection dropIndexes :: DbAccess m => Collection -> m Document -- | Fetch all users of this database allUsers :: DbAccess m => m [Document] -- | Add user with password with read-only access if bool is True or -- read-write access if bool is False addUser :: DbAccess m => Bool -> Username -> Password -> m () removeUser :: DbAccess m => Username -> m () -- | "admin" database admin :: Database -- | Copy database from given host to the server I am connected to. Fails -- and returns ok = 0 if we don't have permission to read -- from given server (use copyDatabase in this case). cloneDatabase :: Access m => Database -> Host -> m Document -- | Copy database from given host to the server I am connected to. If -- username & password is supplied use them to read from given host. copyDatabase :: Access m => Database -> Host -> Maybe (Username, Password) -> Database -> m Document -- | Delete the given database! dropDatabase :: Access m => Database -> m Document -- | Attempt to fix any corrupt records. This operation takes a while. repairDatabase :: Access m => Database -> m Document serverBuildInfo :: Access m => m Document serverVersion :: Access m => m UString collectionStats :: DbAccess m => Collection -> m Document dataSize :: DbAccess m => Collection -> m Int storageSize :: DbAccess m => Collection -> m Int totalIndexSize :: DbAccess m => Collection -> m Int totalSize :: DbAccess m => Collection -> m Int data ProfilingLevel getProfilingLevel :: DbAccess m => m ProfilingLevel type MilliSec = Int setProfilingLevel :: DbAccess m => ProfilingLevel -> Maybe MilliSec -> m () dbStats :: DbAccess m => m Document type OpNum = Int -- | See currently running operation on the database, if any currentOp :: DbAccess m => m (Maybe Document) killOp :: DbAccess m => OpNum -> m (Maybe Document) serverStatus :: Access m => m Document instance Show ProfilingLevel instance Enum ProfilingLevel instance Eq ProfilingLevel instance Show Index instance Eq Index instance Show CollectionOption instance Eq CollectionOption -- | Client interface to MongoDB database management system. -- -- Simple example below. Use with language extension -- OvererloadedStrings. -- --
--
--
-- import Database.MongoDB
-- import Data.UString (u)
-- import Control.Monad.Trans (liftIO)
--
-- main = do
-- pool <- newConnPool Internet 1 (host "127.0.0.1")
-- e <- access safe Master pool run
-- print e
--
-- run = use (Database "baseball") $ do
-- clearTeams
-- insertTeams
-- print' "All Teams" =<< allTeams
-- print' "National League Teams" =<< nationalLeagueTeams
-- print' "New York Teams" =<< newYorkTeams
--
-- clearTeams = delete (select [] "team")
--
-- insertTeams = insertMany "team" [
-- ["name" =: u"Yankees", "home" =: ["city" =: u"New York", "state" =: u"NY"], "league" =: u"American"],
-- ["name" =: u"Mets", "home" =: ["city" =: u"New York", "state" =: u"NY"], "league" =: u"National"],
-- ["name" =: u"Phillies", "home" =: ["city" =: u"Philadelphia", "state" =: u"PA"], "league" =: u"National"],
-- ["name" =: u"Red Sox", "home" =: ["city" =: u"Boston", "state" =: u"MA"], "league" =: u"American"] ]
--
-- allTeams = rest =<< find (select [] "team") {sort = ["home.city" =: (1 :: Int)]}
--
-- nationalLeagueTeams = rest =<< find (select ["league" =: u"National"] "team")
--
-- newYorkTeams = rest =<< find (select ["home.state" =: u"NY"] "team") {project = ["name" =: (1 :: Int), "league" =: (1 :: Int)]}
--
-- print' title docs = liftIO $ putStrLn title >> mapM_ (print . exclude ["_id"]) docs
--
module Database.MongoDB