Exemplo n.º 1
0
 public function query($type, $sql, $as_object = FALSE, array $params = NULL)
 {
     $this->_connection or $this->connect();
     if (JsonApiApplication::$profiling) {
         $benchmark = Profiler::start("Database ({$this->_instance})", $sql);
     }
     try {
         $result = $this->_connection->query($sql);
     } catch (Exception $e) {
         if (isset($benchmark)) {
             Profiler::delete($benchmark);
         }
         throw new Database_Exception(':error [ :query ]', array(':error' => $e->getMessage(), ':query' => $sql), $e->getCode());
     }
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     $this->last_query = $sql;
     if ($type === Database::SELECT) {
         if ($as_object === FALSE) {
             $result->setFetchMode(PDO::FETCH_ASSOC);
         } elseif (is_string($as_object)) {
             $result->setFetchMode(PDO::FETCH_CLASS, $as_object, $params);
         } else {
             $result->setFetchMode(PDO::FETCH_CLASS, 'stdClass');
         }
         $result = $result->fetchAll();
         return new Database_Result_Cached($result, $sql, $as_object, $params);
     } elseif ($type === Database::INSERT) {
         return array($this->_connection->lastInsertId(), $result->rowCount());
     } else {
         return $result->rowCount();
     }
 }
Exemplo n.º 2
0
 /**
  * Processes the request, executing the controller. Before the routed action
  * is run, the before() method will be called, which allows the controller
  * to overload the action based on the request parameters. After the action
  * is run, the after() method will be called, for post-processing.
  *
  * By default, the output from the controller is captured and returned, and
  * no headers are sent.
  *
  * @return  $this
  */
 public function execute()
 {
     // Create the class prefix
     $prefix = 'controller_';
     if (!empty($this->directory)) {
         // Add the directory name to the class prefix
         $prefix .= str_replace(array('\\', '/'), '_', trim($this->directory, '/')) . '_';
     }
     if (Kohana::$profiling === TRUE) {
         // Start benchmarking
         $benchmark = Profiler::start('Requests', $this->uri);
     }
     try {
         // Load the controller using reflection
         $class = new ReflectionClass($prefix . $this->controller);
         if ($class->isAbstract()) {
             throw new Kohana_Exception('Cannot create instances of abstract :controller', array(':controller' => $prefix . $this->controller));
         }
         // Create a new instance of the controller
         $controller = $class->newInstance($this);
         // Execute the "before action" method
         $class->getMethod('before')->invoke($controller);
         // Determine the action to use
         $action = empty($this->action) ? Route::$default_action : $this->action;
         // Ensure the action exists, and use __call() if it doesn't
         if ($class->hasMethod('action_' . $action)) {
             // Execute the main action with the parameters
             $class->getMethod('action_' . $action)->invokeArgs($controller, $this->_params);
         } else {
             $class->getMethod('__call')->invokeArgs($controller, array($action, $this->_params));
         }
         // Execute the "after action" method
         $class->getMethod('after')->invoke($controller);
     } catch (Exception $e) {
         if (isset($benchmark)) {
             // Delete the benchmark, it is invalid
             Profiler::delete($benchmark);
         }
         if ($e instanceof ReflectionException) {
             // Reflection will throw exceptions for missing classes or actions
             $this->status = 404;
         } else {
             // All other exceptions are PHP/server errors
             $this->status = 500;
         }
         // Re-throw the exception
         throw $e;
     }
     if (isset($benchmark)) {
         // Stop the benchmark
         Profiler::stop($benchmark);
     }
     return $this;
 }
Exemplo n.º 3
0
 /**
  * Note: $type is ignored. Reason being, $type is unnecessary for returning correct results, 
  * and in some cases results will not correspond with $type - examples:
  * "select * into outfile..."
  * "insert into...on duplicate key update"
  * Also, for insert queries on tables without an autoincrement id, only rows affected 
  * need be returned.
  * 
  * @param string $type ignored
  * @param string $sql
  * @param boolean $as_object
  * @return object PDO result
  */
 public function query($type, $sql, $as_object)
 {
     // Make sure the database is connected
     $this->_connection or $this->connect();
     if (!empty($this->_config['profiling'])) {
         // Benchmark this query for the current instance
         $benchmark = Profiler::start("Database ({$this->_instance})", $sql);
     }
     try {
         $result = $this->_connection->query($sql);
     } catch (Exception $e) {
         if (isset($benchmark)) {
             // This benchmark is worthless
             Profiler::delete($benchmark);
         }
         // Rethrow the exception
         throw $e;
     }
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     // Set the last query
     $this->last_query = $sql;
     if ($result->columnCount() > 0) {
         // Convert the result into an array, as PDOStatement::rowCount is not reliable
         if ($as_object === FALSE) {
             $result->setFetchMode(PDO::FETCH_ASSOC);
         } elseif (is_string($as_object)) {
             $result->setFetchMode(PDO::FETCH_CLASS, $as_object);
         } else {
             $result->setFetchMode(PDO::FETCH_CLASS, 'stdClass');
         }
         $result = $result->fetchAll();
         // Return an iterator of results
         return new Database_Result_Cached($result, $sql, $as_object);
     } else {
         $insert_id = $this->_connection->lastInsertId();
         if ($insert_id > 0) {
             return array($insert_id, $result->rowCount());
         } else {
             // Return the number of rows affected
             return $result->rowCount();
         }
     }
 }
Exemplo n.º 4
0
Arquivo: pdo.php Projeto: artsec/test1
 public function query($type, $sql, $as_object)
 {
     // Make sure the database is connected
     $this->_connection or $this->connect();
     if (!empty($this->_config['profiling'])) {
         // Benchmark this query for the current instance
         $benchmark = Profiler::start("Database ({$this->_instance})", $sql);
     }
     try {
         $result = $this->_connection->query($sql);
     } catch (Exception $e) {
         if (isset($benchmark)) {
             // This benchmark is worthless
             Profiler::delete($benchmark);
         }
         // Convert the exception in a database exception
         throw new Database_Exception(':error [ :query ]', array(':error' => $e->getMessage(), ':query' => $sql), $e->getCode(), $e);
     }
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     // Set the last query
     $this->last_query = $sql;
     if ($type === Database::SELECT) {
         // Convert the result into an array, as PDOStatement::rowCount is not reliable
         if ($as_object === FALSE) {
             $result->setFetchMode(PDO::FETCH_ASSOC);
         } elseif (is_string($as_object)) {
             $result->setFetchMode(PDO::FETCH_CLASS, $as_object);
         } else {
             $result->setFetchMode(PDO::FETCH_CLASS, 'stdClass');
         }
         $result = $result->fetchAll();
         // Return an iterator of results
         return new Database_Result_Cached($result, $sql, $as_object);
     } elseif ($type === Database::INSERT) {
         // Return a list of insert id and rows created
         return array($result->rowCount());
     } else {
         // Return the number of rows affected
         return $result->rowCount();
     }
 }
Exemplo n.º 5
0
 public function query($sql, $as_object = FALSE)
 {
     $sql_type = '';
     if (preg_match('/^SELECT/i', $sql) || preg_match('/^SHOW/i', $sql)) {
         $sql_type = 'select';
     } elseif (preg_match('/^INSERT/i', $sql)) {
         $sql_type = 'insert';
     }
     $this->connect($sql_type == 'select' ? 'slave' : 'master');
     if (Kohana::$profiling) {
         $benchmark = Profiler::start("Database ({$this->_instance})", $sql);
     }
     try {
         $result = $this->_conn->query($sql);
     } catch (Exception $e) {
         if (isset($benchmark)) {
             Profiler::delete($benchmark);
         }
         throw new Kohana_Exception(':error [ :query ]', array(':error' => $e->getMessage(), ':query' => $sql), $e->getCode());
     }
     if (Kohana::$profiling) {
         Profiler::stop($benchmark);
     }
     $this->last_query = $sql;
     //var_dump($this->last_query);
     if ($sql_type == 'select') {
         if ($as_object === FALSE) {
             $result->setFetchMode(PDO_bak::FETCH_ASSOC);
         } elseif (is_string($as_object)) {
             $result->setFetchMode(PDO_bak::FETCH_CLASS, $as_object);
         } else {
             $result->setFetchMode(PDO_bak::FETCH_CLASS, 'stdClass');
         }
         $result = $result->fetchAll();
         return new Database_Result_Cached($result, $sql, $as_object);
     } elseif ($sql_type == 'insert') {
         return array($this->_conn->lastInsertId(), $result->rowCount());
     } else {
         return $result->rowCount();
     }
 }
Exemplo n.º 6
0
 /**
  * Note: $type is ignored. Reason being, $type is unnecessary for returning correct results, 
  * and in some cases results will not correspond with $type - examples:
  * "select * into outfile..."
  * "insert into...on duplicate key update"
  * Also, for insert queries on tables without an autoincrement id, there is no insert id to
  * return.
  * 
  * @param string $type ignored
  * @param string $sql
  * @param boolean $as_object
  * @return object mysql result
  */
 public function query($type, $sql, $as_object)
 {
     // Make sure the database is connected
     $this->_connection or $this->connect();
     if (!empty($this->_config['profiling'])) {
         // Benchmark this query for the current instance
         $benchmark = Profiler::start("Database ({$this->_instance})", $sql);
     }
     if (!empty($this->_config['connection']['persistent']) and $this->_config['connection']['database'] !== Database_MySQL::$_current_databases[$this->_connection_id]) {
         // Select database on persistent connections
         $this->_select_db($this->_config['connection']['database']);
     }
     // Execute the query
     if (($result = mysql_query($sql, $this->_connection)) === FALSE) {
         if (isset($benchmark)) {
             // This benchmark is worthless
             Profiler::delete($benchmark);
         }
         throw new Database_Exception(':error [ :query ]', array(':error' => mysql_error($this->_connection), ':query' => $sql), mysql_errno($this->_connection));
     }
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     // Set the last query
     $this->last_query = $sql;
     if (!is_bool($result)) {
         // Return an iterator of results
         return new Database_MySQL_Result($result, $sql, $as_object);
     } else {
         $insert_id = mysql_insert_id($this->_connection);
         if ($insert_id > 0) {
             return array($insert_id, mysql_affected_rows($this->_connection));
         } else {
             // Return the number of rows affected
             return mysql_affected_rows($this->_connection);
         }
     }
 }
Exemplo n.º 7
0
 public function query($type, $sql, $as_object = FALSE, array $params = NULL)
 {
     // Make sure the database is connected
     $this->_connection or $this->connect();
     if (Kohana::$profiling && stripos($sql, 'explain') !== 0) {
         // Benchmark this query for the current instance
         $benchmark = Profiler::start("Database ({$this->_instance})", $sql);
     }
     if (!empty($this->_config['connection']['persistent']) and $this->_config['connection']['database'] !== Database_MySQL::$_current_databases[$this->_connection_id]) {
         // Select database on persistent connections
         $this->_select_db($this->_config['connection']['database']);
     }
     // Execute the query
     if (($result = mysql_query($sql, $this->_connection)) === FALSE) {
         if (isset($benchmark)) {
             // This benchmark is worthless
             Profiler::delete($benchmark);
         }
         throw new Database_Exception(':error [ :query ]', array(':error' => mysql_error($this->_connection), ':query' => $sql), mysql_errno($this->_connection));
     }
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     // Set the last query
     $this->last_query = $sql;
     if ($type === Database::SELECT) {
         // Return an iterator of results
         $res = new Database_MySQL_Result($result, $sql, $as_object, $params);
         if (stripos($sql, 'explain') !== 0) {
             ProfilerToolbar::setSqlData($this->_instance, $sql, $res->count());
         }
         return $res;
     } elseif ($type === Database::INSERT) {
         // Return a list of insert id and rows created
         $res = array(mysql_insert_id($this->_connection), mysql_affected_rows($this->_connection));
         ProfilerToolbar::setSqlData($this->_instance, $sql, $res[1]);
         return $res;
     } else {
         // Return the number of rows affected
         $res = mysql_affected_rows($this->_connection);
         ProfilerToolbar::setSqlData($this->_instance, $sql, $res);
         return $res;
     }
 }
Exemplo n.º 8
0
 /**
  * Query the database
  *
  * @param integer $type
  * @param string  $sql
  * @param mixed   $as_object
  *
  * @return mixed
  *
  * @throws \Database_Exception
  */
 public function query($type, $sql, $as_object)
 {
     // Make sure the database is connected
     $this->_connection or $this->connect();
     if (!empty($this->_config['profiling'])) {
         // Get the paths defined in config
         $paths = \Config::get('profiling_paths');
         // Storage for the trace information
         $stacktrace = array();
         // Get the execution trace of this query
         $include = false;
         foreach (debug_backtrace() as $index => $page) {
             // Skip first entry and entries without a filename
             if ($index > 0 and empty($page['file']) === false) {
                 // Checks to see what paths you want backtrace
                 foreach ($paths as $index => $path) {
                     if (strpos($page['file'], $path) !== false) {
                         $include = true;
                         break;
                     }
                 }
                 // Only log if no paths we defined, or we have a path match
                 if ($include or empty($paths)) {
                     $stacktrace[] = array('file' => \Fuel::clean_path($page['file']), 'line' => $page['line']);
                 }
             }
         }
         $benchmark = \Profiler::start($this->_instance, $sql, $stacktrace);
     }
     // run the query. if the connection is lost, try 3 times to reconnect
     $attempts = 3;
     do {
         try {
             // try to run the query
             $result = $this->_connection->query($sql);
             break;
         } catch (\Exception $e) {
             // if failed and we have attempts left
             if ($attempts > 0) {
                 // try reconnecting if it was a MySQL disconnected error
                 if (strpos($e->getMessage(), '2006 MySQL') !== false) {
                     $this->disconnect();
                     $this->connect();
                 } else {
                     // other database error, cleanup the profiler
                     isset($benchmark) and \Profiler::delete($benchmark);
                     // and convert the exception in a database exception
                     if (!is_numeric($error_code = $e->getCode())) {
                         if ($this->_connection) {
                             $error_code = $this->_connection->errorinfo();
                             $error_code = $error_code[1];
                         } else {
                             $error_code = 0;
                         }
                     }
                     throw new \Database_Exception($e->getMessage() . ' with query: "' . $sql . '"', $error_code, $e);
                 }
             } else {
                 // and convert the exception in a database exception
                 if (!is_numeric($error_code = $e->getCode())) {
                     if ($this->_connection) {
                         $error_code = $this->_connection->errorinfo();
                         $error_code = $error_code[1];
                     } else {
                         $error_code = 0;
                     }
                 }
                 throw new \Database_Exception($e->getMessage() . ' with query: "' . $sql . '"', $error_code, $e);
             }
         }
     } while ($attempts-- > 0);
     if (isset($benchmark)) {
         \Profiler::stop($benchmark);
     }
     // Set the last query
     $this->last_query = $sql;
     if ($type === \DB::SELECT) {
         // Convert the result into an array, as PDOStatement::rowCount is not reliable
         if ($as_object === false) {
             $result = $result->fetchAll(\PDO::FETCH_ASSOC);
         } elseif (is_string($as_object)) {
             $result = $result->fetchAll(\PDO::FETCH_CLASS, $as_object);
         } else {
             $result = $result->fetchAll(\PDO::FETCH_CLASS, 'stdClass');
         }
         // Return an iterator of results
         return new \Database_Result_Cached($result, $sql, $as_object);
     } elseif ($type === \DB::INSERT) {
         // Return a list of insert id and rows created
         return array($this->_connection->lastInsertId(), $result->rowCount());
     } elseif ($type === \DB::UPDATE or $type === \DB::DELETE) {
         // Return the number of rows affected
         return $result->errorCode() === '00000' ? $result->rowCount() : -1;
     }
     return $result->errorCode() === '00000' ? true : false;
 }
Exemplo n.º 9
0
 /**
  * @param string $method method of PDOStatement to be called
  * @param mixed $mode    parameters to be passed to the method
  * @param array $params  input parameters (name=>value) for the SQL execution. This is an alternative
  *                       to {@link bindParam} and {@link bindValue}. If you have multiple input parameters, passing
  *                       them in this way can improve the performance. Note that if you pass parameters in this way,
  *                       you cannot bind parameters or values using {@link bindParam} or {@link bindValue}, and vice versa.
  *                       Please also note that all values are treated as strings in this case, if you need them to be handled as
  *                       their real data types, you have to use {@link bindParam} or {@link bindValue} instead.
  * @throws Exception if CDbCommand failed to execute the SQL statement
  * @return mixed the method execution result
  */
 private function queryInternal($method, $mode, $params = [])
 {
     $params = array_merge($this->params, $params);
     if ($this->_connection->enableParamLogging && ($pars = array_merge($this->_paramLog, $params)) !== []) {
         $p = [];
         foreach ($pars as $name => $value) {
             $p[$name] = $name . '=' . var_export($value, true);
         }
         $par = '. Bound with ' . implode(', ', $p);
     } else {
         $par = '';
     }
     //var_echo('Querying SQL: ' . $this->getText() . $par, 'system.db.CDbCommand');
     if ($this->_connection->queryCachingCount > 0 && $method !== '' && $this->_connection->queryCachingDuration > 0 && $this->_connection->queryCacheID !== false) {
         #TODO Сделать систему кеширования Sql запросов
         /*$this->_connection->queryCachingCount--;
         		$cacheKey='yii:dbquery'.$this->_connection->connectionString.':'.$this->_connection->username;
         		$cacheKey.=':'.$this->getText().':'.serialize(array_merge($this->_paramLog,$params));
         		if(($result=$cache->get($cacheKey))!==false)
         		{
         			var_echo('Query result found in cache','system.db.CDbCommand');
         			return $result[0];
         		}*/
     }
     try {
         if (\Kohana::$profiling and $this->_connection->enableProfiling) {
             // Benchmark this query for the current instance
             //var_dump($this->getText());
             foreach ($params as $item) {
                 //var_echo($item);
             }
             //str_replace('')
             $benchmark = \Profiler::start("Database ('default')", $this->Debug($this->getText(), $this->_paramLog) . $par);
         }
         $this->prepare();
         if ($params === []) {
             $this->_statement->execute();
         } else {
             $this->_statement->execute($params);
         }
         if ($method === '') {
             $result = new DataReader($this);
         } else {
             $mode = (array) $mode;
             call_user_func_array([$this->_statement, 'setFetchMode'], $mode);
             $result = $this->_statement->{$method}();
             $this->_statement->closeCursor();
         }
         if (\Kohana::$profiling and $this->_connection->enableProfiling) {
             //var_dump($this->getText());
             \ProfilerToolbar::setSqlData('default', $this->Debug($this->getText(), $this->_paramLog), sizeof($result));
         }
         if (isset($cache, $cacheKey)) {
             \Cache::instance('database')->set($this->getText(), $result, $this->_connection->caching);
         }
         return $result;
     } catch (Exception $e) {
         if (isset($benchmark)) {
             // This benchmark is worthless
             \Profiler::delete($benchmark);
         }
         $errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
         $message = $e->getMessage();
         \Kohana::$log->add(\Log::EMERGENCY, '\\Database\\Command::' . $method . ' failed ' . $message . '. The SQL statement executed was: ' . $this->getText() . $par);
         if (\Kohana::DEVELOPMENT) {
             $message .= '. The SQL statement executed was: ' . $this->getText() . $par;
         }
         throw new Exception('\\Database\\Command failed to execute the SQL statement: ' . $message, (int) $e->getCode(), $errorInfo);
     }
 }
Exemplo n.º 10
0
 public function query($type, $sql, $as_object = FALSE, array $params = NULL)
 {
     // Make sure the database is connected
     $this->_connection or $this->connect();
     // Mssql specific
     if (preg_match("/OFFSET ([0-9]+)/i", $sql, $matches)) {
         list($replace, $offset) = $matches;
         $sql = str_replace($replace, '', $sql);
     }
     if (preg_match("/LIMIT ([0-9]+)/i", $sql, $matches)) {
         list($replace, $limit) = $matches;
         $sql = str_replace($replace, '', $sql);
     }
     if (isset($limit) || isset($offset)) {
         if (!isset($offset)) {
             $sql = preg_replace("/^(SELECT|DELETE|UPDATE)\\s/i", "\$1 TOP " . $limit . ' ', $sql);
         } else {
             $orderby = stristr($sql, 'ORDER BY');
             if (!$orderby) {
                 $over = 'ORDER BY (SELECT 0)';
             } else {
                 $over = preg_replace('/[^,\\s]*\\.([^,\\s]*)/i', 'inner_tbl.$1', $orderby);
             }
             // Remove ORDER BY clause from $sql
             $sql = preg_replace('/\\s+ORDER BY(.*)/', '', $sql);
             // Add ORDER BY clause as an argument for ROW_NUMBER()
             $sql = "SELECT ROW_NUMBER() OVER ({$over}) AS KOHANA_DB_ROWNUM, * FROM ({$sql}) AS inner_tbl";
             $start = $offset + 1;
             $end = $offset + $limit;
             $sql = "WITH outer_tbl AS ({$sql}) SELECT * FROM outer_tbl WHERE KOHANA_DB_ROWNUM BETWEEN {$start} AND {$end}";
         }
     }
     if (!empty($this->_config['profiling'])) {
         // Benchmark this query for the current instance
         $benchmark = Profiler::start("Database ({$this->_instance})", $sql);
     }
     try {
         $result = $this->_connection->query($sql);
     } catch (Exception $e) {
         if (isset($benchmark)) {
             // This benchmark is worthless
             Profiler::delete($benchmark);
         }
         // Rethrow the exception
         throw $e;
     }
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     // Set the last query
     $this->last_query = $sql;
     if ($type === Database::SELECT) {
         // Convert the result into an array, as PDOStatement::rowCount is not reliable
         if ($as_object === FALSE) {
             $result->setFetchMode(PDO::FETCH_ASSOC);
         } elseif (is_string($as_object)) {
             $result->setFetchMode(PDO::FETCH_CLASS, $as_object);
         } else {
             $result->setFetchMode(PDO::FETCH_CLASS, 'stdClass');
         }
         $result = $result->fetchAll();
         // Return an iterator of results
         return new Database_Result_Cached($result, $sql, $as_object);
     } elseif ($type === Database::INSERT) {
         // Return a list of insert id and rows created
         return array($this->insert_id(), $result->rowCount());
     } else {
         // Return the number of rows affected
         return $result->rowCount();
     }
 }
Exemplo n.º 11
0
 public function query($type, $sql, $as_object)
 {
     // Make sure the database is connected
     $this->_connection or $this->connect();
     if (!empty($this->_config['profiling'])) {
         // Benchmark this query for the current instance
         $benchmark = Profiler::start("Database ({$this->_instance})", $sql);
     }
     if (!empty($this->_config['connection']['persistent']) and $this->_config['connection']['database'] !== static::$_current_databases[$this->_connection_id]) {
         // Select database on persistent connections
         $this->_select_db($this->_config['connection']['database']);
     }
     // Execute the query
     if (($result = mysql_query($sql, $this->_connection)) === FALSE) {
         if (isset($benchmark)) {
             // This benchmark is worthless
             Profiler::delete($benchmark);
         }
         throw new \Database_Exception(mysql_error($this->_connection) . ' [ ' . $sql . ' ]', mysql_errno($this->_connection));
     }
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     // Set the last query
     $this->last_query = $sql;
     if ($type === \Database::SELECT) {
         // Return an iterator of results
         return new \Database_MySQL_Result($result, $sql, $as_object);
     } elseif ($type === \Database::INSERT) {
         // Return a list of insert id and rows created
         return array(mysql_insert_id($this->_connection), mysql_affected_rows($this->_connection));
     } else {
         // Return the number of rows affected
         return mysql_affected_rows($this->_connection);
     }
 }
Exemplo n.º 12
0
 public function query($type, $sql, $as_object)
 {
     // Make sure the database is connected
     if ($this->_connection) {
         // Make sure the connection is still alive
         if (!$this->_connection->ping()) {
             throw new \Database_Exception($this->_connection->error . ' [ ' . $sql . ' ]', $this->_connection->errno);
         }
     } else {
         $this->connect();
     }
     if (!empty($this->_config['profiling'])) {
         // Get the paths defined in config
         $paths = \Config::get('profiling_paths');
         // Storage for the trace information
         $stacktrace = array();
         // Get the execution trace of this query
         $include = false;
         foreach (debug_backtrace() as $index => $page) {
             // Skip first entry and entries without a filename
             if ($index > 0 and empty($page['file']) === false) {
                 // Checks to see what paths you want backtrace
                 foreach ($paths as $index => $path) {
                     if (strpos($page['file'], $path) !== false) {
                         $include = true;
                         break;
                     }
                 }
                 // Only log if no paths we defined, or we have a path match
                 if ($include or empty($paths)) {
                     $stacktrace[] = array('file' => Fuel::clean_path($page['file']), 'line' => $page['line']);
                 }
             }
         }
         $benchmark = \Profiler::start("Database ({$this->_instance})", $sql, $stacktrace);
     }
     if (!empty($this->_config['connection']['persistent']) and $this->_config['connection']['database'] !== static::$_current_databases[$this->_connection_id]) {
         // Select database on persistent connections
         $this->_select_db($this->_config['connection']['database']);
     }
     // Execute the query
     if (($result = $this->_connection->query($sql)) === false) {
         if (isset($benchmark)) {
             // This benchmark is worthless
             \Profiler::delete($benchmark);
         }
         throw new \Database_Exception($this->_connection->error . ' [ ' . $sql . ' ]', $this->_connection->errno);
     }
     // check for multiresults, we don't support those at the moment
     while ($this->_connection->more_results() and $this->_connection->next_result()) {
         if ($more_result = $this->_connection->use_result()) {
             throw new \Database_Exception('The MySQLi driver does not support multiple resultsets', 0);
         }
     }
     if (isset($benchmark)) {
         \Profiler::stop($benchmark);
     }
     // Set the last query
     $this->last_query = $sql;
     if ($type === \DB::SELECT) {
         // Return an iterator of results
         return new \Database_MySQLi_Result($result, $sql, $as_object);
     } elseif ($type === \DB::INSERT) {
         // Return a list of insert id and rows created
         return array($this->_connection->insert_id, $this->_connection->affected_rows);
     } else {
         // Return the number of rows affected
         return $this->_connection->affected_rows;
     }
 }
Exemplo n.º 13
0
 public function query($type, $sql, $as_object)
 {
     // Make sure the database is connected
     $this->_connection or $this->connect();
     if (!empty($this->_config['profiling'])) {
         // Benchmark this query for the current instance
         $benchmark = Profiler::start("Database ({$this->_instance})", $sql);
     }
     if (!empty($this->_config['connection']['persistent']) and $this->_config['connection']['database'] !== static::$_current_databases[$this->_connection_id]) {
         // Select database on persistent connections
         $this->_select_db($this->_config['connection']['database']);
     }
     // Execute the query
     if (($result = $this->_connection->query($sql)) === FALSE) {
         if (isset($benchmark)) {
             // This benchmark is worthless
             Profiler::delete($benchmark);
         }
         if ($type !== \DB::SELECT && $this->_trans_enabled) {
             // If we are using transactions, throwing an exception would defeat the purpose
             // We need to log the failures for transaction status
             if (!is_array($this->trans_errors)) {
                 $this->trans_errors = array();
             }
             $this->trans_errors[] = $this->_connection->errno . ': ' . $this->_connection->error . ' [ ' . $sql . ' ]';
         } else {
             throw new \Database_Exception($this->_connection->error . ' [ ' . $sql . ' ]', $this->_connection->errno);
         }
     }
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     // Set the last query
     $this->last_query = $sql;
     if ($type === \DB::SELECT) {
         // Return an iterator of results
         return new \Database_MySQLi_Result($result, $sql, $as_object);
     } elseif ($type === \DB::INSERT) {
         // Return a list of insert id and rows created
         return array($this->_connection->insert_id, $this->_connection->affected_rows);
     } else {
         // Return the number of rows affected
         return $this->_connection->affected_rows;
     }
 }
Exemplo n.º 14
0
 public function query($type, $sql, $as_object = FALSE, array $params = NULL)
 {
     // Make sure the database is connected
     $this->_connection or $this->connect();
     if (!empty($this->_config['profiling'])) {
         // Benchmark this query for the current instance
         $benchmark = Profiler::start("Database ({$this->_instance})", $sql);
     }
     // Detect type Database::INSERT and ensure last id is captured
     if ($type === Database::INSERT) {
         // We need to do some magic here to get the insert ID
         // this is a glorious hack!
         $sql_statement = (string) $sql;
         // Locate VALUES
         $values = strpos($sql, 'VALUES');
         // Insert the lastInsertId logic
         $sql = substr($sql_statement, 0, $values) . 'output inserted.identitycol AS lastInsertId ' . substr($sql_statement, $values);
     }
     // Execute the query
     if (($result = sqlsrv_query($this->_connection, $sql, $params, array('Scrollable' => SQLSRV_CURSOR_KEYSET))) === FALSE) {
         // If something went wrong
         if (isset($benchmark)) {
             // This benchmark is worthless
             Profiler::delete($benchmark);
         }
         // Get the errors
         $error = sqlsrv_errors(SQLSRV_ERR_ERRORS);
         // Throw an exception
         throw new Database_Sqlsrv_Exception(':error [ :query ]', array(':error' => $error[0]['message'], ':query' => $sql), $error[0]['code']);
     }
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     // Set the last query
     $this->last_query = $sql;
     if ($type === Database::SELECT) {
         // Return an iterator of results
         return new Database_Sqlsrv_Result($result, $sql, $as_object);
     } elseif ($type === Database::INSERT) {
         // Get the last insert id
         if (($insert_id = sqlsrv_fetch_array($result)) === FALSE) {
             // Get the errors
             $error = sqlsrv_errors(SQLSRV_ERR_ERRORS);
             // Throw an exception
             throw new Database_Sqlsrv_Exception(':error [ :query ]', array(':error' => 'Unable to get the last inserted row ID from driver', ':query' => $sql), $error[0]['code']);
         }
         return array($insert_id['lastInsertId'], sqlsrv_rows_affected($result));
     } else {
         // Return the number of rows affected
         return sqlsrv_rows_affected($result);
     }
 }
Exemplo n.º 15
0
 public function query($type, $sql, $as_object)
 {
     switch ($type) {
         default:
         case NULL:
         case Database::INSERT:
         case Database::UPDATE:
         case Database::DELETE:
             // Make sure we are connecting to a master database
             $this->_connection and $this->_connection === $this->_db_master or $this->connect(TRUE);
             break;
         case Database::SELECT:
             // Make sure we are connecting to a slave
             $this->_connection and $this->_connection === $this->_db_slave or $this->connect(FALSE);
             break;
     }
     if (!empty($this->_config['profiling'])) {
         // Benchmark this query for the current instance
         $benchmark = Profiler::start("Database ({$this->_instance})", $sql);
     }
     if (!empty($this->_config['connection']['persistent']) and $this->_config['connection']['database'] !== Database_MySQL::$_current_databases[$this->_connection_id]) {
         // Select database on persistent connections
         $this->_select_db($this->_config['connection']['database']);
     }
     // Execute the query
     if (($result = mysql_query($sql, $this->_connection)) === FALSE) {
         if (isset($benchmark)) {
             // This benchmark is worthless
             Profiler::delete($benchmark);
         }
         throw new Database_Exception(':error [ :query ]', array(':error' => mysql_error($this->_connection), ':query' => $sql), mysql_errno($this->_connection));
     }
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     // Set the last query
     $this->last_query = $sql;
     if ($type === Database::SELECT) {
         // Return an iterator of results
         return new Database_MySQL_Result($result, $sql, $as_object);
     } elseif ($type === Database::INSERT) {
         // Return a list of insert id and rows created
         return array(mysql_insert_id($this->_connection), mysql_affected_rows($this->_connection));
     } else {
         // Return the number of rows affected
         return mysql_affected_rows($this->_connection);
     }
 }
Exemplo n.º 16
0
 public function query($type, $sql, $as_object = FALSE, array $params = NULL)
 {
     $this->_connection or $this->connect();
     if (JsonApiApplication::$profiling) {
         $benchmark = Profiler::start("Database ({$this->_instance})", $sql);
     }
     if (!empty($this->_config['connection']['persistent']) and $this->_config['connection']['database'] !== Database_MySQL::$_current_databases[$this->_connection_id]) {
         $this->_select_db($this->_config['connection']['database']);
     }
     if (($result = mysql_query($sql, $this->_connection)) === FALSE) {
         if (isset($benchmark)) {
             Profiler::delete($benchmark);
         }
         throw new Database_Exception(':error [ :query ]', array(':error' => mysql_error($this->_connection), ':query' => $sql), mysql_errno($this->_connection));
     }
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     $this->last_query = $sql;
     if ($type === Database::SELECT) {
         return new Database_MySQL_Result($result, $sql, $as_object, $params);
     } elseif ($type === Database::INSERT) {
         return array(mysql_insert_id($this->_connection), mysql_affected_rows($this->_connection));
     } else {
         return mysql_affected_rows($this->_connection);
     }
 }
Exemplo n.º 17
0
 public function query($type, $sql, $as_object)
 {
     // Make sure the database is connected
     $this->_connection or $this->connect();
     if (!empty($this->_config['profiling'])) {
         // Benchmark this query for the current instance
         $benchmark = Profiler::start("Database ({$this->_instance})", $sql);
     }
     // Execute the query
     if (($result = mysql_query($sql, $this->_connection)) === FALSE) {
         if (isset($benchmark)) {
             // This benchmark is worthless
             Profiler::delete($benchmark);
         }
         throw new Database_Exception(':error [ :query ]', array(':error' => mysql_error($this->_connection), ':query' => $sql), mysql_errno($this->_connection));
     }
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     // Set the last query
     $this->last_query = $sql;
     if ($type === Database::SELECT) {
         // Return an iterator of results
         return new Database_MySQL_Result($result, $sql, $as_object);
     } elseif ($type === Database::INSERT) {
         // Return a list of insert id and rows created
         return array(mysql_insert_id($this->_connection), mysql_affected_rows($this->_connection));
     } else {
         // Return the number of rows affected
         return mysql_affected_rows($this->_connection);
     }
 }
