MongoDB  2.7.0
Public Member Functions | Static Public Member Functions | Protected Member Functions | Protected Attributes | Static Protected Attributes | Friends | List of all members
mongo::DBClientConnection Class Reference

A basic connection to the database. More...

#include <dbclientinterface.h>

Inheritance diagram for mongo::DBClientConnection:
mongo::DBClientBase mongo::DBClientWithCommands mongo::DBConnector mongo::DBClientInterface

Public Member Functions

 DBClientConnection (bool _autoReconnect=false, DBClientReplicaSet *cp=0, double so_timeout=0)
 
virtual bool connect (const char *hostname, string &errmsg)
 Connect to a Mongo database server. More...
 
virtual bool connect (const HostAndPort &server, string &errmsg)
 Connect to a Mongo database server. More...
 
void connect (const string &serverHostname)
 Connect to a Mongo database server. More...
 
virtual void logout (const string &dbname, BSONObj &info)
 Logs out the connection for the given database. More...
 
virtual auto_ptr< DBClientCursorquery (const string &ns, Query query=Query(), int nToReturn=0, int nToSkip=0, const BSONObj *fieldsToReturn=0, int queryOptions=0, int batchSize=0)
 send a query to the database. More...
 
virtual unsigned long long query (boost::function< void(DBClientCursorBatchIterator &)> f, const string &ns, Query query, const BSONObj *fieldsToReturn, int queryOptions)
 
virtual bool runCommand (const string &dbname, const BSONObj &cmd, BSONObj &info, int options=0)
 Run a database command. More...
 
bool isFailed () const
 
bool isStillConnected ()
 if not checked recently, checks whether the underlying socket/sockets are still valid
 
MessagingPortport ()
 
string toString () const
 
string getServerAddress () const
 
virtual void killCursor (long long cursorID)
 
virtual bool callRead (Message &toSend, Message &response)
 
virtual void say (Message &toSend, bool isRetry=false, string *actualServer=0)
 
virtual bool recv (Message &m)
 
virtual void checkResponse (const char *data, int nReturned, bool *retry=NULL, string *host=NULL)
 
virtual bool call (Message &toSend, Message &response, bool assertOk=true, string *actualServer=0)
 actualServer is set to the actual server where they call went if there was a choice (SlaveOk)
 
virtual
ConnectionString::ConnectionType 
type () const
 
void setSoTimeout (double timeout)
 
double getSoTimeout () const
 
virtual bool lazySupported () const
 
void setReplSetClientCallback (DBClientReplicaSet *rsClient)
 Primarily used for notifying the replica set client that the server it is talking to is not primary anymore. More...
 
uint64_t getSockCreationMicroSec () const
 
- Public Member Functions inherited from mongo::DBClientBase
long long getConnectionId () const
 
WriteConcern getWriteConcern () const
 
void setWriteConcern (WriteConcern w)
 
void setWireVersions (int minWireVersion, int maxWireVersion)
 
int getMinWireVersion ()
 
int getMaxWireVersion ()
 
virtual unsigned long long query (boost::function< void(const BSONObj &)> f, const string &ns, Query query, const BSONObj *fieldsToReturn=0, int queryOptions=0)
 Uses QueryOption_Exhaust, when available. More...
 
virtual auto_ptr< DBClientCursorgetMore (const string &ns, long long cursorId, int nToReturn=0, int options=0)
 don't use this - called automatically by DBClientCursor for you More...
 
virtual void insert (const string &ns, BSONObj obj, int flags=0)
 insert an object into the database
 
virtual void insert (const string &ns, const vector< BSONObj > &v, int flags=0)
 insert a vector of objects into the database
 
virtual void update (const string &ns, Query query, BSONObj obj, bool upsert=false, bool multi=false)
 updates objects matching query
 
virtual void update (const string &ns, Query query, BSONObj obj, int flags)
 
virtual void remove (const string &ns, Query q, bool justOne=0)
 remove matching objects from the database More...
 
virtual void remove (const string &ns, Query query, int flags)
 
- Public Member Functions inherited from mongo::DBClientWithCommands
bool simpleCommand (const string &dbname, BSONObj *info, const string &command)
 helper function. More...
 
void auth (const BSONObj &params)
 Authenticate a user. More...
 
bool auth (const string &dbname, const string &username, const string &pwd, string &errmsg, bool digestPassword=true)
 Authorize access to a particular database. More...
 
virtual unsigned long long count (const string &ns, const BSONObj &query=BSONObj(), int options=0, int limit=0, int skip=0)
 count number of objects in collection ns that match the query criteria specified throws UserAssertion if database returns an error
 
virtual bool isMaster (bool &isMaster, BSONObj *info=0)
 returns true in isMaster parm if this db is the current master of a replica pair. More...
 
bool createCollection (const string &ns, long long size=0, bool capped=false, int max=0, BSONObj *info=0)
 Create a new collection in the database. More...
 
string getLastError (const std::string &db, bool fsync=false, bool j=false, int w=0, int wtimeout=0)
 Get error result from the last write operation (insert/update/delete) on this connection. More...
 
string getLastError (bool fsync=false, bool j=false, int w=0, int wtimeout=0)
 Same as the form of getLastError that takes a dbname, but just uses the admin DB.
 
virtual BSONObj getLastErrorDetailed (const std::string &db, bool fsync=false, bool j=false, int w=0, int wtimeout=0)
 Get error result from the last write operation (insert/update/delete) on this connection. More...
 
virtual BSONObj getLastErrorDetailed (bool fsync=false, bool j=false, int w=0, int wtimeout=0)
 Same as the form of getLastErrorDetailed that takes a dbname, but just uses the admin DB.
 
BSONObj getPrevError ()
 Return the last error which has occurred, even if not the very last operation. More...
 
bool resetError ()
 Reset the previous error state for this connection (accessed via getLastError and getPrevError). More...
 
virtual bool dropCollection (const string &ns, BSONObj *info=NULL)
 Delete the specified collection. More...
 
bool repairDatabase (const string &dbname, BSONObj *info=0)
 Perform a repair and compaction of the specified database. More...
 
bool copyDatabase (const string &fromdb, const string &todb, const string &fromhost="", BSONObj *info=0)
 Copy database from one server or name to another server or name. More...
 
bool setDbProfilingLevel (const string &dbname, ProfilingLevel level, BSONObj *info=0)
 
bool getDbProfilingLevel (const string &dbname, ProfilingLevel &level, BSONObj *info=0)
 
BSONObj mapreduce (const string &ns, const string &jsmapf, const string &jsreducef, BSONObj query=BSONObj(), MROutput output=MRInline)
 Run a map/reduce job on the server. More...
 
bool eval (const string &dbname, const string &jscode, BSONObj &info, BSONElement &retValue, BSONObj *args=0)
 Run javascript code on the database server. More...
 
bool validate (const string &ns, bool scandata=true)
 validate a collection, checking for errors and reporting back statistics. More...
 
bool eval (const string &dbname, const string &jscode)
 
template<class T >
bool eval (const string &dbname, const string &jscode, T parm1)
 
template<class T , class NumType >
bool eval (const string &dbname, const string &jscode, T parm1, NumType &ret)
 eval invocation with one parm to server and one numeric field (either int or double) returned
 
list< string > getDatabaseNames ()
 get a list of all the current databases uses the { listDatabases : 1 } command. More...
 
list< string > getCollectionNames (const string &db)
 get a list of all the current collections in db
 
bool exists (const string &ns)
 
virtual bool ensureIndex (const string &ns, BSONObj keys, bool unique=false, const string &name="", bool cache=true, bool background=false, int v=-1, int ttl=0)
 Create an index if it does not already exist. More...
 
virtual void resetIndexCache ()
 clears the index cache, so the subsequent call to ensureIndex for any index will go to the server
 
virtual auto_ptr< DBClientCursorgetIndexes (const string &ns)
 
virtual void dropIndex (const string &ns, BSONObj keys)
 
virtual void dropIndex (const string &ns, const string &indexName)
 
virtual void dropIndexes (const string &ns)
 drops all indexes for the collection
 
virtual void reIndex (const string &ns)
 
string genIndexName (const BSONObj &keys)
 
virtual bool dropDatabase (const string &dbname, BSONObj *info=0)
 Erase / drop an entire database.
 
virtual void setRunCommandHook (RunCommandHookFunc func)
 
RunCommandHookFunc getRunCommandHook () const
 
virtual void setPostRunCommandHook (PostRunCommandHookFunc func)
 
