2010-11-01 00:38:38 +00:00
-- | Query and update documents
2010-06-15 03:14:40 +00:00
2011-07-09 02:13:47 +00:00
{- # LANGUAGE OverloadedStrings, RecordWildCards, NamedFieldPuns, TupleSections, FlexibleContexts, FlexibleInstances, UndecidableInstances, MultiParamTypeClasses, GeneralizedNewtypeDeriving, StandaloneDeriving, TypeSynonymInstances, TypeFamilies # -}
2010-06-15 03:14:40 +00:00
module Database.MongoDB.Query (
2011-07-05 14:37:01 +00:00
-- * Monad
2011-07-09 02:13:47 +00:00
Action , access , Failure ( .. ) ,
AccessMode ( .. ) , GetLastError , master , slaveOk , accessMode ,
MonadDB ( .. ) ,
2010-06-15 03:14:40 +00:00
-- * Database
2011-07-05 14:37:01 +00:00
Database , allDatabases , useDb , thisDatabase ,
2010-06-15 03:14:40 +00:00
-- ** Authentication
2011-07-05 14:37:01 +00:00
Username , Password , auth ,
2010-06-15 03:14:40 +00:00
-- * Collection
Collection , allCollections ,
-- ** Selection
2010-06-21 15:06:20 +00:00
Selection ( .. ) , Selector , whereJS ,
Select ( select ) ,
2010-06-15 03:14:40 +00:00
-- * Write
-- ** Insert
insert , insert_ , insertMany , insertMany_ ,
-- ** Update
save , replace , repsert , Modifier , modify ,
-- ** Delete
delete , deleteOne ,
-- * Read
-- ** Query
2010-07-27 21:18:53 +00:00
Query ( .. ) , QueryOption ( .. ) , Projector , Limit , Order , BatchSize ,
2011-07-09 02:13:47 +00:00
explain , find , findOne , fetch , count , distinct ,
2010-06-15 03:14:40 +00:00
-- *** Cursor
2010-12-20 02:08:53 +00:00
Cursor , next , nextN , rest , closeCursor , isCursorClosed ,
2010-06-15 03:14:40 +00:00
-- ** Group
Group ( .. ) , GroupKey ( .. ) , group ,
-- ** MapReduce
2011-06-22 21:18:32 +00:00
MapReduce ( .. ) , MapFun , ReduceFun , FinalizeFun , MROut ( .. ) , MRMerge ( .. ) , MRResult , mapReduce , runMR , runMR' ,
2010-06-15 03:14:40 +00:00
-- * Command
Command , runCommand , runCommand1 ,
eval ,
) where
import Prelude as X hiding ( lookup )
2011-07-05 14:37:01 +00:00
import Data.UString as U ( UString , dropWhile , any , tail )
import Data.Bson ( Document , at , lookup , look , Field ( .. ) , ( =: ) , ( =? ) , Label , Value ( String , Doc ) , Javascript , genObjectId )
2011-07-09 02:13:47 +00:00
import Database.MongoDB.Internal.Protocol ( Pipe , Notice ( .. ) , Request ( GetMore ) , Reply ( .. ) , QueryOption ( .. ) , ResponseFlag ( .. ) , UpdateOption ( .. ) , DeleteOption ( .. ) , CursorId , FullCollection , Username , Password , pwKey )
2011-07-05 14:37:01 +00:00
import qualified Database.MongoDB.Internal.Protocol as P ( send , call , Request ( Query ) )
import Database.MongoDB.Internal.Util ( MonadIO ' , loop , liftIOE , true1 , ( <.> ) )
2010-11-01 19:35:13 +00:00
import Control.Monad.MVar
2011-07-05 14:37:01 +00:00
import Control.Monad.Error
import Control.Monad.Reader
2011-07-09 02:13:47 +00:00
import Control.Monad.State ( StateT )
import Control.Monad.Writer ( WriterT , Monoid )
import Control.Monad.RWS ( RWST )
2011-07-05 14:37:01 +00:00
import Control.Applicative ( Applicative , ( <$> ) )
2010-07-27 21:18:53 +00:00
import Data.Maybe ( listToMaybe , catMaybes )
2011-07-05 14:37:01 +00:00
import Data.Int ( Int32 )
import Data.Word ( Word32 )
-- * Monad
2011-07-09 02:13:47 +00:00
newtype Action m a = Action ( ErrorT Failure ( ReaderT Context m ) a )
deriving ( Functor , Applicative , Monad , MonadIO , MonadMVar , MonadError Failure )
-- ^ A monad on top of m (which must be a MonadIO) that may access the database and may fail with a DB 'Failure'
instance MonadTrans Action where lift = Action . lift . lift
access :: ( MonadIO m ) => Pipe -> AccessMode -> Database -> Action m a -> m ( Either Failure a )
-- ^ Run action against database on server at other end of pipe. Use write mode for any writes and read mode for any reads. Return Left on connection or read/write failure.
access myPipe myAccessMode myDatabase ( Action action ) = runReaderT ( runErrorT action ) Context { .. }
2010-06-21 15:06:20 +00:00
2010-11-01 00:38:38 +00:00
-- | A connection failure, or a read or write exception like cursor expired or inserting a duplicate key.
2010-07-27 21:18:53 +00:00
-- 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.
2010-06-21 15:06:20 +00:00
data Failure =
2011-07-05 14:37:01 +00:00
ConnectionFailure IOError -- ^ TCP connection ('Pipeline') failed. May work if you try again on the same Mongo 'Connection' which will create a new Pipe.
2010-10-27 20:13:23 +00:00
| CursorNotFoundFailure CursorId -- ^ 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)
2010-07-27 21:18:53 +00:00
| QueryFailure String -- ^ Query failed for some reason as described in the string
| WriteFailure ErrorCode String -- ^ Error observed by getLastError after a write, error description is in string
2011-07-09 02:13:47 +00:00
| DocNotFound Selection -- ^ 'fetch' found no document matching selection
2010-06-21 15:06:20 +00:00
deriving ( Show , Eq )
2011-07-05 14:37:01 +00:00
type ErrorCode = Int
-- ^ Error code from getLastError
2010-07-27 21:18:53 +00:00
instance Error Failure where strMsg = error
2011-07-09 02:13:47 +00:00
-- ^ 'fail' is treated the same as a programming 'error'. In other words, don't use it.
-- | Type of reads and writes to perform
data AccessMode =
ReadStaleOk -- Read-only action, reading stale data from a slave is OK.
| UnconfirmedWrites -- Read-write action, slave not OK, every write is fire & forget.
| ConfirmWrites GetLastError -- Read-write action, slave not OK, every write is confirmed with getLastError.
type GetLastError = Document
-- ^ Parameters for getLastError command. For example ["w" =: 2] tells the server to wait for the write to reach at least two servers in replica set before acknowledging. See "http://www.mongodb.org/display/DOCS/Last+Error+Commands" for more options.
master :: AccessMode
-- ^ @'ConfirmWrites' []@
master = ConfirmWrites []
slaveOk :: AccessMode
-- ^ @'ReadStaleOk'@
slaveOk = ReadStaleOk
accessMode :: ( Monad m ) => AccessMode -> Action m a -> Action m a
-- ^ Run action with given 'AccessMode'
accessMode mode ( Action act ) = Action $ local ( \ ctx -> ctx { myAccessMode = mode } ) act
readMode :: AccessMode -> ReadMode
readMode ReadStaleOk = StaleOk
readMode _ = Fresh
writeMode :: AccessMode -> WriteMode
writeMode ReadStaleOk = Confirm []
writeMode UnconfirmedWrites = NoConfirm
writeMode ( ConfirmWrites z ) = Confirm z
2010-06-15 03:14:40 +00:00
2011-07-05 14:37:01 +00:00
-- | Values needed when executing a db operation
data Context = Context {
myPipe :: Pipe , -- | operations read/write to this pipelined TCP connection to a MongoDB server
2011-07-09 02:13:47 +00:00
myAccessMode :: AccessMode , -- | read/write operation will use this access mode
2011-07-05 14:37:01 +00:00
myDatabase :: Database } -- | operations query/update this database
2010-06-15 03:14:40 +00:00
2011-07-09 02:13:47 +00:00
myReadMode :: Context -> ReadMode
myReadMode = readMode . myAccessMode
myWriteMode :: Context -> WriteMode
myWriteMode = writeMode . myAccessMode
2010-06-15 03:14:40 +00:00
2011-07-05 14:37:01 +00:00
send :: ( MonadIO m ) => [ Notice ] -> Action m ()
-- ^ Send notices as a contiguous batch to server with no reply. Throw 'ConnectionFailure' if pipe fails.
2011-07-09 02:13:47 +00:00
send ns = Action $ do
2011-07-05 14:37:01 +00:00
pipe <- asks myPipe
liftIOE ConnectionFailure $ P . send pipe ns
2010-10-27 20:13:23 +00:00
2011-07-05 14:37:01 +00:00
call :: ( MonadIO m ) => [ Notice ] -> Request -> Action m ( ErrorT Failure IO Reply )
-- ^ Send notices and request as a contiguous batch to server and return reply promise, which will block when invoked until reply arrives. This call will throw 'ConnectionFailure' if pipe fails on send, and promise will throw 'ConnectionFailure' if pipe fails on receive.
2011-07-09 02:13:47 +00:00
call ns r = Action $ do
2011-07-05 14:37:01 +00:00
pipe <- asks myPipe
promise <- liftIOE ConnectionFailure $ P . call pipe ns r
return ( liftIOE ConnectionFailure promise )
2010-06-21 15:06:20 +00:00
2011-07-09 02:13:47 +00:00
-- | If you stack a monad on top of 'Action' then make it an instance of this class and use 'liftDB' to execute an DB Actions within it. Instances already exist for simple mtl transformers.
class ( Monad m , MonadMVar ( BaseMonad m ) , Applicative ( BaseMonad m ) , Functor ( BaseMonad m ) ) => MonadDB m where
type BaseMonad m :: * -> *
liftDB :: Action ( BaseMonad m ) a -> m a
instance ( MonadMVar m , Applicative m , Functor m ) => MonadDB ( Action m ) where
type BaseMonad ( Action m ) = m
liftDB = id
instance ( MonadDB m , Error e ) => MonadDB ( ErrorT e m ) where
type BaseMonad ( ErrorT e m ) = BaseMonad m
liftDB = lift . liftDB
instance ( MonadDB m ) => MonadDB ( ReaderT r m ) where
type BaseMonad ( ReaderT r m ) = BaseMonad m
liftDB = lift . liftDB
instance ( MonadDB m ) => MonadDB ( StateT s m ) where
type BaseMonad ( StateT s m ) = BaseMonad m
liftDB = lift . liftDB
instance ( MonadDB m , Monoid w ) => MonadDB ( WriterT w m ) where
type BaseMonad ( WriterT w m ) = BaseMonad m
liftDB = lift . liftDB
instance ( MonadDB m , Monoid w ) => MonadDB ( RWST r w s m ) where
type BaseMonad ( RWST r w s m ) = BaseMonad m
liftDB = lift . liftDB
2011-07-05 14:37:01 +00:00
-- * Database
2010-06-15 03:14:40 +00:00
2011-07-05 14:37:01 +00:00
type Database = UString
allDatabases :: ( MonadIO' m ) => Action m [ Database ]
-- ^ List all databases residing on server
allDatabases = map ( at " name " ) . at " databases " <$> useDb " admin " ( runCommand1 " listDatabases " )
2010-06-15 03:14:40 +00:00
2011-07-05 14:37:01 +00:00
thisDatabase :: ( Monad m ) => Action m Database
2010-06-15 03:14:40 +00:00
-- ^ Current database in use
2011-07-09 02:13:47 +00:00
thisDatabase = Action $ asks myDatabase
2011-07-05 14:37:01 +00:00
useDb :: ( Monad m ) => Database -> Action m a -> Action m a
-- ^ Run action against given database
2011-07-09 02:13:47 +00:00
useDb db ( Action act ) = Action $ local ( \ ctx -> ctx { myDatabase = db } ) act
2010-06-15 03:14:40 +00:00
-- * Authentication
2011-07-05 14:37:01 +00:00
auth :: ( MonadIO' m ) => Username -> Password -> Action m Bool
-- ^ Authenticate with the current database (if server is running in secure mode). Return whether authentication was successful or not. Reauthentication is required for every new pipe.
2010-12-27 05:23:02 +00:00
auth usr pss = do
2010-06-15 03:14:40 +00:00
n <- at " nonce " <$> runCommand [ " getnonce " =: ( 1 :: Int ) ]
2010-12-27 05:23:02 +00:00
true1 " ok " <$> runCommand [ " authenticate " =: ( 1 :: Int ) , " user " =: usr , " nonce " =: n , " key " =: pwKey n usr pss ]
2010-06-15 03:14:40 +00:00
-- * Collection
type Collection = UString
-- ^ Collection name (not prefixed with database)
2011-07-05 14:37:01 +00:00
allCollections :: ( MonadMVar m , Functor m ) => Action m [ Collection ]
2010-06-15 03:14:40 +00:00
-- ^ List all collections in this database
allCollections = do
db <- thisDatabase
docs <- rest =<< find ( query [] " system.namespaces " ) { sort = [ " name " =: ( 1 :: Int ) ] }
return . filter ( not . isSpecial db ) . map dropDbPrefix $ map ( at " name " ) docs
where
dropDbPrefix = U . tail . U . dropWhile ( /= '.' )
2011-07-05 14:37:01 +00:00
isSpecial db col = U . any ( == '$' ) col && db <.> col /= " local.oplog.$main "
2010-06-15 03:14:40 +00:00
-- * Selection
data Selection = Select { selector :: Selector , coll :: Collection } deriving ( Show , Eq )
-- ^ Selects documents in collection that match selector
type Selector = Document
-- ^ 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.
whereJS :: Selector -> Javascript -> Selector
-- ^ Add Javascript predicate to selector, in which case a document must match both selector and predicate
whereJS sel js = ( " $where " =: js ) : sel
2010-06-21 15:06:20 +00:00
class Select aQueryOrSelection where
select :: Selector -> Collection -> aQueryOrSelection
-- ^ 'Query' or 'Selection' that selects documents in collection that match selector. The choice of type depends on use, for example, in @find (select sel col)@ it is a Query, and in @delete (select sel col)@ it is a Selection.
instance Select Selection where
select = Select
instance Select Query where
select = query
2010-06-15 03:14:40 +00:00
-- * Write
2010-06-21 15:06:20 +00:00
data WriteMode =
2011-07-09 02:13:47 +00:00
NoConfirm -- ^ Submit writes without receiving acknowledgments. Fast. Assumes writes succeed even though they may not.
| Confirm GetLastError -- ^ 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.
2010-06-21 15:06:20 +00:00
deriving ( Show , Eq )
2011-07-05 14:37:01 +00:00
write :: ( MonadIO m ) => Notice -> Action m ()
2010-07-27 21:18:53 +00:00
-- ^ Send write to server, and if write-mode is 'Safe' then include getLastError request and raise 'WriteFailure' if it reports an error.
2011-07-09 02:13:47 +00:00
write notice = Action ( asks myWriteMode ) >>= \ mode -> case mode of
NoConfirm -> send [ notice ]
Confirm params -> do
2011-07-05 14:37:01 +00:00
let q = query ( ( " getlasterror " =: ( 1 :: Int ) ) : params ) " $cmd "
Batch _ _ [ doc ] <- fulfill =<< request [ notice ] =<< queryRequest False q { limit = 1 }
case lookup " err " doc of
Nothing -> return ()
Just err -> throwError $ WriteFailure ( maybe 0 id $ lookup " code " doc ) err
2010-06-21 15:06:20 +00:00
2010-06-15 03:14:40 +00:00
-- ** Insert
2011-07-05 14:37:01 +00:00
insert :: ( MonadIO' m ) => Collection -> Document -> Action m Value
2010-06-15 03:14:40 +00:00
-- ^ Insert document into collection and return its \"_id\" value, which is created automatically if not supplied
insert col doc = head <$> insertMany col [ doc ]
2011-07-05 14:37:01 +00:00
insert_ :: ( MonadIO' m ) => Collection -> Document -> Action m ()
2010-06-15 03:14:40 +00:00
-- ^ Same as 'insert' except don't return _id
insert_ col doc = insert col doc >> return ()
2011-07-05 14:37:01 +00:00
insertMany :: ( MonadIO m ) => Collection -> [ Document ] -> Action m [ Value ]
2010-06-15 03:14:40 +00:00
-- ^ Insert documents into collection and return their \"_id\" values, which are created automatically if not supplied
2010-06-21 15:06:20 +00:00
insertMany col docs = do
2011-07-05 14:37:01 +00:00
db <- thisDatabase
2010-06-15 03:14:40 +00:00
docs' <- liftIO $ mapM assignId docs
2010-06-21 15:06:20 +00:00
write ( Insert ( db <.> col ) docs' )
2010-06-15 03:14:40 +00:00
mapM ( look " _id " ) docs'
2011-07-05 14:37:01 +00:00
insertMany_ :: ( MonadIO m ) => Collection -> [ Document ] -> Action m ()
2010-06-15 03:14:40 +00:00
-- ^ Same as 'insertMany' except don't return _ids
insertMany_ col docs = insertMany col docs >> return ()
assignId :: Document -> IO Document
-- ^ Assign a unique value to _id field if missing
assignId doc = if X . any ( ( " _id " == ) . label ) doc
then return doc
else ( \ oid -> ( " _id " =: oid ) : doc ) <$> genObjectId
-- ** Update
2011-07-05 14:37:01 +00:00
save :: ( MonadIO' m ) => Collection -> Document -> Action m ()
2010-06-15 03:14:40 +00:00
-- ^ 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 col doc = case look " _id " doc of
Nothing -> insert_ col doc
Just i -> repsert ( Select [ " _id " := i ] col ) doc
2011-07-05 14:37:01 +00:00
replace :: ( MonadIO m ) => Selection -> Document -> Action m ()
2010-06-15 03:14:40 +00:00
-- ^ Replace first document in selection with given document
replace = update []
2011-07-05 14:37:01 +00:00
repsert :: ( MonadIO m ) => Selection -> Document -> Action m ()
2010-06-15 03:14:40 +00:00
-- ^ Replace first document in selection with given document, or insert document if selection is empty
repsert = update [ Upsert ]
type Modifier = Document
-- ^ Update operations on fields in a document. See <http://www.mongodb.org/display/DOCS/Updating#Updating-ModifierOperations>
2011-07-05 14:37:01 +00:00
modify :: ( MonadIO m ) => Selection -> Modifier -> Action m ()
2010-06-15 03:14:40 +00:00
-- ^ Update all documents in selection using given modifier
modify = update [ MultiUpdate ]
2011-07-05 14:37:01 +00:00
update :: ( MonadIO m ) => [ UpdateOption ] -> Selection -> Document -> Action m ()
2010-06-15 03:14:40 +00:00
-- ^ Update first document in selection using updater document, unless 'MultiUpdate' option is supplied then update all documents in selection. If 'Upsert' option is supplied then treat updater as document and insert it if selection is empty.
2010-06-21 15:06:20 +00:00
update opts ( Select sel col ) up = do
2011-07-05 14:37:01 +00:00
db <- thisDatabase
2010-06-21 15:06:20 +00:00
write ( Update ( db <.> col ) opts sel up )
2010-06-15 03:14:40 +00:00
-- ** Delete
2011-07-05 14:37:01 +00:00
delete :: ( MonadIO m ) => Selection -> Action m ()
2010-06-15 03:14:40 +00:00
-- ^ Delete all documents in selection
2010-06-21 15:06:20 +00:00
delete = delete' []
2010-06-15 03:14:40 +00:00
2011-07-05 14:37:01 +00:00
deleteOne :: ( MonadIO m ) => Selection -> Action m ()
2010-06-15 03:14:40 +00:00
-- ^ Delete first document in selection
2010-06-21 15:06:20 +00:00
deleteOne = delete' [ SingleRemove ]
2011-07-05 14:37:01 +00:00
delete' :: ( MonadIO m ) => [ DeleteOption ] -> Selection -> Action m ()
2010-06-21 15:06:20 +00:00
-- ^ Delete all documents in selection unless 'SingleRemove' option is given then only delete first document in selection
delete' opts ( Select sel col ) = do
2011-07-05 14:37:01 +00:00
db <- thisDatabase
2010-06-21 15:06:20 +00:00
write ( Delete ( db <.> col ) opts sel )
2010-06-15 03:14:40 +00:00
-- * Read
2011-07-09 02:13:47 +00:00
data ReadMode =
Fresh -- ^ read from master only
| StaleOk -- ^ read from slave ok
deriving ( Show , Eq )
2010-07-27 21:18:53 +00:00
2011-07-09 02:13:47 +00:00
readModeOption :: ReadMode -> [ QueryOption ]
readModeOption Fresh = []
readModeOption StaleOk = [ SlaveOK ]
2010-07-27 21:18:53 +00:00
2010-06-15 03:14:40 +00:00
-- ** Query
2010-06-21 15:06:20 +00:00
-- | Use 'select' to create a basic query with defaults, then modify if desired. For example, @(select sel col) {limit = 10}@
2010-06-15 03:14:40 +00:00
data Query = Query {
2010-06-21 15:06:20 +00:00
options :: [ QueryOption ] , -- ^ Default = []
2010-06-15 03:14:40 +00:00
selection :: Selection ,
2010-06-21 15:06:20 +00:00
project :: Projector , -- ^ \[\] = all fields. Default = []
skip :: Word32 , -- ^ Number of initial matching documents to skip. Default = 0
limit :: Limit , -- ^ Maximum number of documents to return, 0 = no limit. Default = 0
sort :: Order , -- ^ Sort results by this order, [] = no sort. Default = []
snapshot :: Bool , -- ^ 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
batchSize :: BatchSize , -- ^ The number of document to return in each batch response from the server. 0 means use Mongo default. Default = 0
hint :: Order -- ^ Force MongoDB to use this index, [] = no hint. Default = []
2010-06-15 03:14:40 +00:00
} deriving ( Show , Eq )
type Projector = Document
-- ^ 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 Limit = Word32
-- ^ Maximum number of documents to return, i.e. cursor will close after iterating over this number of documents. 0 means no limit.
type Order = Document
2010-07-03 17:15:30 +00:00
-- ^ 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
2010-06-15 03:14:40 +00:00
type BatchSize = Word32
-- ^ The number of document to return in each batch response from the server. 0 means use Mongo default.
query :: Selector -> Collection -> Query
-- ^ Selects documents in collection that match selector. It uses no query options, projects all fields, does not skip any documents, does not limit result size, uses default batch size, does not sort, does not hint, and does not snapshot.
query sel col = Query [] ( Select sel col ) [] 0 0 [] False 0 []
2011-07-05 14:37:01 +00:00
find :: ( MonadMVar m ) => Query -> Action m Cursor
2010-06-15 03:14:40 +00:00
-- ^ Fetch documents satisfying query
2010-06-21 15:06:20 +00:00
find q @ Query { selection , batchSize } = do
db <- thisDatabase
2011-07-05 14:37:01 +00:00
dBatch <- request [] =<< queryRequest False q
newCursor db ( coll selection ) batchSize dBatch
2010-06-15 03:14:40 +00:00
2011-07-05 14:37:01 +00:00
findOne :: ( MonadIO m ) => Query -> Action m ( Maybe Document )
2010-06-21 15:06:20 +00:00
-- ^ Fetch first document satisfying query or Nothing if none satisfy it
2011-07-05 14:37:01 +00:00
findOne q = do
Batch _ _ docs <- fulfill =<< request [] =<< queryRequest False q { limit = 1 }
return ( listToMaybe docs )
2010-06-21 15:06:20 +00:00
2011-07-09 02:13:47 +00:00
fetch :: ( MonadIO m ) => Query -> Action m Document
-- ^ Same as 'findOne' except throw 'DocNotFound' if no match
fetch q = findOne q >>= maybe ( throwError $ DocNotFound $ selection q ) return
2011-07-05 14:37:01 +00:00
explain :: ( MonadIO m ) => Query -> Action m Document
2010-06-15 03:14:40 +00:00
-- ^ Return performance stats of query execution
2010-06-21 15:06:20 +00:00
explain q = do -- same as findOne but with explain set to true
2011-07-05 14:37:01 +00:00
Batch _ _ docs <- fulfill =<< request [] =<< queryRequest True q { limit = 1 }
2010-06-21 15:06:20 +00:00
return $ if null docs then error ( " no explain: " ++ show q ) else head docs
2010-06-15 03:14:40 +00:00
2011-07-05 14:37:01 +00:00
count :: ( MonadIO' m ) => Query -> Action m Int
2010-06-15 03:14:40 +00:00
-- ^ Fetch number of documents satisfying query (including effect of skip and/or limit if present)
count Query { selection = Select sel col , skip , limit } = at " n " <$> runCommand
( [ " count " =: col , " query " =: sel , " skip " =: ( fromIntegral skip :: Int32 ) ]
++ ( " limit " =? if limit == 0 then Nothing else Just ( fromIntegral limit :: Int32 ) ) )
2011-07-05 14:37:01 +00:00
distinct :: ( MonadIO' m ) => Label -> Selection -> Action m [ Value ]
2010-06-15 03:14:40 +00:00
-- ^ Fetch distinct values of field in selected documents
distinct k ( Select sel col ) = at " values " <$> runCommand [ " distinct " =: col , " key " =: k , " query " =: sel ]
2011-07-05 14:37:01 +00:00
queryRequest :: ( Monad m ) => Bool -> Query -> Action m ( Request , Limit )
-- ^ Translate Query to Protocol.Query. If first arg is true then add special $explain attribute.
queryRequest isExplain Query { .. } = do
2011-07-09 02:13:47 +00:00
ctx <- Action ask
2011-07-05 14:37:01 +00:00
return $ queryRequest' ( myReadMode ctx ) ( myDatabase ctx )
where
2011-07-09 02:13:47 +00:00
queryRequest' rm db = ( P . Query { .. } , remainingLimit ) where
qOptions = readModeOption rm ++ options
2011-07-05 14:37:01 +00:00
qFullCollection = db <.> coll selection
qSkip = fromIntegral skip
( qBatchSize , remainingLimit ) = batchSizeRemainingLimit batchSize limit
qProjector = project
mOrder = if null sort then Nothing else Just ( " $orderby " =: sort )
mSnapshot = if snapshot then Just ( " $snapshot " =: True ) else Nothing
mHint = if null hint then Nothing else Just ( " $hint " =: hint )
mExplain = if isExplain then Just ( " $explain " =: True ) else Nothing
special = catMaybes [ mOrder , mSnapshot , mHint , mExplain ]
qSelector = if null special then s else ( " $query " =: s ) : special where s = selector selection
2010-06-15 03:14:40 +00:00
2011-07-05 14:37:01 +00:00
batchSizeRemainingLimit :: BatchSize -> Limit -> ( Int32 , Limit )
-- ^ Given batchSize and limit return P.qBatchSize and remaining limit
batchSizeRemainingLimit batchSize limit = if limit == 0
then ( fromIntegral batchSize' , 0 ) -- no limit
else if 0 < batchSize' && batchSize' < limit
then ( fromIntegral batchSize' , limit - batchSize' )
else ( - fromIntegral limit , 1 )
where batchSize' = if batchSize == 1 then 2 else batchSize
-- batchSize 1 is broken because server converts 1 to -1 meaning limit 1
2010-06-15 03:14:40 +00:00
2011-07-05 14:37:01 +00:00
type DelayedBatch = ErrorT Failure IO Batch
-- ^ A promised batch which may fail
2010-06-21 15:06:20 +00:00
2011-07-05 14:37:01 +00:00
data Batch = Batch Limit CursorId [ Document ]
-- ^ CursorId = 0 means cursor is finished. Documents is remaining documents to serve in current batch. Limit is remaining limit for next fetch.
2010-06-21 15:06:20 +00:00
2011-07-05 14:37:01 +00:00
request :: ( MonadIO m ) => [ Notice ] -> ( Request , Limit ) -> Action m DelayedBatch
-- ^ Send notices and request and return promised batch
2010-11-01 19:35:13 +00:00
request ns ( req , remainingLimit ) = do
2010-07-27 21:18:53 +00:00
promise <- call ns req
2010-11-01 19:35:13 +00:00
return $ fromReply remainingLimit =<< promise
2010-06-21 15:06:20 +00:00
2011-07-05 14:37:01 +00:00
fromReply :: Limit -> Reply -> DelayedBatch
-- ^ Convert Reply to Batch or Failure
2010-07-27 21:18:53 +00:00
fromReply limit Reply { .. } = do
mapM_ checkResponseFlag rResponseFlags
2011-07-05 14:37:01 +00:00
return ( Batch limit rCursorId rDocuments )
2010-07-03 17:15:30 +00:00
where
2010-07-27 21:18:53 +00:00
-- If response flag indicates failure then throw it, otherwise do nothing
checkResponseFlag flag = case flag of
AwaitCapable -> return ()
2011-07-05 14:37:01 +00:00
CursorNotFound -> throwError ( CursorNotFoundFailure rCursorId )
QueryError -> throwError ( QueryFailure $ at " $err " $ head rDocuments )
2011-07-09 02:13:47 +00:00
fulfill :: ( MonadIO m ) => DelayedBatch -> Action m Batch
2011-07-05 14:37:01 +00:00
-- ^ Demand and wait for result, raise failure if exception
2011-07-09 02:13:47 +00:00
fulfill = Action . liftIOE id
2011-07-05 14:37:01 +00:00
-- *** Cursor
data Cursor = Cursor FullCollection BatchSize ( MVar DelayedBatch )
-- ^ 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.
2010-06-15 03:14:40 +00:00
2011-07-05 14:37:01 +00:00
newCursor :: ( MonadMVar m ) => Database -> Collection -> BatchSize -> DelayedBatch -> Action m Cursor
2010-06-21 15:06:20 +00:00
-- ^ Create new cursor. If you don't read all results then close it. Cursor will be closed automatically when all results are read from it or when eventually garbage collected.
2011-07-05 14:37:01 +00:00
newCursor db col batchSize dBatch = do
var <- newMVar dBatch
let cursor = Cursor ( db <.> col ) batchSize var
addMVarFinalizer var ( closeCursor cursor )
2010-06-21 15:06:20 +00:00
return cursor
2010-06-15 03:14:40 +00:00
2011-07-05 14:37:01 +00:00
next :: ( MonadMVar m ) => Cursor -> Action m ( Maybe Document )
2010-06-15 20:15:37 +00:00
-- ^ Return next document in query result, or Nothing if finished.
2011-07-05 14:37:01 +00:00
next ( Cursor fcol batchSize var ) = modifyMVar var nextState where
2010-06-21 15:06:20 +00:00
-- Pre-fetch next batch promise from server when last one in current batch is returned.
2011-07-05 14:37:01 +00:00
-- nextState:: DelayedBatch -> Action m (DelayedBatch, Maybe Document)
nextState dBatch = do
Batch limit cid docs <- fulfill dBatch
2010-06-21 15:06:20 +00:00
case docs of
doc : docs' -> do
2011-07-05 14:37:01 +00:00
dBatch' <- if null docs' && cid /= 0
2010-11-01 19:35:13 +00:00
then nextBatch limit cid
2011-07-05 14:37:01 +00:00
else return $ return ( Batch limit cid docs' )
return ( dBatch' , Just doc )
2010-06-21 15:06:20 +00:00
[] -> if cid == 0
2011-07-05 14:37:01 +00:00
then return ( return $ Batch 0 0 [] , Nothing ) -- finished
2010-06-21 15:06:20 +00:00
else error $ " server returned empty batch but says more results on server "
2011-07-05 14:37:01 +00:00
nextBatch limit cid = request [] ( GetMore fcol batchSize' cid , remLimit )
where ( batchSize' , remLimit ) = batchSizeRemainingLimit batchSize limit
2010-06-15 03:14:40 +00:00
2011-07-05 14:37:01 +00:00
nextN :: ( MonadMVar m , Functor m ) => Int -> Cursor -> Action m [ Document ]
2010-06-15 03:14:40 +00:00
-- ^ Return next N documents or less if end is reached
nextN n c = catMaybes <$> replicateM n ( next c )
2011-07-05 14:37:01 +00:00
rest :: ( MonadMVar m , Functor m ) => Cursor -> Action m [ Document ]
2010-06-15 03:14:40 +00:00
-- ^ Return remaining documents in query result
rest c = loop ( next c )
2011-07-05 14:37:01 +00:00
closeCursor :: ( MonadMVar m ) => Cursor -> Action m ()
closeCursor ( Cursor _ _ var ) = modifyMVar var $ \ dBatch -> do
Batch _ cid _ <- fulfill dBatch
unless ( cid == 0 ) $ send [ KillCursors [ cid ] ]
return $ ( return $ Batch 0 0 [] , () )
2010-12-20 02:08:53 +00:00
2011-07-05 14:37:01 +00:00
isCursorClosed :: ( MonadIO m ) => Cursor -> Action m Bool
isCursorClosed ( Cursor _ _ var ) = do
Batch _ cid docs <- fulfill =<< readMVar var
2010-06-21 15:06:20 +00:00
return ( cid == 0 && null docs )
2010-06-15 03:14:40 +00:00
-- ** Group
2010-07-03 17:15:30 +00:00
-- | Groups documents in collection by key then reduces (aggregates) each group
2010-06-15 03:14:40 +00:00
data Group = Group {
gColl :: Collection ,
gKey :: GroupKey , -- ^ Fields to group by
2010-07-03 17:15:30 +00:00
gReduce :: Javascript , -- ^ @(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.
gInitial :: Document , -- ^ @agg@. Initial aggregation value supplied to reduce
2010-06-15 03:14:40 +00:00
gCond :: Selector , -- ^ Condition that must be true for a row to be considered. [] means always true.
2010-07-03 17:15:30 +00:00
gFinalize :: Maybe Javascript -- ^ @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).
2010-06-15 03:14:40 +00:00
} deriving ( Show , Eq )
data GroupKey = Key [ Label ] | KeyF Javascript deriving ( Show , Eq )
2010-07-03 17:15:30 +00:00
-- ^ 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).
2010-06-15 03:14:40 +00:00
groupDocument :: Group -> Document
-- ^ Translate Group data into expected document form
groupDocument Group { .. } =
( " finalize " =? gFinalize ) ++ [
" ns " =: gColl ,
case gKey of Key k -> " key " =: map ( =: True ) k ; KeyF f -> " $keyf " =: f ,
" $reduce " =: gReduce ,
" initial " =: gInitial ,
" cond " =: gCond ]
2011-07-05 14:37:01 +00:00
group :: ( MonadIO' m ) => Group -> Action m [ Document ]
2010-06-15 03:14:40 +00:00
-- ^ Execute group query and return resulting aggregate value for each distinct key
group g = at " retval " <$> runCommand [ " group " =: groupDocument g ]
-- ** MapReduce
2010-10-27 20:13:23 +00:00
-- | 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.
2011-06-22 21:18:32 +00:00
-- This implements the latest version of map-reduce that requires MongoDB 1.7.4 or greater. To map-reduce against an older server use runCommand directly as described in http://www.mongodb.org/display/DOCS/MapReduce.
2010-06-15 03:14:40 +00:00
data MapReduce = MapReduce {
rColl :: Collection ,
rMap :: MapFun ,
rReduce :: ReduceFun ,
2010-07-03 17:15:30 +00:00
rSelect :: Selector , -- ^ Operate on only those documents selected. Default is [] meaning all documents.
2010-06-15 03:14:40 +00:00
rSort :: Order , -- ^ Default is [] meaning no sort
rLimit :: Limit , -- ^ Default is 0 meaning no limit
2011-06-22 21:18:32 +00:00
rOut :: MROut , -- ^ Output to a collection with a certain merge policy. Default is no collection (Inline). Note, you don't want this default if your result set is large.
2010-06-15 03:14:40 +00:00
rFinalize :: Maybe FinalizeFun , -- ^ Function to apply to all the results when finished. Default is Nothing.
rScope :: Document , -- ^ Variables (environment) that can be accessed from map/reduce/finalize. Default is [].
rVerbose :: Bool -- ^ Provide statistics on job execution time. Default is False.
} deriving ( Show , Eq )
type MapFun = Javascript
2010-07-03 17:15:30 +00:00
-- ^ @() -> 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.
2010-06-15 03:14:40 +00:00
type ReduceFun = Javascript
2010-10-27 20:13:23 +00:00
-- ^ @(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.
2010-06-15 03:14:40 +00:00
type FinalizeFun = 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.
2011-06-22 21:18:32 +00:00
data MROut =
Inline -- ^ Return results directly instead of writing them to an output collection. Results must fit within 16MB limit of a single document
| Output MRMerge Collection ( Maybe Database ) -- ^ Write results to given collection, in other database if specified. Follow merge policy when entry already exists
deriving ( Show , Eq )
data MRMerge =
Replace -- ^ Clear all old data and replace it with new data
| Merge -- ^ Leave old data but overwrite entries with the same key with new data
| Reduce -- ^ Leave old data but combine entries with the same key via MR's reduce function
deriving ( Show , Eq )
type MRResult = Document
-- ^ Result of running a MapReduce has some stats besides the output. See http://www.mongodb.org/display/DOCS/MapReduce#MapReduce-Resultobject
2010-06-15 03:14:40 +00:00
mrDocument :: MapReduce -> Document
-- ^ Translate MapReduce data into expected document form
mrDocument MapReduce { .. } =
( " mapreduce " =: rColl ) :
2011-06-22 21:18:32 +00:00
( " out " =: mrOutDoc rOut ) :
2010-06-15 03:14:40 +00:00
( " finalize " =? rFinalize ) ++ [
" map " =: rMap ,
" reduce " =: rReduce ,
" query " =: rSelect ,
" sort " =: rSort ,
" limit " =: ( fromIntegral rLimit :: Int ) ,
" scope " =: rScope ,
" verbose " =: rVerbose ]
2011-06-22 21:18:32 +00:00
mrOutDoc :: MROut -> Document
-- ^ Translate MROut into expected document form
mrOutDoc Inline = [ " inline " =: ( 1 :: Int ) ]
mrOutDoc ( Output mrMerge coll mDB ) = ( mergeName mrMerge =: coll ) : mdb mDB where
mergeName Replace = " replace "
mergeName Merge = " merge "
mergeName Reduce = " reduce "
mdb Nothing = []
2011-07-05 14:37:01 +00:00
mdb ( Just db ) = [ " db " =: db ]
2011-06-22 21:18:32 +00:00
2010-06-15 03:14:40 +00:00
mapReduce :: Collection -> MapFun -> ReduceFun -> MapReduce
-- ^ MapReduce on collection with given map and reduce functions. Remaining attributes are set to their defaults, which are stated in their comments.
2011-06-22 21:18:32 +00:00
mapReduce col map' red = MapReduce col map' red [] [] 0 Inline Nothing [] False
2010-06-15 03:14:40 +00:00
2011-07-05 14:37:01 +00:00
runMR :: ( MonadMVar m , Applicative m ) => MapReduce -> Action m Cursor
2010-06-15 03:14:40 +00:00
-- ^ Run MapReduce and return cursor of results. Error if map/reduce fails (because of bad Javascript)
2011-06-22 21:18:32 +00:00
runMR mr = do
res <- runMR' mr
case look " result " res of
Just ( String coll ) -> find $ query [] coll
2011-07-05 14:37:01 +00:00
Just ( Doc doc ) -> useDb ( at " db " doc ) $ find $ query [] ( at " collection " doc )
2011-06-22 21:18:32 +00:00
Just x -> error $ " unexpected map-reduce result field: " ++ show x
2011-07-05 14:37:01 +00:00
Nothing -> newCursor " " " " 0 $ return $ Batch 0 0 ( at " results " res )
2011-06-22 21:18:32 +00:00
2011-07-05 14:37:01 +00:00
runMR' :: ( MonadIO' m ) => MapReduce -> Action m MRResult
2011-06-22 21:18:32 +00:00
-- ^ Run MapReduce and return a MR result document containing stats and the results if Inlined. Error if the map/reduce failed (because of bad Javascript).
2010-06-15 03:14:40 +00:00
runMR' mr = do
doc <- runCommand ( mrDocument mr )
2010-10-27 20:13:23 +00:00
return $ if true1 " ok " doc then doc else error $ " mapReduce error: \ n " ++ show doc ++ " \ n in: \ n " ++ show mr
2010-06-15 03:14:40 +00:00
-- * Command
type Command = Document
-- ^ A command is a special query or action against the database. See <http://www.mongodb.org/display/DOCS/Commands> for details.
2011-07-05 14:37:01 +00:00
runCommand :: ( MonadIO' m ) => Command -> Action m Document
2010-06-15 03:14:40 +00:00
-- ^ Run command against the database and return its result
2011-07-05 14:37:01 +00:00
runCommand c = maybe err id <$> findOne ( query c " $cmd " ) where
err = error $ " Nothing returned for command: " ++ show c
2010-06-15 03:14:40 +00:00
2011-07-05 14:37:01 +00:00
runCommand1 :: ( MonadIO' m ) => UString -> Action m Document
2010-06-21 15:06:20 +00:00
-- ^ @runCommand1 foo = runCommand [foo =: 1]@
2010-06-15 03:14:40 +00:00
runCommand1 c = runCommand [ c =: ( 1 :: Int ) ]
2011-07-05 14:37:01 +00:00
eval :: ( MonadIO' m ) => Javascript -> Action m Document
2010-06-15 03:14:40 +00:00
-- ^ Run code on server
eval code = at " retval " <$> runCommand [ " $eval " =: code ]
{- Authors: Tony Hannan <tony@10gen.com>
2011-07-05 14:37:01 +00:00
Copyright 2011 10 gen Inc .
2010-06-15 03:14:40 +00:00
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at : http :// www . apache . org / licenses / LICENSE - 2.0 . Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . - }