execute() 공개 메소드

Runs JavaScript code on the database server.
public execute ( MongoCode | string $code, array $args = [] ) : array
$code MongoCode | string Code to execute.
$args array [optional] Arguments to be passed to code.
리턴 array Returns the result of the evaluation.
예제 #1
0
 public function onExecute(\UniMapper\Adapter\IQuery $query)
 {
     $result = $this->database->execute($query->getRaw());
     $callback = $query->callback;
     if ($callback) {
         return $callback($result);
     }
     return $result;
 }
예제 #2
0
    /**
     * 插入新的行,_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"];
    }
예제 #3
0
파일: MDb.php 프로젝트: myurasov/rockmongo
 /**
  * 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"];
 }
예제 #4
0
 public function testExecute()
 {
     $ret = $this->object->execute('4+3*6');
     $this->assertEquals($ret['retval'], 22, json_encode($ret));
     $ret = $this->object->execute(new MongoCode('function() { return x+y; }', array('x' => 'hi', 'y' => 'bye')));
     $this->assertEquals($ret['retval'], 'hibye', json_encode($ret));
     $ret = $this->object->execute(new MongoCode('function(x) { return x+y; }', array('y' => 'bye')), array('bye'));
     $this->assertEquals($ret['retval'], 'byebye', json_encode($ret));
 }
 public function getDeviceFallBackTree($wurflID)
 {
     $this->numQueries++;
     $response = $this->dbcon->execute('function(deviceID){ return performFallback(deviceID) }', array($wurflID));
     $data = $response['retval'];
     if ($data[count($data) - 1]['id'] != WurflConstants::$GENERIC) {
         $tw = new TeraWurfl();
         $tw->toLog("WURFL Error: device {$data[count($data) - 1]['id']} falls back on an inexistent device: {$data[count($data) - 1]['fall_back']}", LOG_ERR, __CLASS__ . '::' . __FUNCTION__);
     }
     return $data;
 }
예제 #6
0
파일: MDb.php 프로젝트: Briareos/rockmongo
 /**
  * List collections in a DB
  *
  * @param MongoDB $db DB
  * @return array<MongoCollection>
  */
 static function listCollections(MongoDB $db)
 {
     $server = MServer::currentServer();
     $names = array();
     $query = $db->execute("function (){ return db.getCollectionNames(); }", array());
     if ($query["ok"]) {
         $names = $query["retval"];
     } else {
         $colls = $db->listCollections(true);
         foreach ($colls as $coll) {
             $names[] = $coll->getName();
         }
     }
     $ret = array();
     foreach ($names as $name) {
         if ($server->shouldHideCollection($name)) {
             continue;
         }
         if (preg_match("/^system\\./", $name)) {
             continue;
         }
         $ret[] = $name;
     }
     sort($ret);
     //system collections
     if (!$server->uiHideSystemCollections()) {
         foreach ($names as $name) {
             if ($server->shouldHideCollection($name)) {
                 continue;
             }
             if (preg_match("/^system\\./", $name)) {
                 $ret[] = $name;
             }
         }
     }
     $collections = array();
     foreach ($ret as $v) {
         if ($v === "") {
             //older MongoDB version (maybe before 1.7) allow empty collection name
             continue;
         }
         $collections[] = $db->selectCollection($v);
     }
     return $collections;
 }
예제 #7
0
    private function _runJson()
    {
        $timezone = date_default_timezone_get();
        date_default_timezone_set("UTC");
        $ret = $this->_db->execute('function () {
			if (typeof(ISODate) == "undefined") {
				function ISODate (isoDateStr) {
				    if (!isoDateStr) {
				        return new Date;
				    }
				    var isoDateRegex = /(\\d{4})-?(\\d{2})-?(\\d{2})([T ](\\d{2})(:?(\\d{2})(:?(\\d{2}(\\.\\d+)?))?)?(Z|([+-])(\\d{2}):?(\\d{2})?)?)?/;
				    var res = isoDateRegex.exec(isoDateStr);
				    if (!res) {
				        throw "invalid ISO date";
				    }
				    var year = parseInt(res[1], 10) || 1970;
				    var month = (parseInt(res[2], 10) || 1) - 1;
				    var date = parseInt(res[3], 10) || 0;
				    var hour = parseInt(res[5], 10) || 0;
				    var min = parseInt(res[7], 10) || 0;
				    var sec = parseFloat(res[9]) || 0;
				    var ms = Math.round(sec % 1 * 1000);
				    sec -= ms / 1000;
				    var time = Date.UTC(year, month, date, hour, min, sec, ms);
				    if (res[11] && res[11] != "Z") {
				        var ofs = 0;
				        ofs += (parseInt(res[13], 10) || 0) * 60 * 60 * 1000;
				        ofs += (parseInt(res[14], 10) || 0) * 60 * 1000;
				        if (res[12] == "+") {
				            ofs *= -1;
				        }
				        time += ofs;
				    }
				    return new Date(time);
				};
			}
			return ' . $this->_source . ';}');
        date_default_timezone_set($timezone);
        if ($ret["ok"]) {
            return $ret["retval"];
        }
        return false;
    }
