Connect to the Mongo server using the MongoDB extension.
355027
protected function setupMongoDB($dsn, $options)
    {
        try {
            $this->client = new \MongoDB\Client($dsn, $options);
            $this->dbh    = $this->client->selectDatabase($this->dbName);
        } catch (\MongoDB\Driver\Exception $e) {
            throw new ModuleException($this, sprintf('Failed to open Mongo connection: %s', $e->getMessage()));
        }
    }
46960
function DocumentServer(socket, connection, modelDirectory) {
  this.changeDispatch = new ChangeDispatch( this.handleDocumentChange.bind(this)
                                          , this.handleCollectionChange.bind(this))

  this.db = DatabaseMethods(connection, ChangeDispatch)
  Document.prototype.db = this.db
  this.connection = connection
  this.setSocket(socket)
  this.embeddedIds = {}
  this.modelDirectory = modelDirectory
}
287985
function connect(dbUri, debugFlag, mongos) {
    var deferred = Q.defer();
    var opts = {
        server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } },
        replset: { socketOptions: { keepAlive: 1, connectTimeoutMS : 30000 } }
    };

    if (mongos) {
        opts.mongos = true;
    }

    mongoose.set('debug', debugFlag);

    // make sure we disconnect any other existing connections
    mongoose.disconnect(function () {
        mongoose.connect(dbUri, opts, function (err)  {
            err ? deferred.reject(err) : deferred.resolve();
        });
    });

    return deferred.promise;
}
264703
function MongoDB () {
  var self = this;

  self.klass = MongoDB;
  self.klass.super_.apply(self, arguments);
}
499203
def connect(self):
        
        self.client = redis.Redis(
            host=self.host, port=self.port, password=self.password)
714100
def connect(self):
        """"""
        if not getattr(self._local, 'conn', None):
            try:
                server = self._servers.get()
                logger.debug('Connecting to %s', server)
                self._local.conn = ClientTransport(server, self._framed_transport,
                    self._timeout, self._recycle)
            except (Thrift.TException, socket.timeout, socket.error):
                logger.warning('Connection to %s failed.', server)
                self._servers.mark_dead(server)
                return self.connect()
        return self._local.conn
1365943
def try_mongodb_opts(self, host="localhost", database_name='INGInious'):
        
        try:
            mongo_client = MongoClient(host=host)
        except Exception as e:
            self._display_warning("Cannot connect to MongoDB on host %s: %s" % (host, str(e)))
            return None

        try:
            database = mongo_client[database_name]
        except Exception as e:
            self._display_warning("Cannot access database %s: %s" % (database_name, str(e)))
            return None

        try:
            GridFS(database)
        except Exception as e:
            self._display_warning("Cannot access gridfs %s: %s" % (database_name, str(e)))
            return None

        return database
907390
def _construct_mongos(self, logpath, port, configdb):
        """"""
        extra = ''

        auth_param = ''
        if self.args['auth']:
            key_path = os.path.abspath(os.path.join(self.dir, 'keyfile'))
            auth_param = '--keyFile %s' % key_path

        if self.unknown_args:
            extra = self._filter_valid_arguments(self.unknown_args,
                                                 "mongos") + extra

        extra += ' ' + self._get_ssl_server_args()

        path = self.args['binarypath'] or ''
        if os.name == 'nt':
            newlogpath = logpath.replace('\\', '\\\\')
            command_str = ("start /b %s --logpath \"%s\" --port %i --configdb %s "
                           "%s %s " % (os.path.join(path, 'mongos'),
                                       newlogpath, port, configdb,
                                       auth_param, extra))
        else:
            command_str = ("%s --logpath \"%s\" --port %i --configdb %s %s %s "
                           "--fork" % (os.path.join(path, 'mongos'), logpath,
                                       port, configdb, auth_param, extra))

        # store parameters in startup_info
        self.startup_info[str(port)] = command_str
1351681
def connect(uri, factory=pymongo.MongoClient):
    
    warnings.warn(
        "do not use. Just call MongoClient directly.", DeprecationWarning)
    return factory(uri)