Exemplo n.º 18
0
 public function query($type, $sql, $as_object = FALSE, array $params = NULL)
 {
     // Make sure the database is connected
     $this->_connection or $this->connect();
     if (Kohana::$profiling) {
         // Benchmark this query for the current instance
         $benchmark = Profiler::start("Database ({$this->_instance})", $sql);
     }
     // Execute the query
     if (($result = $this->_connection->query($sql)) === FALSE) {
         if (isset($benchmark)) {
             // This benchmark is worthless
             Profiler::delete($benchmark);
         }
         throw new Database_Exception(':error [ :query ]', array(':error' => $this->_connection->error, ':query' => $sql), $this->_connection->errno);
     }
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     // Set the last query
     $this->last_query = $sql;
     if ($type === Database::SELECT) {
         // Return an iterator of results
         return new Database_MySQLi_Result($result, $sql, $as_object, $params);
     } elseif ($type === Database::INSERT) {
         // Return a list of insert id and rows created
         return array($this->_connection->insert_id, $this->_connection->affected_rows);
     } else {
         // Return the number of rows affected
         return $this->_connection->affected_rows;
     }
 }
Exemplo n.º 19
0
 /**
  * Processes the request, executing the controller action that handles this
  * request, determined by the [Route].
  *
  * 1. Before the controller action is called, the [Controller::before] method
  * will be called.
  * 2. Next the controller action will be called.
  * 3. After the controller action is called, the [Controller::after] method
  * will be called.
  *
  * By default, the output from the controller is captured and returned, and
  * no headers are sent.
  *
  *     $request->execute();
  *
  * KoJo Modification:
  *		extension name is prefixed to the prefix instead of directory suffixed to the prefix. 
  *		extension name format will be changed to ComAppname, ModAppname, or PlgAppname 
  *
  * @return  $this
  * @throws  Kohana_Exception
  * @uses    [Kohana::$profiling]
  * @uses    [Profiler]
  */
 public function execute()
 {
     // Create the class prefix
     $prefix = 'controller_';
     if ($this->extension) {
         // extension format name should be com_app or mod_app or plg_app
         $extension = substr($this->extension, 0, 3) . substr($this->extension, 4);
         // Add the extension name to the class prefix. Add _admin_ depending on the client being called
         $this->extension_prefix = $this->client == 'admin' ? $extension . '_admin_' : $extension . '_';
         // Set the extension prefix for the controller
         $prefix = $this->extension_prefix . $prefix;
     }
     if (Kohana::$profiling) {
         // Set the benchmark name
         $benchmark = '"' . $this->uri . '"';
         if ($this !== Request::$instance and Request::$current) {
             // Add the parent request uri
             $benchmark .= ' « "' . Request::$current->uri . '"';
         }
         // Start benchmarking
         $benchmark = Profiler::start('Requests', $benchmark);
     }
     // Store the currently active request
     $previous = Request::$current;
     // Change the current request to this request
     Request::$current = $this;
     try {
         // Load the controller using reflection
         $class = new ReflectionClass($prefix . $this->controller);
         // Add the classes path in the CFS
         $path = KoJo::get_path_from_class($prefix . $this->controller);
         // Assign the path to this Request
         $this->path = $path['path'];
         // Add the path to the CFS under existing paths of parent Requests
         KoJo::add_path($this->path);
         if ($class->isAbstract()) {
             throw new Kohana_Exception('Cannot create instances of abstract :controller', array(':controller' => $prefix . $this->controller));
         }
         // Create a new instance of the controller
         $controller = $class->newInstance($this);
         // Execute the "before action" method
         $class->getMethod('before')->invoke($controller);
         // Determine the action to use
         $action = empty($this->action) ? Route::$default_action : $this->action;
         // Execute the main action with the parameters
         $class->getMethod('action_' . $action)->invokeArgs($controller, $this->_params);
         // Execute the "after action" method
         $class->getMethod('after')->invoke($controller);
     } catch (Exception $e) {
         // Restore the previous request
         Request::$current = $previous;
         if (isset($benchmark)) {
             // Delete the benchmark, it is invalid
             Profiler::delete($benchmark);
         }
         if ($e instanceof ReflectionException) {
             // Reflection will throw exceptions for missing classes or actions
             $this->status = 404;
         } else {
             // All other exceptions are PHP/server errors
             $this->status = 500;
         }
         // Re-throw the exception
         throw $e;
     }
     // Restore the previous request
     Request::$current = $previous;
     if (isset($benchmark)) {
         // Stop the benchmark
         Profiler::stop($benchmark);
     }
     return $this;
 }
Exemplo n.º 20
0
 public function query($type, $sql, $as_object = FALSE, array $params = NULL)
 {
     $this->_connection or $this->connect();
     if (Kohana::$profiling) {
         // Benchmark this query for the current instance
         $benchmark = Profiler::start("Database ({$this->_instance})", $sql);
     }
     try {
         if ($type === Database::INSERT and $this->_config['primary_key']) {
             $sql .= ' RETURNING ' . $this->quote_identifier($this->_config['primary_key']);
         }
         try {
             $result = pg_query($this->_connection, $sql);
         } catch (Exception $e) {
             throw new Database_Exception(':error [ :query ]', array(':error' => pg_last_error($this->_connection), ':query' => $sql));
         }
         if (!$result) {
             throw new Database_Exception(':error [ :query ]', array(':error' => pg_last_error($this->_connection), ':query' => $sql));
         }
         // Check the result for errors
         switch (pg_result_status($result)) {
             case PGSQL_COMMAND_OK:
                 $rows = pg_affected_rows($result);
                 break;
             case PGSQL_TUPLES_OK:
                 $rows = pg_num_rows($result);
                 break;
             case PGSQL_BAD_RESPONSE:
             case PGSQL_NONFATAL_ERROR:
             case PGSQL_FATAL_ERROR:
                 throw new Database_Exception(':error [ :query ]', array(':error' => pg_result_error($result), ':query' => $sql));
             case PGSQL_COPY_OUT:
             case PGSQL_COPY_IN:
                 pg_end_copy($this->_connection);
                 throw new Database_Exception('PostgreSQL COPY operations not supported [ :query ]', array(':query' => $sql));
             default:
                 $rows = 0;
         }
         if (isset($benchmark)) {
             Profiler::stop($benchmark);
         }
         $this->last_query = $sql;
         if ($type === Database::SELECT) {
             return new Database_PostgreSQL_Result($result, $sql, $as_object, $params, $rows);
         }
         if ($type === Database::INSERT) {
             if ($this->_config['primary_key']) {
                 // Fetch the first column of the last row
                 $insert_id = pg_fetch_result($result, $rows - 1, 0);
             } elseif ($insert_id = pg_send_query($this->_connection, 'SELECT LASTVAL()')) {
                 if ($result = pg_get_result($this->_connection) and pg_result_status($result) === PGSQL_TUPLES_OK) {
                     $insert_id = pg_fetch_result($result, 0);
                 }
             }
             return array($insert_id, $rows);
         }
         return $rows;
     } catch (Exception $e) {
         if (isset($benchmark)) {
             Profiler::delete($benchmark);
         }
         throw $e;
     }
 }
Exemplo n.º 21
0
 /**
  * Processes the request, executing the controller action that handles this
  * request, determined by the [Route].
  *
  * 1. Before the controller action is called, the [Controller::before] method
  * will be called.
  * 2. Next the controller action will be called.
  * 3. After the controller action is called, the [Controller::after] method
  * will be called.
  *
  * By default, the output from the controller is captured and returned, and
  * no headers are sent.
  *
  *     $request->execute();
  *
  * @param   Request $request
  * @return  Response
  * @throws  Kohana_Exception
  * @uses    [Kohana::$profiling]
  * @uses    [Profiler]
  * @deprecated passing $params to controller methods deprecated since version 3.1
  *             will be removed in 3.2
  */
 public function execute(Request $request)
 {
     // Check for cache existance
     if ($this->_cache instanceof Cache and ($response = $this->cache_response($request)) instanceof Response) {
         return $response;
     }
     // Create the class prefix
     $prefix = 'controller_';
     // Directory
     $directory = $request->directory();
     // Controller
     $controller = $request->controller();
     // Determine the action to use
     $action = $request->action();
     if ($directory) {
         // Add the directory name to the class prefix
         $prefix .= str_replace(array('\\', '/'), '_', trim($directory, '/')) . '_';
     }
     if (Kohana::$profiling) {
         // Set the benchmark name
         $benchmark = '"' . $request->uri() . '"';
         if ($request !== Request::$initial and Request::$current) {
             // Add the parent request uri
             $benchmark .= ' « "' . Request::$current->uri() . '"';
         }
         // Start benchmarking
         $benchmark = Profiler::start('Requests', $benchmark);
     }
     // Store the currently active request
     $previous = Request::$current;
     // Change the current request to this request
     Request::$current = $request;
     // Is this the initial request
     $initial_request = $request === Request::$initial;
     try {
         // Initiate response time
         $this->_response_time = time();
         $response = $request->create_response();
         try {
             $class = false;
             try {
                 // Load the controller using reflection
                 $class = new ReflectionClass($prefix . $controller);
             } catch (Exception $e) {
                 $request->response()->body($this->_invoke_model($request, isset($_REQUEST['params']) ? $_REQUEST['params'] : array()));
                 return $request->response();
             }
             //new
             if ($class->isAbstract()) {
                 throw new Kohana_Exception('Cannot create instances of abstract :controller', array(':controller' => $prefix . $controller));
             }
             // Create a new instance of the controller
             $controller = $class->newInstance($request, $response);
             $class->getMethod('before')->invoke($controller);
             $params = $request->param();
             // If the action doesn't exist, it's a 404
             if ($class->hasMethod('action_' . $action)) {
                 $method = $class->getMethod('action_' . $action);
                 /**
                  * Execute the main action with the parameters
                  *
                  * @deprecated $params passing is deprecated since version 3.1
                  *             will be removed in 3.2.
                  */
                 $method->invokeArgs($controller, $params);
             } elseif ($class->hasMethod('__call')) {
                 $class->getMethod('__call')->invokeArgs($controller, array($action, $params));
             } else {
                 $request->response()->body($this->_invoke_model($request, isset($_REQUEST['params']) ? $_REQUEST['params'] : array()));
                 //throw new HTTP_Exception_404('The requested URL :uri was not found on this server.',
                 //	array(':uri' => $request->param('uri')));
             }
             // Execute the "after action" method
             $class->getMethod('after')->invoke($controller);
         } catch (Exception $e) {
             // Restore the previous request
             Request::$current = $previous;
             if (isset($benchmark)) {
                 // Delete the benchmark, it is invalid
                 Profiler::delete($benchmark);
             }
             if ($e instanceof ReflectionException) {
                 // Reflection will throw exceptions for missing classes or actions
                 $this->status = 404;
             } else {
                 // All other exceptions are PHP/server errors
                 $this->status = 500;
             }
             // Re-throw the exception
             throw $e;
         }
         // Stop response time
         $this->_response_time = time() - $this->_response_time;
         // Add the default Content-Type header to initial request if not present
         if ($initial_request and !$request->headers('content-type')) {
             $request->headers('content-type', Kohana::$content_type . '; charset=' . Kohana::$charset);
         }
     } catch (Exception $e) {
         // Restore the previous request
         Request::$current = $previous;
         if (isset($benchmark)) {
             // Delete the benchmark, it is invalid
             Profiler::delete($benchmark);
         }
         // Re-throw the exception
         throw $e;
     }
     // Restore the previous request
     Request::$current = $previous;
     if (isset($benchmark)) {
         // Stop the benchmark
         Profiler::stop($benchmark);
     }
     // Cache the response if cache is available
     if ($this->_cache instanceof Cache) {
         $this->cache_response($request, $request->response());
     }
     // Return the response
     return $request->response();
 }
Exemplo n.º 22
0
 public function query($type, $sql, $as_object)
 {
     // Make sure the database is connected
     $this->_connection or $this->connect();
     if (!empty($this->_config['profiling'])) {
         // Benchmark this query for the current instance
         $benchmark = Profiler::start("Database ({$this->_instance})", $sql);
     }
     try {
         $result = $this->_connection->query($sql);
     } catch (\Exception $e) {
         if (isset($benchmark)) {
             // This benchmark is worthless
             Profiler::delete($benchmark);
         }
         if ($type !== \DB::SELECT && $this->_trans_enabled) {
             // If we are using transactions, throwing an exception would defeat the purpose
             // We need to log the failures for transaction status
             if (!is_array($this->trans_errors)) {
                 $this->trans_errors = array();
             }
             $this->trans_errors[] = $e->getMessage() . ' with query: "' . $sql . '"';
             return false;
         } else {
             // Convert the exception in a database exception
             throw new \Database_Exception($e->getMessage() . ' with query: "' . $sql . '"');
         }
     }
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     // Set the last query
     $this->last_query = $sql;
     if ($type === \DB::SELECT) {
         // Convert the result into an array, as PDOStatement::rowCount is not reliable
         if ($as_object === FALSE) {
             $result->setFetchMode(\PDO::FETCH_ASSOC);
         } elseif (is_string($as_object)) {
             $result->setFetchMode(\PDO::FETCH_CLASS, $as_object);
         } else {
             $result->setFetchMode(\PDO::FETCH_CLASS, 'stdClass');
         }
         $result = $result->fetchAll();
         // Return an iterator of results
         return new \Database_Result_Cached($result, $sql, $as_object);
     } elseif ($type === \DB::INSERT) {
         // Return a list of insert id and rows created
         return array($this->_connection->lastInsertId(), $result->rowCount());
     } else {
         // Return the number of rows affected
         return $result->rowCount();
     }
 }
Exemplo n.º 23
0
 public function query($type, $sql, $as_object)
 {
     // Make sure the database is connected
     $this->_connection or $this->connect();
     if (!empty($this->_config['profiling'])) {
         // Benchmark this query for the current instance
         $benchmark = \Profiler::start("Database ({$this->_instance})", $sql);
     }
     // run the query. if the connection is lost, try 3 times to reconnect
     $attempts = 3;
     do {
         try {
             $result = $this->_connection->query($sql);
             break;
         } catch (\Exception $e) {
             if (strpos($e->getMessage(), '2006 MySQL') !== false) {
                 $this->connect();
             } else {
                 if (isset($benchmark)) {
                     // This benchmark is worthless
                     \Profiler::delete($benchmark);
                 }
                 // Convert the exception in a database exception
                 $error_code = is_numeric($e->getCode()) ? $e->getCode() : 0;
                 throw new \Database_Exception($e->getMessage() . ' with query: "' . $sql . '"', $error_code, $e);
             }
         }
     } while ($attempts-- > 0);
     if (isset($benchmark)) {
         \Profiler::stop($benchmark);
     }
     // Set the last query
     $this->last_query = $sql;
     if ($type === \DB::SELECT) {
         // Convert the result into an array, as PDOStatement::rowCount is not reliable
         if ($as_object === false) {
             $result = $result->fetchAll(\PDO::FETCH_ASSOC);
         } elseif (is_string($as_object)) {
             $result = $result->fetchAll(\PDO::FETCH_CLASS, $as_object);
         } else {
             $result = $result->fetchAll(\PDO::FETCH_CLASS, 'stdClass');
         }
         // Return an iterator of results
         return new \Database_Result_Cached($result, $sql, $as_object);
     } elseif ($type === \DB::INSERT) {
         // Return a list of insert id and rows created
         return array($this->_connection->lastInsertId(), $result->rowCount());
     } else {
         // Return the number of rows affected
         return $result->errorCode() === '00000' ? $result->rowCount() : -1;
     }
 }
Exemplo n.º 24
0
 public function query($type, $sql, $as_object = FALSE, array $params = NULL)
 {
     // Make sure the database is connected
     $this->_connection or $this->connect();
     // Mssql specific
     if (preg_match("/OFFSET ([0-9]+)/i", $sql, $matches)) {
         list($replace, $offset) = $matches;
         $sql = str_replace($replace, '', $sql);
     }
     if (preg_match("/LIMIT ([0-9]+)/i", $sql, $matches)) {
         list($replace, $limit) = $matches;
         $sql = str_replace($replace, '', $sql);
     }
     if (isset($limit) || isset($offset)) {
         if (!isset($offset)) {
             $sql = preg_replace("/^(SELECT|DELETE|UPDATE)\\s/i", "\$1 TOP " . $limit . ' ', $sql);
         } else {
             $ob_count = (int) preg_match_all('/ORDER BY/i', $sql, $ob_matches, PREG_OFFSET_CAPTURE);
             if ($ob_count < 1) {
                 $over = 'ORDER BY (SELECT 0)';
             } else {
                 $ob_last = array_pop($ob_matches[0]);
                 $orderby = strrchr($sql, $ob_last[0]);
                 $over = preg_replace('/[^,\\s]*\\.([^,\\s]*)/i', 'inner_tbl.$1', $orderby);
                 // Remove ORDER BY clause from $sql
                 $sql = substr($sql, 0, $ob_last[1]);
             }
             // Add ORDER BY clause as an argument for ROW_NUMBER()
             $sql = "SELECT ROW_NUMBER() OVER ({$over}) AS KOHANA_DB_ROWNUM, * FROM ({$sql}) AS inner_tbl";
             $start = $offset + 1;
             $end = $offset + $limit;
             $sql = "WITH outer_tbl AS ({$sql}) SELECT * FROM outer_tbl WHERE KOHANA_DB_ROWNUM BETWEEN {$start} AND {$end}";
         }
     }
     if (!empty($this->_config['profiling'])) {
         // Benchmark this query for the current instance
         $benchmark = Profiler::start("Database ({$this->_instance})", $sql);
     }
     try {
         $result = $this->_connection->query($sql);
     } catch (Exception $e) {
         if (isset($benchmark)) {
             // This benchmark is worthless
             Profiler::delete($benchmark);
         }
         $errArr = $this->_connection->errorInfo();
         $resultTextError = $this->_connection->query("select * from sys.messages where  language_id=1033 and message_id=" . arr::get($errArr, 1, 0))->fetchAll();
         // Convert the exception in a database exception
         throw new Database_Exception('[:code] :error ( :info )', array(':code' => $e->getCode(), ':error' => $e->getMessage(), ':info' => arr::get($resultTextError[0], 'text')), $e->getCode());
     }
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     // Set the last query
     $this->last_query = $sql;
     if ($type === Database::SELECT) {
         // Convert the result into an array, as PDOStatement::rowCount is not reliable
         if ($as_object === FALSE) {
             $result->setFetchMode(PDO::FETCH_ASSOC);
         } elseif (is_string($as_object)) {
             $result->setFetchMode(PDO::FETCH_CLASS, $as_object, $params);
         } else {
             $result->setFetchMode(PDO::FETCH_CLASS, 'stdClass');
         }
         $result = $result->fetchAll();
         // Return an iterator of results
         return new Database_Result_Cached($result, $sql, $as_object, $params);
     } elseif ($type === Database::INSERT) {
         // Return a list of insert id and rows created
         return array($this->insert_id(), $result->rowCount());
     } else {
         // Return the number of rows affected
         return $result->rowCount();
     }
 }
Exemplo n.º 25
0
 /**
  * Processes the request, executing the controller action that handles this
  * request, determined by the [Route].
  *
  * 1. Before the controller action is called, the [Controller::before] method
  * will be called.
  * 2. Next the controller action will be called.
  * 3. After the controller action is called, the [Controller::after] method
  * will be called.
  *
  * By default, the output from the controller is captured and returned, and
  * no headers are sent.
  *
  *     $request->execute();
  *
  * @param   Request $request
  * @return  Response
  * @throws  Kohana_Exception
  * @uses    [Kohana::$profiling]
  * @uses    [Profiler]
  * @deprecated passing $params to controller methods deprecated since version 3.1
  *             will be removed in 3.2
  */
 public function execute_request(Request $request)
 {
     // Create the class prefix
     $prefix = 'controller_';
     // Directory
     $directory = $request->directory();
     // Controller
     $controller = $request->controller();
     if ($directory) {
         // Add the directory name to the class prefix
         $prefix .= str_replace(array('\\', '/'), '_', trim($directory, '/')) . '_';
     }
     if (Kohana::$profiling) {
         // Set the benchmark name
         $benchmark = '"' . $request->uri() . '"';
         if ($request !== Request::$initial and Request::$current) {
             // Add the parent request uri
             $benchmark .= ' « "' . Request::$current->uri() . '"';
         }
         // Start benchmarking
         $benchmark = Profiler::start('Requests', $benchmark);
     }
     // Store the currently active request
     $previous = Request::$current;
     // Change the current request to this request
     Request::$current = $request;
     // Is this the initial request
     $initial_request = $request === Request::$initial;
     try {
         if (!class_exists($prefix . $controller)) {
             throw new HTTP_Exception_404('The requested URL :uri was not found on this server.', array(':uri' => $request->uri()));
         }
         // Load the controller using reflection
         $class = new ReflectionClass($prefix . $controller);
         if ($class->isAbstract()) {
             throw new Kohana_Exception('Cannot create instances of abstract :controller', array(':controller' => $prefix . $controller));
         }
         // Create a new instance of the controller
         $controller = $class->newInstance($request, $request->response() ? $request->response() : $request->create_response());
         $class->getMethod('before')->invoke($controller);
         // Determine the action to use
         $action = $request->action();
         $params = $request->param();
         // If the action doesn't exist, it's a 404
         if (!$class->hasMethod('action_' . $action)) {
             throw new HTTP_Exception_404('The requested URL :uri was not found on this server.', array(':uri' => $request->uri()));
         }
         $method = $class->getMethod('action_' . $action);
         $method->invoke($controller);
         // Execute the "after action" method
         $class->getMethod('after')->invoke($controller);
     } catch (Exception $e) {
         // Restore the previous request
         if ($previous instanceof Request) {
             Request::$current = $previous;
         }
         if (isset($benchmark)) {
             // Delete the benchmark, it is invalid
             Profiler::delete($benchmark);
         }
         // Re-throw the exception
         throw $e;
     }
     // Restore the previous request
     Request::$current = $previous;
     if (isset($benchmark)) {
         // Stop the benchmark
         Profiler::stop($benchmark);
     }
     // Return the response
     return $request->response();
 }
Exemplo n.º 26
0
 /**
  * Processes the request, executing the controller action that handles this
  * request, determined by the [Route].
  *
  * 1. Before the controller action is called, the [Controller::before] method
  * will be called.
  * 2. Next the controller action will be called.
  * 3. After the controller action is called, the [Controller::after] method
  * will be called.
  *
  * By default, the output from the controller is captured and returned, and
  * no headers are sent.
  *
  *     $request->execute();
  *
  * @param   Request $request A request object
  * @return  Response
  * @throws  Kohana_Exception
  * @uses    [Kohana::$profiling]
  * @uses    [Profiler]
  */
 public function execute(Request $request)
 {
     // Check for cache existance
     if ($this->_cache instanceof Cache and ($response = $this->cache_response($request)) instanceof Response) {
         return $response;
     }
     if (Kohana::$profiling) {
         // Set the benchmark name
         $benchmark = '"' . $request->uri() . '"';
         if ($request !== Request::$initial and Request::$current) {
             // Add the parent request uri
             $benchmark .= ' « "' . Request::$current->uri() . '"';
         }
         // Start benchmarking
         $benchmark = Profiler::start('Requests', $benchmark);
     }
     // Store the current active request and replace current with new request
     $previous = Request::$current;
     Request::$current = $request;
     try {
         // If PECL_HTTP is present, use extension to complete request
         if (extension_loaded('http')) {
             $this->_http_execute($request);
         } elseif (extension_loaded('curl')) {
             $this->_curl_execute($request);
         } else {
             $this->_native_execute($request);
         }
     } catch (Exception $e) {
         // Restore the previous request
         Request::$current = $previous;
         if (isset($benchmark)) {
             // Delete the benchmark, it is invalid
             Profiler::delete($benchmark);
         }
         // Re-throw the exception
         throw $e;
     }
     // Restore the previous request
     Request::$current = $previous;
     if (isset($benchmark)) {
         // Stop the benchmark
         Profiler::stop($benchmark);
     }
     // Cache the response if cache is available
     if ($this->_cache instanceof Cache) {
         $this->cache_response($request, $request->response());
     }
     // Return the response
     return $request->response();
 }
Exemplo n.º 27
0
 public function query($type, $sql, $as_object)
 {
     // Make sure the database is connected
     if ($this->_connection) {
         // Make sure the connection is still alive
         if (!$this->_connection->ping()) {
             throw new \Database_Exception($this->_connection->error . ' [ ' . $sql . ' ]', $this->_connection->errno);
         }
     } else {
         $this->connect();
     }
     if (!empty($this->_config['profiling'])) {
         // Benchmark this query for the current instance
         $benchmark = \Profiler::start("Database ({$this->_instance})", $sql);
     }
     if (!empty($this->_config['connection']['persistent']) and $this->_config['connection']['database'] !== static::$_current_databases[$this->_connection_id]) {
         // Select database on persistent connections
         $this->_select_db($this->_config['connection']['database']);
     }
     // Execute the query
     if (($result = $this->_connection->query($sql)) === false) {
         if (isset($benchmark)) {
             // This benchmark is worthless
             \Profiler::delete($benchmark);
         }
         throw new \Database_Exception($this->_connection->error . ' [ ' . $sql . ' ]', $this->_connection->errno);
     }
     // check for multiresults, we don't support those at the moment
     while ($this->_connection->more_results() and $this->_connection->next_result()) {
         if ($more_result = $this->_connection->use_result()) {
             throw new \Database_Exception('The MySQLi driver does not support multiple resultsets', 0);
         }
     }
     if (isset($benchmark)) {
         \Profiler::stop($benchmark);
     }
     // Set the last query
     $this->last_query = $sql;
     if ($type === \DB::SELECT) {
         // Return an iterator of results
         return new \Database_MySQLi_Result($result, $sql, $as_object);
     } elseif ($type === \DB::INSERT) {
         // Return a list of insert id and rows created
         return array($this->_connection->insert_id, $this->_connection->affected_rows);
     } else {
         // Return the number of rows affected
         return $this->_connection->affected_rows;
     }
 }
Exemplo n.º 28
0
 /**
  * Processes the request, executing the controller action that handles this
  * request, determined by the [Route].
  *
  * 1. Before the controller action is called, the [Controller::before] method
  * will be called.
  * 2. Next the controller action will be called.
  * 3. After the controller action is called, the [Controller::after] method
  * will be called.
  *
  * By default, the output from the controller is captured and returned, and
  * no headers are sent.
  *
  *     $request->execute();
  *
  * @return  $this
  * @throws  Kohana_Exception
  * @uses    [Kohana::$profiling]
  * @uses    [Profiler]
  */
 public function execute()
 {
     // Create the class prefix
     $prefix = 'controller_';
     if ($this->directory) {
         // Add the directory name to the class prefix
         $prefix .= str_replace(array('\\', '/'), '_', trim($this->directory, '/')) . '_';
     }
     if (Kohana::$profiling) {
         // Set the benchmark name
         $benchmark = '"' . $this->uri . '"';
         if ($this !== Request::$instance) {
             // Add the parent request uri
             $benchmark .= ' « "' . Request::$current->uri . '"';
         }
         // Start benchmarking
         $benchmark = Profiler::start('Requests', $benchmark);
     }
     // Store the currently active request
     $previous = Request::$current;
     // Change the current request to this request
     Request::$current = $this;
     try {
         // Load the controller using reflection
         $class = new ReflectionClass($prefix . $this->controller);
         if ($class->isAbstract()) {
             throw new Kohana_Exception('Cannot create instances of abstract :controller', array(':controller' => $prefix . $this->controller));
         }
         // Create a new instance of the controller
         $controller = $class->newInstance($this);
         // Execute the "before action" method
         $class->getMethod('before')->invoke($controller);
         // Determine the action to use
         $action = empty($this->action) ? Route::$default_action : $this->action;
         // Execute the main action with the parameters
         $class->getMethod('action_' . $action)->invokeArgs($controller, $this->_params);
         // Execute the "after action" method
         $class->getMethod('after')->invoke($controller);
     } catch (Exception $e) {
         // Restore the previous request
         Request::$current = $previous;
         if (isset($benchmark)) {
             // Delete the benchmark, it is invalid
             Profiler::delete($benchmark);
         }
         if ($e instanceof ReflectionException) {
             // Reflection will throw exceptions for missing classes or actions
             $this->status = 404;
         } else {
             // All other exceptions are PHP/server errors
             $this->status = 500;
         }
         // Re-throw the exception
         throw $e;
     }
     // Restore the previous request
     Request::$current = $previous;
     if (isset($benchmark)) {
         // Stop the benchmark
         Profiler::stop($benchmark);
     }
     return $this;
 }
Exemplo n.º 29
0
 public function query($type, $sql, $as_object)
 {
     // Make sure the database is connected
     if ($this->_connection) {
         if (!mysql_ping($this->_connection)) {
             throw new \Database_Exception(mysql_error($this->_connection) . ' [ ' . $sql . ' ]', mysql_errno($this->_connection));
         }
     } else {
         $this->connect();
     }
     if (!empty($this->_config['profiling'])) {
         // Get the paths defined in config
         $paths = \Config::get('profiling_paths');
         // Storage for the trace information
         $stacktrace = array();
         // Get the execution trace of this query
         $include = false;
         foreach (debug_backtrace() as $index => $page) {
             // Skip first entry and entries without a filename
             if ($index > 0 and empty($page['file']) === false) {
                 // Checks to see what paths you want backtrace
                 foreach ($paths as $index => $path) {
                     if (strpos($page['file'], $path) !== false) {
                         $include = true;
                         break;
                     }
                 }
                 // Only log if no paths we defined, or we have a path match
                 if ($include or empty($paths)) {
                     $stacktrace[] = array('file' => \Fuel::clean_path($page['file']), 'line' => $page['line']);
                 }
             }
         }
         $benchmark = \Profiler::start($this->_instance, $sql, $stacktrace);
     }
     if (!empty($this->_config['connection']['persistent']) and $this->_config['connection']['database'] !== static::$_current_databases[$this->_connection_id]) {
         // Select database on persistent connections
         $this->_select_db($this->_config['connection']['database']);
     }
     // Execute the query
     if (($result = mysql_query($sql, $this->_connection)) === false) {
         if (isset($benchmark)) {
             // This benchmark is worthless
             \Profiler::delete($benchmark);
         }
         throw new \Database_Exception(mysql_error($this->_connection) . ' [ ' . $sql . ' ]', mysql_errno($this->_connection));
     }
     if (isset($benchmark)) {
         \Profiler::stop($benchmark);
     }
     // Set the last query
     $this->last_query = $sql;
     if ($type === \DB::SELECT) {
         // Return an iterator of results
         return new \Database_MySQL_Result($result, $sql, $as_object);
     } elseif ($type === \DB::INSERT) {
         // Return a list of insert id and rows created
         return array(mysql_insert_id($this->_connection), mysql_affected_rows($this->_connection));
     } elseif ($type === \DB::UPDATE or $type === \DB::DELETE) {
         // Return the number of rows affected
         return mysql_affected_rows($this->_connection);
     }
     return $result;
 }
Exemplo n.º 30
0
 /**
  * Processes the request, executing the controller action that handles this
  * request, determined by the [Route].
  *
  * 1. Before the controller action is called, the [Controller::before] method
  * will be called.
  * 2. Next the controller action will be called.
  * 3. After the controller action is called, the [Controller::after] method
  * will be called.
  *
  * By default, the output from the controller is captured and returned, and
  * no headers are sent.
  *
  *     $request->execute();
  *
  * @param   Request   $request   A request object
  * @param   Response  $response  A response object
  * @return  Response
  * @throws  Kohana_Exception
  * @uses    [Kohana::$profiling]
  * @uses    [Profiler]
  */
 public function execute_request(Request $request, Response $response)
 {
     if (Kohana::$profiling) {
         // Set the benchmark name
         $benchmark = '"' . $request->uri() . '"';
         if ($request !== Request::$initial and Request::$current) {
             // Add the parent request uri
             $benchmark .= ' « "' . Request::$current->uri() . '"';
         }
         // Start benchmarking
         $benchmark = Profiler::start('Requests', $benchmark);
     }
     // Store the current active request and replace current with new request
     $previous = Request::$current;
     Request::$current = $request;
     // Resolve the POST fields
     if ($post = $request->post()) {
         $request->body(http_build_query($post, NULL, '&'))->headers('content-type', 'application/x-www-form-urlencoded; charset=' . Kohana::$charset);
     }
     $request->headers('content-length', (string) $request->content_length());
     // If Kohana expose, set the user-agent
     if (Kohana::$expose) {
         $request->headers('user-agent', Kohana::version());
     }
     try {
         $response = $this->_send_message($request, $response);
     } catch (Exception $e) {
         // Restore the previous request
         Request::$current = $previous;
         if (isset($benchmark)) {
             // Delete the benchmark, it is invalid
             Profiler::delete($benchmark);
         }
         // Re-throw the exception
         throw $e;
     }
     // Restore the previous request
     Request::$current = $previous;
     if (isset($benchmark)) {
         // Stop the benchmark
         Profiler::stop($benchmark);
     }
     // Return the response
     return $response;
 }