예제 #8
0
 /**
  * Execute
  *
  * @param  string                          $sql
  * @throws Exception\InvalidQueryException
  * @return Result
  */
 public function execute($sql)
 {
     if (!$this->isConnected()) {
         $this->connect();
     }
     try {
         if ($this->profiler) {
             $this->profiler->profilerStart($sql);
         }
         $resultResource = $this->db->execute($sql);
         if ($this->profiler) {
             $this->profiler->profilerFinish($sql);
         }
         // if the returnValue is something other than a mysqli_result, bypass wrapping it
         if (!$resultResource['ok']) {
             throw new Exception\InvalidQueryException($resultResource['errmsg']);
         }
     } catch (\Exception $e) {
         throw new Exception\InvalidQueryException($ex->getMessage(), $ex->getCode());
     }
     $resultPrototype = $this->driver->createResult($resultResource === true ? $this->resource : $resultResource);
     return $resultResource['retval'];
 }
 /**
  * read collection information
  *
  * @param MongoDB $db database
  * @param string $collection collection name
  */
 static function info(MongoDB $db, $collection)
 {
     $ret = $db->execute('function (coll){return db.getCollection(coll).exists();}', array($collection));
     if (!$ret["ok"]) {
         exit("There is something wrong:<font color=\"red\">{$ret['errmsg']}</font>, please refresh the page to try again.");
     }
     if (!isset($ret["retval"]["options"])) {
         $ret["retval"]["options"] = array();
     }
     $isCapped = 0;
     $size = 0;
     $max = 0;
     $options = $ret["retval"]["options"];
     if (isset($options["capped"])) {
         $isCapped = $options["capped"];
     }
     if (isset($options["size"])) {
         $size = $options["size"];
     }
     if (isset($options["max"])) {
         $max = $options["max"];
     }
     return array("capped" => $isCapped, "size" => $size, "max" => $max);
 }
예제 #10
0
 /**
  * Enter description here...
  *
  * @param MongoDB $db
  * @param unknown_type $from
  * @param unknown_type $to
  * @param unknown_type $index
  */
 protected function _copyCollection($db, $from, $to, $index = true)
 {
     if ($index) {
         $indexes = $db->selectCollection($from)->getIndexInfo();
         foreach ($indexes as $index) {
             $options = array();
             if (isset($index["unique"])) {
                 $options["unique"] = $index["unique"];
             }
             if (isset($index["name"])) {
                 $options["name"] = $index["name"];
             }
             if (isset($index["background"])) {
                 $options["background"] = $index["background"];
             }
             if (isset($index["dropDups"])) {
                 $options["dropDups"] = $index["dropDups"];
             }
             $db->selectCollection($to)->ensureIndex($index["key"], $options);
         }
     }
     $ret = $db->execute('function (coll, coll2) { return db.getCollection(coll).copyTo(coll2);}', array($from, $to));
     return $ret["ok"];
 }
예제 #11
0
 /** collection statistics **/
 public function doCollectionStats()
 {
     $this->db = x("db");
     $this->collection = xn("collection");
     $this->stats = array();
     $db = new MongoDB($this->_mongo, $this->db);
     $ret = $db->execute("db.{$this->collection}.stats()");
     if ($ret["ok"]) {
         $this->stats = $ret["retval"];
         foreach ($this->stats as $index => $stat) {
             if (is_array($stat)) {
                 $this->stats[$index] = $this->_highlight($stat, "json");
             }
         }
     }
     //top
     $ret = $this->_mongo->selectDB("admin")->command(array("top" => 1));
     $this->top = array();
     $namespace = $this->db . "." . $this->collection;
     if ($ret["ok"] && !empty($ret["totals"][$namespace])) {
         $this->top = $ret["totals"][$namespace];
         foreach ($this->top as $index => $value) {
             $this->top[$index] = $value["count"];
         }
     }
     $this->display();
 }
 /**
  * Executes a native JS MongoDB command
  * This method is not currently used for anything
  * @param string $cmd
  * @return mixed
  */
 protected function _exec($cmd)
 {
     $exec = $this->mongo->execute($cmd);
     return $exec['retval'];
 }
예제 #13
0
 /**
  * Wrapper method for MongoDB::execute().
  *
  * @see http://php.net/manual/en/mongodb.execute.php
  * @return array
  */
 public function execute($code, array $args = [])
 {
     return $this->mongoDB->execute($code, $args);
 }
예제 #14
0
 protected function _call($command, array $arguments = array(), array $values = NULL)
 {
     $this->_connected or $this->connect();
     extract($arguments);
     $_bm_name = isset($collection_name) ? $collection_name . '.' . $command : $command;
     if (isset($collection_name)) {
         $c = $this->_db->selectCollection($collection_name);
     }
     switch ($command) {
         case 'ensure_index':
             $r = $c->ensureIndex($keys, $options);
             break;
         case 'create_collection':
             $r = $this->_db->createCollection($name, $capped, $size, $max);
             break;
         case 'drop_collection':
             $r = $this->_db->dropCollection($name);
             break;
         case 'command':
             $r = $this->_db->command($values);
             break;
         case 'execute':
             $r = $this->_db->execute($code, $args);
             break;
         case 'batch_insert':
             $r = $c->batchInsert($values);
             break;
         case 'count':
             $r = $c->count($query);
             break;
         case 'find_one':
             $r = $c->findOne($query, $fields);
             break;
         case 'find':
             $r = $c->find($query, $fields);
             break;
         case 'group':
             $r = $c->group($keys, $initial, $reduce, $condition);
             break;
         case 'update':
             $r = $c->update($criteria, $values, $options);
             break;
         case 'insert':
             $r = $c->insert($values, $options);
             break;
         case 'remove':
             $r = $c->remove($criteria, $options);
             break;
         case 'save':
             $r = $c->save($values, $options);
             break;
         case 'get_file':
             $r = $this->gridFS()->findOne($criteria);
             break;
         case 'get_files':
             $r = $this->gridFS()->find($query, $fields);
             break;
         case 'set_file_bytes':
             $r = $this->gridFS()->storeBytes($bytes, $extra, $options);
             break;
         case 'set_file':
             $r = $this->gridFS()->storeFile($filename, $extra, $options);
             break;
         case 'remove_file':
             $r = $this->gridFS()->remove($criteria, $options);
             break;
     }
     if (isset($_bm)) {
         Profiler::stop($_bm);
     }
     return $r;
 }
예제 #15
0
 /**
  * execute.
  */
 public function execute($code, array $args = array())
 {
     $this->time->start();
     $return = parent::execute($code, $args);
     $time = $this->time->stop();
     $this->log(array('type' => 'execute', 'code' => $code, 'args' => $args, 'time' => $time));
     return $return;
 }
예제 #16
0
    private function _runJson()
    {
        $timezone = @date_default_timezone_get();
        date_default_timezone_set("UTC");
        $ret = $this->_db->execute('function () {
			if (typeof(ISODate) == "undefined") {
				function ISODate (isoDateStr) {
				    if (!isoDateStr) {
				        return new Date;
				    }
				    var isoDateRegex = /(\\d{4})-?(\\d{2})-?(\\d{2})([T ](\\d{2})(:?(\\d{2})(:?(\\d{2}(\\.\\d+)?))?)?(Z|([+-])(\\d{2}):?(\\d{2})?)?)?/;
				    var res = isoDateRegex.exec(isoDateStr);
				    if (!res) {
				        throw "invalid ISO date";
				    }
				    var year = parseInt(res[1], 10) || 1970;
				    var month = (parseInt(res[2], 10) || 1) - 1;
				    var date = parseInt(res[3], 10) || 0;
				    var hour = parseInt(res[5], 10) || 0;
				    var min = parseInt(res[7], 10) || 0;
				    var sec = parseFloat(res[9]) || 0;
				    var ms = Math.round(sec % 1 * 1000);
				    sec -= ms / 1000;
				    var time = Date.UTC(year, month, date, hour, min, sec, ms);
				    if (res[11] && res[11] != "Z") {
				        var ofs = 0;
				        ofs += (parseInt(res[13], 10) || 0) * 60 * 60 * 1000;
				        ofs += (parseInt(res[14], 10) || 0) * 60 * 1000;
				        if (res[12] == "+") {
				            ofs *= -1;
				        }
				        time += ofs;
				    }
				    return new Date(time);
				};
			};
				
			function r_util_convert_empty_object_to_string(obj) {
				if (r_util_is_empty(obj)) {
					return "__EMPTYOBJECT__";
				}
				if (typeof(obj) == "object") {
					for (var k in obj) {
						obj[k] = r_util_convert_empty_object_to_string(obj[k]);
					}
				}
				return obj;
			};
				
			function r_util_is_empty(obj) {
				if (obj == null || typeof(obj) != "object" || (obj.constructor != Object)) {
					return false;
				}
			    for(var k in obj) {
			        if(obj.hasOwnProperty(k)) {
			            return false;
					}
			    }
			
			    return true;
			};
			var o = ' . $this->_source . '; return r_util_convert_empty_object_to_string(o); }');
        $this->_fixEmptyObject($ret);
        date_default_timezone_set($timezone);
        if ($ret["ok"]) {
            return $ret["retval"];
        }
        return json_decode($this->_source, true);
    }
예제 #17
0
 public function query($query, $bind = array())
 {
     $this->_connect();
     return $this->_db->execute($query);
 }