PostRunCommandHookFunc getPostRunCommandHook () const
 
- Public Member Functions inherited from mongo::DBClientInterface
virtual BSONObj findOne (const string &ns, const Query &query, const BSONObj *fieldsToReturn=0, int queryOptions=0)
 
void findN (vector< BSONObj > &out, const string &ns, Query query, int nToReturn, int nToSkip=0, const BSONObj *fieldsToReturn=0, int queryOptions=0)
 query N objects from the database into an array. More...
 

Static Public Member Functions

static int getNumConnections ()
 
static void setLazyKillCursor (bool lazy)
 
static bool getLazyKillCursor ()
 
- Static Public Member Functions inherited from mongo::DBClientWithCommands
static string createPasswordDigest (const string &username, const string &clearTextPassword)
 
static string getLastErrorString (const BSONObj &res)
 Can be called with the returned value from getLastErrorDetailed to extract an error string. More...
 

Protected Member Functions

virtual void _auth (const BSONObj &params)
 
virtual void sayPiggyBack (Message &toSend)
 
void _checkConnection ()
 
void checkConnection ()
 
bool _connect (string &errmsg)
 
- Protected Member Functions inherited from mongo::DBClientWithCommands
bool isOk (const BSONObj &)
 if the result of a command is ok
 
bool isNotMasterErrorString (const BSONElement &e)
 if the element contains a not master error
 
BSONObj _countCmd (const string &ns, const BSONObj &query, int options, int limit, int skip)
 
QueryOptions availableOptions ()
 Look up the options available on this client. More...
 
virtual QueryOptions _lookupAvailableOptions ()
 
bool _authMongoCR (const string &dbname, const string &username, const string &pwd, BSONObj *info, bool digestPassword)
 Use the MONGODB-CR protocol to authenticate as "username" against the database "dbname", with the given password. More...
 
bool _authX509 (const string &dbname, const string &username, BSONObj *info)
 Use the MONGODB-X509 protocol to authenticate as "username. More...
 

Protected Attributes

DBClientReplicaSetclientSet
 
boost::scoped_ptr< MessagingPortp
 
boost::scoped_ptr< SockAddrserver
 
bool _failed
 
const bool autoReconnect
 
Backoff autoReconnectBackoff
 
HostAndPort _server
 
string _serverString
 
string _serverAddrString
 
map< string, BSONObjauthCache
 
double _so_timeout
 
- Protected Attributes inherited from mongo::DBClientBase
long long _connectionId
 
WriteConcern _writeConcern
 
int _minWireVersion
 
int _maxWireVersion
 
- Protected Attributes inherited from mongo::DBClientWithCommands
RunCommandHookFunc _runCommandHook
 These functions will be executed by the driver on runCommand calls.
 
PostRunCommandHookFunc _postRunCommandHook
 

Static Protected Attributes

static AtomicUInt _numConnections
 
static bool _lazyKillCursor = true
 
- Static Protected Attributes inherited from mongo::DBClientBase
static AtomicInt64 ConnectionIdSequence
 

Friends

class SyncClusterConnection
 

Additional Inherited Members

- Public Types inherited from mongo::DBClientWithCommands
enum  ProfilingLevel { ProfileOff = 0, ProfileSlow = 1, ProfileAll = 2 }
 The Mongo database provides built-in performance profiling capabilities. More...
 
typedef boost::function< void(BSONObjBuilder *)> RunCommandHookFunc
 A function type for runCommand hooking; the function takes a pointer to a BSONObjBuilder and returns nothing. More...
 
typedef boost::function< void(const
BSONObj &, const std::string &)> 
PostRunCommandHookFunc
 Similar to above, but for running a function on a command response after a command has been run.
 
- Public Attributes inherited from mongo::DBClientWithCommands
logger::LogSeverity _logLevel
 controls how chatty the client is about network errors & such. More...
 
- Static Public Attributes inherited from mongo::DBClientBase
static const uint64_t INVALID_SOCK_CREATION_TIME
 
- Static Public Attributes inherited from mongo::DBClientWithCommands
static MROutput MRInline
 

Detailed Description

A basic connection to the database.

This is the main entry point for talking to a simple Mongo setup

Constructor & Destructor Documentation