469130
function initMongo(config, callback) {
  
  var self = this;
  
  // Set db
  self.db = new Db(config.database, new Server(config.host, config.port, {}), {safe: true});
  
  // Get client
  self.db.open(function(err, client) {
    if (err) throw err;
    else {
      self.client = client;
      client.collectionNames(function(err, names) {
        if (err) throw err;
        else {
          var name = config.database + '.' + config.collection;
          var exists = names.filter(function(col) {
            if (col.name == name) return col; 
          });
          
          // Collection options
          var opts = {capped: true, size: config.logSize};
          if (config.logLimit != null) opts.max = config.logLimit;
          
          if (exists.length === 0) {
            client.createCollection(config.collection, opts, function(err, collection) {
              if (err) throw err;
              else {
                self.collection = collection;
                callback.call(self);
              }
            });
          } else {
            // Get collection
            client.collection(config.collection, function(err, collection) {
              if (err) throw err;
              else {
                self.collection = collection;
                // Get collection options » Check if collection has already been capped
                collection.options(function(err, options) {
                  if (err) {
                    throw err;
                  } else {
                    // Check if collection's options match log requirements
                    var ready = (options.capped === true && options.size === opts.size);
                    if ('max' in opts) ready = (ready && options.max === opts.max);
                    if (!ready) {
                      // Convert collection to capped if it's not match log requirements
                      var cmd = {"convertToCapped": config.collection, size: opts.size};
                      if ('max' in opts) cmd.max = opts.max;
                      client.command(cmd, function(err) {
                        if (err) throw err;
                        else {
                          callback.call(self);
                        }
                      });
                    } else {
                      callback.call(self);
                    }
                  }
                });
              }
            });
          }
        }
      });
    }
  });
}
151514
def configure(self, options, conf):
        
        # This option has to be specified on the command line, to enable the
        # plugin.
        if not options.mongoengine or options.mongodb_bin:
            return

        if not options.mongodb_bin:
            self.mongodb_param['mongodb_bin'] = scan_path()
            if self.mongodb_param['mongodb_bin'] is None:
                raise AssertionError(
                    "Mongoengine plugin enabled, but no mongod on path, "
                    "please specify path to binary\n"
                    "ie. --mongoengine-mongodb=/path/to/mongod")
        else:
            self.mongodb_param['mongodb_bin'] = os.path.abspath(
                os.path.expanduser(os.path.expandvars(options.mongodb_bin)))
            if not os.path.exists(self.mongodb_param['mongodb_bin']):
                raise AssertionError(
                    "Invalid mongodb binary %r" % \
                    self.mongodb_param['mongodb_bin'])

        # Its necessary to enable in nose
        self.enabled = True

        db_log_path = os.path.expandvars(os.path.expanduser(
            options.mongodb_logpath))
        try:
            db_file = open(db_log_path, "w")
            db_file.close()
        except Exception as exc:
            raise AssertionError("Invalid log path %r" % exc)

        if not options.mongodb_port:
            self.mongodb_param['db_port'] = get_open_port()
        else:
            self.mongodb_param['db_port'] = options.mongodb_port

        db_prealloc = options.mongodb_prealloc
        db_scripting = options.mongodb_scripting

        self.clear_context['module'] = options.mongoengine_clear_after_module
        self.clear_context['class'] = options.mongoengine_clear_after_class

        # generate random database name
        self.database_name = str(uuid.uuid1())

        #########################################
        # Start a instance of mongo
        #########################################

        # Stores data here
        self.mongodb_param['db_path'] = tempfile.mkdtemp()
        if not os.path.exists(self.mongodb_param['db_path']):
            os.mkdir(self.mongodb_param['db_path'])

        args = [
            self.mongodb_param['mongodb_bin'],
            "--dbpath",
            self.mongodb_param['db_path'],
            "--port",
            str(self.mongodb_param['db_port']),
            # don't flood stdout, we're not reading it
            "--quiet",
            # save the port
            "--nohttpinterface",
            # disable unused.
            "--nounixsocket",
            # use a smaller default file size
            "--smallfiles",
            # journaling on by default in 2.0 and makes it to slow
            # for tests, can causes failures in jenkins
            "--nojournal",
            # Default is /dev/null
            "--logpath",
            db_log_path,
            "-vvvvv"
            ]

        if not db_prealloc:
            args.append("--noprealloc")

        if not db_scripting:
            args.append("--noscripting")

        self.process = Popen(
            args,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT
            )

        self._running = True
        os.environ["TEST_MONGODB"] = "localhost:%s" % \
                                     self.mongodb_param['db_port']
        os.environ["TEST_MONGODB_DATABASE"] = self.database_name

        # Give a moment for mongodb to finish coming up
        time.sleep(0.3)

        # Connecting using mongoengine
        self.connection = connect(self.database_name, host="localhost",
                port=self.mongodb_param['db_port'])
599868
def connect(self):
        """"""
        log.info('Connecting socket on %s:%d' % (self.server, self.port))
        tries = 0
        while not self._socket and tries < 10:
            try:
                time.sleep(.2 * tries)
                self._socket = Socket((self.server, self.port))
            except socket.error:
                tries += 1
                log.warning(
                    'You must start/install wdb.server '
                    '(Retrying on %s:%d) [Try #%d/10]' %
                    (self.server, self.port, tries)
                )
                self._socket = None

        if not self._socket:
            log.warning('Could not connect to server')
            return

        Wdb._sockets.append(self._socket)
        self._socket.send_bytes(self.uuid.encode('utf-8'))
1064690
function connect(mongodbUri, callback) {
  snapdb.connect(mongodbUri, function(err, client) {
    if (err) return callback(err);
    callback(null, client);
  });
}
313135
public function connect()
    {

        if ($this->_connection && $this->_connection->connect()) {
            return true;
        }
        /**
         * Add required variables
         * Clear the connection parameters for security
         */
        $config = $this->_config['connection'] + array(
                'hostnames'  => 'localhost:27017'
        );

        unset($this->_config['connection']);

        /* Add Username & Password to server string */
        if (isset($config['username']) && isset($config['password'])) {
            $config['hostnames'] = $config['username'] . ':' . $config['password'] . '@' . $config['hostnames'] . '/' . $config['database'];
        }

        /* Add required 'mongodb://' prefix */
        if (strpos($config['hostnames'], 'mongodb://') !== 0) {
            $config['hostnames'] = 'mongodb://' . $config['hostnames'];
        }

        if (!isset($config['options']) || !is_array($config['options'])) {
            $config['options'] = array();
        }

        /* Create connection object, attempt to connect */
        $config['options']['connect'] = false;

        $class = '\MongoClient';
        if (!class_exists($class)) {
            $class = '\Mongo';
        }

        $this->_connection = new $class($config['hostnames'], $config['options']);

        /* Try connect */
        try {
            $this->_connection->connect();
        } catch (\MongoConnectionException $e) {
            throw new \Exception('Unable to connect to MongoDB server at ' . $config['hostnames']);
        }

        if (!isset($config['database'])) {
            throw new \Exception('No database specified in MangoDB Config');
        }

        $this->_db = $this->_connection->selectDB($config['database']);

        if(!$this->_db instanceof \MongoDB) {
            throw new \Exception('Unable to connect to database :: $_db is ' . gettype($this->_db));
        }
        
        $this->_connected = true;

        return true;
    }
123491
def connection(self, collectionname, dbname=None):
        
        if not collectionname or ".." in collectionname:
            raise DataError("collection names cannot be empty")
        if "$" in collectionname and not (collectionname.startswith("oplog.$main") or
                                collectionname.startswith("$cmd")):
            raise DataError("collection names must not "
                              "contain '$': %r" % collectionname)
        if collectionname.startswith(".") or collectionname.endswith("."):
            raise DataError("collecion names must not start "
                            "or end with '.': %r" % collectionname)
        if "\x00" in collectionname:
            raise DataError("collection names must not contain the "
                              "null character")
        return Cursor(dbname or self._pool._dbname, collectionname, self._pool)
1300093
public function initialize()
    {
        if ($this->mongoClient !== null) {
            return;
        }

        if ($this->eventManager->hasListeners(Events::preConnect)) {
            $this->eventManager->dispatchEvent(Events::preConnect, new EventArgs($this));
        }

        $server = $this->server ?: 'mongodb://localhost:27017';
        $options = $this->options;

        $options = isset($options['timeout']) ? $this->convertConnectTimeout($options) : $options;
        $options = isset($options['wTimeout']) ? $this->convertWriteTimeout($options) : $options;

        $this->mongoClient = $this->retry(function() use ($server, $options) {
            return new \MongoClient($server, $options, $this->driverOptions);
        });

        if ($this->eventManager->hasListeners(Events::postConnect)) {
            $this->eventManager->dispatchEvent(Events::postConnect, new EventArgs($this));
        }
    }
766763
def connect(self, **kwargs):
        ''' 
        '''
        if 'database' not in kwargs:
            kwargs['database'] = 'ait'

        self._conn = self._backend.connect(kwargs['database'])