public function tearDown() { if ($this->db instanceof \MongoDB) { $this->db->drop(); } parent::tearDown(); }
/** * @access protected */ protected function setUp() { $m = new Mongo(); $db = new MongoDB($m, "phpunit"); $this->object = $db->selectCollection('c'); $this->object->drop(); }
public function getCollection($collName) { if (!$this->database) { throw new Exception\LogicException("Can't select collection as there's no database set"); } return $this->database->selectCollection($collName); }
/** * Fetches the object pointed to by a reference * @link http://php.net/manual/en/mongodbref.get.php * @static * @param MongoDB $db Database to use * @param array $ref Reference to fetch * @return array|null Returns the document to which the reference refers or null if the document does not exist (the reference is broken) */ public static function get($db, $ref) { if (!static::isRef($ref)) { return null; } return $db->selectCollection($ref[static::$refKey])->findOne(['_id' => $ref[static::$idKey]]); }
public static function getChannelCollection() { if (MongoConnector::$db == null) { MongoConnector::connect(); } return MongoConnector::$db->selectCollection("channels"); }
/** * Evaluates the constraint for parameter $other. Returns TRUE if the * constraint is met, FALSE otherwise. * * @param mixed $other Value or object to evaluate. * @return bool */ public function evaluate($other) { $query = array('_id' => $other); $data = $this->db->selectCollection($this->collection)->findOne($query); $this->found = $data[$this->property]; return ($this->found == $this->expected); }
public function testAuthBasic() { $ok = $this->object->authenticate("testUser", "testPass"); $this->assertEquals($ok['ok'], 1, json_encode($ok)); $ok = $this->object->authenticate("testUser", "bar"); $this->assertEquals($ok['ok'], 0, json_encode($ok)); }
/** * Creates new file collections * * @param mongodb $db - Database. * @param string $prefix - * @param mixed $chunks - */ public function __construct(MongoDB $db, $prefix = 'fs', $chunks = 'fs') { $this->db = $db; $thisName = $prefix . '.files'; $this->chunksName = $prefix . '.chunks'; $this->chunks = $db->selectCollection($this->chunksName); parent::__construct($db, $thisName); }
public function __construct(\MongoDB $db, $collection_name, array $additional_find_fields = []) { if (false === is_string($collection_name)) { throw new Exception('collection name must be a string'); } $this->collection = $db->selectCollection($collection_name); $this->additional_find_fields = $additional_find_fields; }
/** * Execute a piece of javascript code * * @param MongoDB $db DB * @param string $code javascript code * @param array $params javascript function parameters * @return array */ static function exec(MongoDB $db, $code, array $params = array()) { $query = $db->execute($code, $params); if (!$query["ok"]) { exit("Execute failed:<font color=\"red\">" . $query["errmsg"] . "</font><br/>\n<pre>" . $code . "</pre>"); } return $query["retval"]; }
/** * Constructor. * * @param Connection $connection Connection used to create Collections * @param \MongoDB $mongoDB MongoDB instance being wrapped * @param EventManager $evm EventManager instance * @param integer $numRetries Number of times to retry queries * @param callable $loggerCallable The logger callable */ public function __construct(Connection $connection, $mongoDB, EventManager $evm, $numRetries, $loggerCallable) { if (!is_callable($loggerCallable)) { throw new \InvalidArgumentException('$loggerCallable must be a valid callback'); } parent::__construct($evm, $mongoDB->getDatabaseName()); $this->loggerCallable = $loggerCallable; }
public function setUp() { parent::setUp(); $this->mongo = new MongoDB(new \MongoClient('mongodb://localhost:27017'), 'mongo_test', new InMemoryCache()); $this->collection = $this->mongo->selectCollection('test'); for ($i = 0; $i < 2; $i++) { $this->collection->insert(['foo' => 1]); } }
public function onExecute(\UniMapper\Adapter\IQuery $query) { $result = $this->database->execute($query->getRaw()); $callback = $query->callback; if ($callback) { return $callback($result); } return $result; }
/** * Retrieves a collection by name. * @param $name * @return MongoCollection */ public function collection($name) { if ($this->collections[$name]) { return $this->collections[$name]; } $c = $this->mongo_db->selectCollection($name); $this->collections[$name] = $c; return $c; }
/** * Evaluates the constraint for parameter $other. Returns TRUE if the * constraint is met, FALSE otherwise. * * @param mixed $other Value or object to evaluate. * @return bool */ public function evaluate($other) { $exists = false; $collections = $this->db->listCollections(); $collectionNames = array(); foreach ($collections as $collection) { $collectionNames[] = $collection->getName(); } return !\in_array($other, $collectionNames); }
/** * @param Client $client * @param \MongoDB|string $database */ public function __construct(Client $client, $database) { $this->client = $client; if ($database instanceof \MongoDB) { $this->database = $database; $this->databaseName = $database->__toString(); } else { $this->databaseName = $database; } }
public function __construct($host, $port, $name, $username, $password) { try { $client = new \MongoClient("mongodb://{$host}:{$port}"); $this->db = new \MongoDB($client, $name); $this->db->authenticate($username, $password); } catch (\MongoException $e) { die('Connection failed: ' . $e->getMessage()); } }
/** * Evaluates the constraint for parameter $other. Returns TRUE if the * constraint is met, FALSE otherwise. * * @param mixed $other Value or object to evaluate. * @return bool */ public function evaluate($other) { $documentExists = false; $query = array('_id' => $other); $data = $this->db->selectCollection($this->collection)->findOne($query); if (!empty($data)) { $documentExists = true; } return $documentExists; }
public function testTest() { return; $mongo = new MongoDB(new \MongoClient('mongodb://localhost:27017'), 'mongo_test', new Memcache($this->memcache, 1)); $collection = $mongo->selectCollection('test_memcache'); $collection->insert(['foo' => 1]); $this->assertEquals(1, $collection->count()); sleep(1); $collection->insert(['foo' => 1]); $this->assertEquals(2, $collection->count()); }
/** * Connects to our database */ public function connect() { if (!extension_loaded('mongo')) { throw new EMongoException(yii::t('yii', 'We could not find the MongoDB extension ( http://php.net/manual/en/mongo.installation.php ), please install it')); } try { $this->_mongo = new MongoClient($this->connectionString, $this->connectOptions); $dbname = $this->db; $this->_db = $this->_mongo->{$dbname}; $this->_db->setWriteConcern($this->options['writeConcerns'], $this->options['wTimeoutMS']); } catch (Exception $e) { throw new EMongoException(yii::t('yii', 'We could not find the MongoDB extension ( http://php.net/manual/en/mongo.installation.php ), please install it')); } }
/** * Communicates with the database to log in a user. * * @param MongoDB $db database * @param string $username username * @param string $pwd plaintext password * * @return array the database response */ protected static function getUser($db, $username, $pwd) { $ns = "{$db}.system.users"; // get the nonce $result = $db->command(array(MongoUtil::NONCE => 1)); if (!$result["ok"]) { return $result; } $nonce = $result["nonce"]; // create a digest of nonce/username/pwd $digest = md5($nonce . $username . $pwd); $data = array(MongoUtil::AUTHENTICATE => 1, "user" => $username, "nonce" => $nonce, "key" => $digest); // send everything to the db and pray return $db->command($data); }
/** * Files as stored across two collections, the first containing file meta * information, the second containing chunks of the actual file. By default, * fs.files and fs.chunks are the collection names used. * * @link http://php.net/manual/en/mongogridfs.construct.php * @param MongoDB $db Database * @param string $prefix [optional] <p>Optional collection name prefix.</p> * @param mixed $chunks [optional] * @throws \Exception */ public function __construct(MongoDB $db, $prefix = "fs", $chunks = null) { if ($chunks) { trigger_error("The 'chunks' argument is deprecated and ignored", E_DEPRECATED); } if (empty($prefix)) { throw new \Exception('MongoGridFS::__construct(): invalid prefix'); } $this->database = $db; $this->prefix = (string) $prefix; $this->filesName = $prefix . '.files'; $this->chunksName = $prefix . '.chunks'; $this->chunks = $db->selectCollection($this->chunksName); parent::__construct($db, $this->filesName); }
public function __construct(MongoPlus $mongo, $name) { $this->_mongo = $mongo; // $this->_mongo_id = md5(microtime(1)); // $this->ref_mongo($mongo); parent::__construct($mongo, $name); }
/** * Delete the database with all documents, it will be recreated on * next access. * * @return void */ public function resetStorage() { $collectioNames = $this->database->listCollections(); foreach ($collectioNames as $collectionName) { $this->database->dropCollection($collectionName); } }
/** * Return an array of stored tags * * @return array array of stored tags (string) */ public function getTags() { $cmd['mapreduce'] = $this->_options['collection']; $cmd['map'] = 'function(){ this.t.forEach( function(z){ emit( z , { count : 1 } ); } ); };'; $cmd['reduce'] = 'function( key , values ){ var total = 0; for ( var i=0; i<values.length; i++ ) total += values[i].count; return { count : total }; };'; $cmd['out'] = array('replace' => 'getTagsCollection'); $res2 = $this->_db->command($cmd); $res3 = $this->_db->selectCollection('getTagsCollection')->find(); $res = array(); foreach ($res3 as $key => $val) { $res[] = $key; } $this->_db->dropCollection($res2['result']); return $res; }
/** * 插入新的行,_id是上一行的ID加1 * * @param array $attrs 新行的属性集 * @return boolean */ function insertNext(array $attrs) { $response = $this->_db->execute('function insertObject(o, myCollection) { var x = db.getCollection(myCollection); while( 1 ) { // determine next _id value to try var c = x.find({},{_id:1}).sort({_id:-1}).limit(1); var i = c.hasNext() ? c.next()._id + 1 : 1; o._id = i; x.insert(o); var err = db.getLastErrorObj(); if( err && err.code ) { if( err.code == 11000 /* dup key */ ) continue; else print("unexpected error inserting data: " + tojson(err)); } break; } return o._id; }', array($attrs, $this->_collectionName)); if ($response["ok"]) { import("@.RMongo"); RMongo::setLastInsertId($response["retval"]); } return $response["ok"]; }
/** * Imports data into the current collection * * @param string $collection * @param array $data * @param string $importMethod Valid options are batchInsert, save, insert, update */ public function import($collection, array $data, $importMethod) { $coll = $this->mongo->selectCollection($collection); switch ($importMethod) { case 'batchInsert': foreach ($data as &$obj) { $obj = unserialize($obj); } $coll->{$importMethod}($data); break; case 'update': foreach ($data as $obj) { $obj = unserialize($obj); if (is_object($obj) && property_exists($obj, '_id')) { $_id = $obj->_id; } else { if (is_array($obj) && isset($obj['_id'])) { $_id = $obj['_id']; } else { continue; } } $coll->{$importMethod}(array('_id' => $_id), $obj); } break; default: //insert & save foreach ($data as $obj) { $coll->{$importMethod}(unserialize($obj)); } break; } }
/** * Instantiate class * @param $dsn string * @param $dbname string * @param $options array **/ function __construct($dsn, $dbname, array $options = NULL) { $this->uuid = \Base::instance()->hash($this->dsn = $dsn); $class = class_exists('\\MongoClient') ? '\\MongoClient' : '\\Mongo'; parent::__construct(new $class($dsn, $options ?: array()), $dbname); $this->setprofilinglevel(2); }
/** * Drop the database * * @return boolean */ public function drop() { $ok = $this->db->drop(); if (1 == (int) $ok['ok']) { return true; } return false; }
/** * Purges the cache deleting all items within it. * * @return boolean True on success. False otherwise. */ public function purge() { if ($this->isready) { $this->collection->drop(); $this->collection = $this->database->selectCollection($this->definitionhash); } return true; }