mongo::DBClientConnection::DBClientConnection ( bool  _autoReconnect = false,
DBClientReplicaSet cp = 0,
double  so_timeout = 0 
)
inline
Parameters
_autoReconnectif true, automatically reconnect on a connection failure
cpused by DBClientReplicaSet. You do not need to specify this parameter
timeouttcp timeout in seconds - this is for read/write, not connect. Connect timeout is fixed, but short, at 5 seconds.

Member Function Documentation

virtual bool mongo::DBClientConnection::connect ( const char *  hostname,
string &  errmsg 
)
inlinevirtual

Connect to a Mongo database server.

If autoReconnect is true, you can try to use the DBClientConnection even when false was returned – it will try to connect again.

Parameters
serverHostnamehost to connect to. can include port number ( 127.0.0.1 , 127.0.0.1:5555 ) If you use IPv6 you must add a port number ( ::1:27017 )
errmsgany relevant error message will appended to the string
Deprecated:
please use HostAndPort
Returns
false if fails to connect.
bool mongo::DBClientConnection::connect ( const HostAndPort server,
string &  errmsg 
)
virtual

Connect to a Mongo database server.

If autoReconnect is true, you can try to use the DBClientConnection even when false was returned – it will try to connect again.

Parameters
serverserver to connect to.
errmsgany relevant error message will appended to the string
Returns
false if fails to connect.
void mongo::DBClientConnection::connect ( const string &  serverHostname)
inline

Connect to a Mongo database server.

Exception throwing version. Throws a UserException if cannot connect.

If autoReconnect is true, you can try to use the DBClientConnection even when false was returned – it will try to connect again.

Parameters
serverHostnamehost to connect to. can include port number ( 127.0.0.1 , 127.0.0.1:5555 )
bool mongo::DBClientConnection::isFailed ( ) const
inlinevirtual
Returns
true if this connection is currently in a failed state. When autoreconnect is on, a connection will transition back to an ok state after reconnecting.

Implements mongo::DBClientBase.

void mongo::DBClientConnection::logout ( const string &  dbname,
BSONObj info 
)
virtual

Logs out the connection for the given database.

Parameters
dbnamethe database to logout from.
infothe result object for the logout command (provided for backwards compatibility with mongo shell)

Reimplemented from mongo::DBClientWithCommands.

virtual auto_ptr<DBClientCursor> mongo::DBClientConnection::query ( const string &  ns,
Query  query = Query(),
int  nToReturn = 0,
int  nToSkip = 0,
const BSONObj fieldsToReturn = 0,
int  queryOptions = 0,
int  batchSize = 0 
)
inlinevirtual

send a query to the database.

Parameters
nsnamespace to query, format is <dbname>.<collectname>[.<collectname>]*
queryquery to perform on the collection. this is a BSONObj (binary JSON) You may format as { query: { ... }, orderby: { ... } } to specify a sort order.
nToReturnn to return (i.e., limit). 0 = unlimited
nToSkipstart with the nth item
fieldsToReturnoptional template of which fields to select. if unspecified, returns all fields
queryOptionssee options enum at top of this file
Returns
cursor. 0 if error (connection failure)
Exceptions
AssertionException

Reimplemented from mongo::DBClientBase.

bool mongo::DBClientConnection::runCommand ( const string &  dbname,
const BSONObj cmd,
BSONObj info,
int  options = 0 
)
virtual

Run a database command.

Database commands are represented as BSON objects. Common database commands have prebuilt helper functions – see below. If a helper is not available you can directly call runCommand.

Parameters
dbnamedatabase name. Use "admin" for global administrative commands.
cmdthe command object to execute. For example, { ismaster : 1 }
infothe result object the database returns. Typically has { ok : ..., errmsg : ... } fields set.
optionssee enum QueryOptions - normally not needed to run a command
authif set, the BSONObj representation will be appended to the command object sent
Returns
true if the command returned "ok".

Reimplemented from mongo::DBClientWithCommands.

void mongo::DBClientConnection::setReplSetClientCallback ( DBClientReplicaSet rsClient)

Primarily used for notifying the replica set client that the server it is talking to is not primary anymore.

Parameters
rsClientcaller is responsible for managing the life of rsClient and making sure that it lives longer than this object.

Warning: This is only for internal use and will eventually be removed in the future.


The documentation for this class was generated from the following files: