Beispiel #1
0
 public function init(&$pdoStmnt, $removePagingEnable = false)
 {
     $this->_pdoStmnt =& $pdoStmnt;
     $this->_removePagingEnable = $removePagingEnable;
     $this->_colCount = $this->_pdoStmnt->columnCount();
     //$this->_rowCount = $this->_pdoStmnt->rowCount();
     $this->_rowCount = 0;
     return $this;
 }
Beispiel #2
0
 public function query($sql, $noexcept = false, $params = array())
 {
     if (!$noexcept) {
         $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
         $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
     }
     $this->statement = $this->connection->prepare($sql);
     $result = false;
     $time_start = microtime(true);
     try {
         if ($this->statement && $this->statement->execute($params)) {
             $data = array();
             if ($this->statement->columnCount()) {
                 while ($row = $this->statement->fetch(PDO::FETCH_ASSOC)) {
                     $data[] = $row;
                 }
                 $result = new stdClass();
                 $result->row = isset($data[0]) ? $data[0] : array();
                 $result->rows = $data;
                 $result->num_rows = $this->statement->rowCount();
             }
         }
     } catch (PDOException $e) {
         $this->error = 'SQL Error: ' . $e->getMessage() . '<br />Error No: ' . $e->getCode() . '<br />SQL:' . $sql;
         if ($noexcept) {
             return false;
         } else {
             throw new AException(AC_ERR_MYSQL, $this->error);
         }
     }
     $time_exec = microtime(true) - $time_start;
     // to avoid debug class init while setting was not yet loaded
     if ($this->registry->get('config')) {
         if ($this->registry->get('config')->has('config_debug')) {
             $backtrace = debug_backtrace();
             ADebug::set_query($sql, $time_exec, $backtrace[2]);
         }
     }
     if ($result) {
         return $result;
     } else {
         $result = new stdClass();
         $result->row = array();
         $result->rows = array();
         $result->num_rows = 0;
         return $result;
     }
 }
Beispiel #3
0
 /**
  * @return int
  */
 public function getLastColumnCount()
 {
     if (!$this->lastPdoStatement) {
         return null;
     }
     return $this->lastPdoStatement->columnCount();
 }
Beispiel #4
0
 public function columnCount()
 {
     if ($this->_statement instanceof \PDOStatement) {
         return $this->_statement->columnCount();
     }
     return 0;
 }
Beispiel #5
0
 /**
  * Returns the number of columns in the result set.
  * Returns null if the statement has no result set metadata.
  *
  * @return int The number of columns.
  * @throws Zend_Db_Statement_Exception
  */
 public function columnCount()
 {
     try {
         return $this->_stmt->columnCount();
     } catch (PDOException $e) {
         require_once 'Zend/Db/Statement/Exception.php';
         throw new Zend_Db_Statement_Exception($e->getMessage());
     }
 }
Beispiel #6
0
 /**
  * @param \PDOStatement $stmt
  * @return array
  */
 private function getFields(\PDOStatement $stmt)
 {
     $fields = [];
     $columnCount = $stmt->columnCount();
     for ($i = 0; $i < $columnCount; $i++) {
         $fields[$i] = $stmt->getColumnMeta($i);
     }
     return $fields;
 }
 protected function bindColumns()
 {
     if (!$this->columnsBound) {
         $this->columnsBound = true;
         $this->actRow = array();
         $this->actRowIndex = array();
         $count = $this->pdoStmt->columnCount();
         for ($i = 0; $i < $count; $i++) {
             $meta = $this->pdoStmt->getColumnMeta($i);
             if (array_key_exists('native_type', $meta) && $meta['native_type'] == 'BLOB') {
                 $this->pdoStmt->bindColumn($i + 1, $this->actRow[$meta['name']], \PDO::PARAM_LOB);
             } else {
                 $this->pdoStmt->bindColumn($i + 1, $this->actRow[$meta['name']]);
             }
             $this->actRowIndex[$i] =& $this->actRow[$meta['name']];
         }
     }
 }
Beispiel #8
0
 /**
  * returns sets result set from query
  * @param string $sql
  * @param array $bindValues
  * @return \ErrorObject|boolean
  */
 public function query($sql, array $bindValues)
 {
     $this->stmt = $this->pdoConn->prepare($sql);
     try {
         $this->stmt->execute($bindValues);
     } catch (PDOException $e) {
         $errorObject = new ErrorObject($e->getCode(), $e->getMessage(), $e->getTrace(), $_SERVER['SCRIPT_FILENAME']);
         return $errorObject;
     }
     if ($this->stmt->columnCount() > 0) {
         $this->resultSet = $this->stmt->fetchAll(PDO::FETCH_ASSOC);
     } else {
         $this->lastInserted = $this->pdoConn->lastInsertId();
         $this->numRows = $this->stmt->rowCount();
     }
     unset($this->stmt);
     unset($this->pdoConn);
     return true;
 }
Beispiel #9
0
 /**
  * Load the column metadata from the last query.
  * @return array
  */
 public function load_col_info()
 {
     if ($this->col_info) {
         return $this->col_info;
     }
     $num_fields = $this->result->columnCount();
     for ($i = 0; $i < $num_fields; $i++) {
         $this->col_info[$i] = (object) $this->result->getColumnMeta($i);
     }
     return $this->col_info;
 }
 public function getMoreResults()
 {
     $this->checkClosed();
     $this->stmt->nextRowset();
     $this->resultSet = null;
     $this->updateCount = -1;
     if ($this->stmt->columnCount() == 0) {
         $this->updateCount = $this->stmt->rowCount();
         return false;
     }
     return true;
 }
Beispiel #11
0
 /**
  * Returns metadata for all columns in a result set.
  *
  * @return array
  * @throws DibiException
  */
 public function getColumnsMeta()
 {
     $count = $this->resultSet->columnCount();
     $meta = array();
     for ($i = 0; $i < $count; $i++) {
         // items 'name' and 'table' are required
         $info = @$this->resultSet->getColumnsMeta($i);
         // intentionally @
         if ($info === FALSE) {
             throw new DibiDriverException('Driver does not support meta data.');
         }
         $meta[] = $info;
     }
     return $meta;
 }
Beispiel #12
0
 /**
  * @inheritDoc
  */
 public function fetch()
 {
     $data = $this->pdoStatement ? $this->pdoStatement->fetch() : NULL;
     if (!$data) {
         $this->pdoStatement->closeCursor();
         return FALSE;
     }
     $row = new Row();
     foreach ($this->normalizeRow($data) as $key => $value) {
         $row->{$key} = $value;
     }
     if ($this->result === NULL && count($data) !== $this->pdoStatement->columnCount()) {
         trigger_error('Found duplicate columns in database result set.', E_USER_NOTICE);
     }
     $this->resultKey++;
     return $this->result = $row;
 }
 public function __construct(PDOStatement $statement, $param_values = array(), $param_data_types = array(), $fetch_style = moojon_db::FETCH_ASSOC)
 {
     $this->iterator = $this->getIterator();
     $query_string = $statement->queryString;
     $log = $query_string;
     if (ENVIRONMENT == 'development' || ENVIRONMENT == 'cli') {
         $values = 'Param values(';
         $parsed_query = $log;
         foreach ($param_values as $key => $value) {
             $values .= "{$key} = {$value}, ";
             $apos = array_key_exists($key, $param_data_types) && $param_data_types[$key] == moojon_db::PARAM_STR ? "'" : '';
             $parsed_query = str_replace($key, "{$apos}{$value}{$apos}", $parsed_query);
         }
         $parsed_query = "Parsed query: {$parsed_query}";
         if (count($param_values)) {
             $values = substr($values, 0, -2);
         }
         $values .= ')';
         $data_types = 'Param data types(';
         foreach ($param_data_types as $key => $value) {
             $data_types .= "{$key} = {$value}, ";
         }
         if (count($data_types)) {
             $data_types = substr($data_types, 0, -2);
         }
         $data_types .= ')';
         $log .= "\n\n{$parsed_query}\n\n{$values}\n\n{$data_types}";
         moojon_base::log($log);
     }
     foreach ($param_values as $key => $value) {
         if ($value !== null) {
             $data_type = array_key_exists($key, $param_data_types) ? $param_data_types[$key] : moojon_db::PARAM_STR;
             if (strpos($query_string, $key) !== false) {
                 $statement->bindValue($key, $value, $data_type);
             }
         }
     }
     $this->affected = $statement->execute();
     $this->non_query = $statement->columnCount() > 0;
     if ($this->non_query) {
         foreach ($statement->fetchAll($fetch_style) as $record) {
             $this[] = $record;
         }
     }
 }
Beispiel #14
0
 /**
  * Builds a map of the columns contained in a result
  *
  * @param PDOStatement $results
  * @return void
  */
 public function resultSet($results)
 {
     $this->map = array();
     $numFields = $results->columnCount();
     $index = 0;
     while ($numFields-- > 0) {
         $column = $results->getColumnMeta($index);
         if (empty($column['native_type'])) {
             $type = $column['len'] == 1 ? 'boolean' : 'string';
         } else {
             $type = $column['native_type'];
         }
         if (strpos($column['name'], '__')) {
             list($column['table'], $column['name']) = explode('__', $column['name']);
         }
         if (!empty($column['table']) && strpos($column['name'], $this->virtualFieldSeparator) === false) {
             $this->map[$index++] = array($column['table'], $column['name'], $type);
         } else {
             $this->map[$index++] = array(0, $column['name'], $type);
         }
     }
 }
Beispiel #15
0
 /**
  *  execute a previously bounded $stmt
  *  
  *  @param  \PDOStatement $stmt should already have been passed through {@link bindStatement()}
  *  @return mixed boolean if the statement is something like INSERT, DELETE, or UPDATE, the result
  *                set if statement is SELECT
  */
 protected function execStatement(PDOStatement $stmt)
 {
     $ret_mixed = false;
     try {
         if ($stmt->execute()) {
             $col_count = $stmt->columnCount();
             if ($col_count === 1) {
                 $ret_mixed = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
             } else {
                 if ($col_count === 0) {
                     $ret_mixed = true;
                 } else {
                     $ret_mixed = $stmt->fetchAll(PDO::FETCH_ASSOC);
                 }
             }
             //if/else
         } else {
             // error stuff? I'm actually not sure this will ever execute
             ///$arr = $stmt->errorInfo();
             ///\out::e($arr);
             ///\out::e($stmt->errorCode());
             ///$db = $this->getDb();
             ///\out::e($db->errorInfo());
             ///\out::e($db->errorCode());
         }
         //if/else
         $stmt->closeCursor();
     } catch (Exception $e) {
         $stmt->closeCursor();
         throw $e;
     }
     //try/catch
     return $ret_mixed;
 }
Beispiel #16
0
 /**
  * Returns associative array of detected types (IReflection::FIELD_*) in result set.
  */
 public function getColumnTypes(\PDOStatement $statement)
 {
     $types = [];
     $count = $statement->columnCount();
     for ($col = 0; $col < $count; $col++) {
         $meta = $statement->getColumnMeta($col);
         if (isset($meta['native_type'])) {
             $types[$meta['name']] = $type = Nette\Database\Helpers::detectType($meta['native_type']);
             if ($type === Nette\Database\IStructure::FIELD_TIME) {
                 $types[$meta['name']] = Nette\Database\IStructure::FIELD_TIME_INTERVAL;
             }
         }
     }
     return $types;
 }
Beispiel #17
0
 /**
  * Common column type detection.
  * @return array
  */
 public static function detectTypes(\PDOStatement $statement)
 {
     $types = array();
     $count = $statement->columnCount();
     // driver must be meta-aware, see PHP bugs #53782, #54695
     for ($col = 0; $col < $count; $col++) {
         $meta = $statement->getColumnMeta($col);
         if (isset($meta['native_type'])) {
             $types[$meta['name']] = self::detectType($meta['native_type']);
         }
     }
     return $types;
 }
Beispiel #18
0
 /**
  * Exec the sql statement.
  *
  * @param $sql
  *
  * @throws BuildException
  * @throws Exception
  */
 protected function execSQL($sql)
 {
     // Check and ignore empty statements
     if (trim($sql) == "") {
         return;
     }
     try {
         $this->totalSql++;
         $this->statement = $this->conn->prepare($sql);
         $this->statement->execute();
         $this->log($this->statement->rowCount() . " rows affected", Project::MSG_VERBOSE);
         // only call processResults() for statements that return actual data (such as 'select')
         if ($this->statement->columnCount() > 0) {
             $this->processResults();
         }
         $this->statement->closeCursor();
         $this->statement = null;
         $this->goodSql++;
     } catch (PDOException $e) {
         $this->log("Failed to execute: " . $sql, Project::MSG_ERR);
         if ($this->onError != "continue") {
             throw new BuildException("Failed to execute SQL", $e);
         }
         $this->log($e->getMessage(), Project::MSG_ERR);
     }
 }
 /**
  * 返回结果集中的列数
  * 
  * @return number
  */
 public function columnCount()
 {
     return $this->_statement->columnCount();
 }
Beispiel #20
0
 /**
  * Builds a map of the columns contained in a result
  *
  * @param PDOStatement $results
  * @return void
  */
 public function resultSet($results)
 {
     $this->map = array();
     $numFields = $results->columnCount();
     $index = 0;
     while ($numFields-- > 0) {
         $column = $results->getColumnMeta($index);
         $name = $column['name'];
         if (strpos($name, '__')) {
             if (isset($this->_fieldMappings[$name]) && strpos($this->_fieldMappings[$name], '.')) {
                 $map = explode('.', $this->_fieldMappings[$name]);
             } elseif (isset($this->_fieldMappings[$name])) {
                 $map = array(0, $this->_fieldMappings[$name]);
             } else {
                 $map = array(0, $name);
             }
         } else {
             $map = array(0, $name);
         }
         $map[] = $column['sqlsrv:decl_type'] === 'bit' ? 'boolean' : $column['native_type'];
         $this->map[$index++] = $map;
     }
 }
Beispiel #21
0
 protected function FetchFields()
 {
     for ($i = 0; $i < $this->statement->columnCount(); $i++) {
         $columnMetadata = $this->statement->getColumnMeta($i);
         $this->AddField($columnMetadata['name']);
         if (isset($columnMetadata['native_type'])) {
             $this->nativeTypes[$columnMetadata['name']] = $columnMetadata['native_type'];
         }
     }
 }
Beispiel #22
0
 /**
  * Returns associative array of detected types (IReflection::FIELD_*) in result set.
  */
 public function getColumnTypes(\PDOStatement $statement)
 {
     $types = [];
     $count = $statement->columnCount();
     for ($col = 0; $col < $count; $col++) {
         $meta = $statement->getColumnMeta($col);
         if (isset($meta['sqlite:decl_type'])) {
             if ($meta['sqlite:decl_type'] === 'DATE') {
                 $types[$meta['name']] = Nette\Database\IStructure::FIELD_UNIX_TIMESTAMP;
             } else {
                 $types[$meta['name']] = Nette\Database\Helpers::detectType($meta['sqlite:decl_type']);
             }
         } elseif (isset($meta['native_type'])) {
             $types[$meta['name']] = Nette\Database\Helpers::detectType($meta['native_type']);
         }
     }
     return $types;
 }
 /**
  * Builds a map of the columns contained in a result
  *
  * @param PDOStatement $results
  * @return void
  */
 public function resultSet($results)
 {
     $this->results = $results;
     $this->map = array();
     $numFields = $results->columnCount();
     $index = 0;
     $j = 0;
     //PDO::getColumnMeta is experimental and does not work with oci,
     //	so try to figure it out based on the querystring
     $querystring = $results->queryString;
     if (strpos($querystring, 'cake_paging') !== false) {
         $querystring = preg_replace('/^SELECT \\* FROM \\((.*)\\) cake_paging.+$/s', '$1', $querystring);
         $querystring = trim($querystring);
     }
     if (stripos($querystring, 'SELECT') === 0) {
         $last = strripos($querystring, 'FROM');
         if ($last !== false) {
             $selectpart = substr($querystring, 7, $last - 8);
             $selects = String::tokenize($selectpart, ',', '(', ')');
         }
     } elseif (strpos($querystring, 'PRAGMA table_info') === 0) {
         $selects = array('cid', 'name', 'type', 'notnull', 'dflt_value', 'pk');
     } elseif (strpos($querystring, 'PRAGMA index_list') === 0) {
         $selects = array('seq', 'name', 'unique');
     } elseif (strpos($querystring, 'PRAGMA index_info') === 0) {
         $selects = array('seqno', 'cid', 'name');
     }
     while ($j < $numFields) {
         if (!isset($selects[$j])) {
             $j++;
             continue;
         }
         if (preg_match('/\\bAS\\s+(.*)/i', $selects[$j], $matches)) {
             $columnName = trim($matches[1], '"');
         } else {
             $columnName = trim(str_replace('"', '', $selects[$j]));
         }
         if (strpos($selects[$j], 'DISTINCT') === 0) {
             $columnName = str_ireplace('DISTINCT', '', $columnName);
         }
         $metaType = false;
         try {
             $metaData = (array) $results->getColumnMeta($j);
             if (!empty($metaData['oci:decl_type'])) {
                 $metaType = trim($metaData['oci:decl_type']);
             }
         } catch (Exception $e) {
         }
         if (strpos($columnName, '__')) {
             $parts = explode('__', $columnName);
             $this->map[$index++] = array(trim($parts[0]), trim($parts[1]), $metaType);
         } else {
             $this->map[$index++] = array(0, $columnName, $metaType);
         }
         $j++;
     }
 }
 private function return_from_statement(\PDOStatement $sth)
 {
     if ($sth->columnCount()) {
         if ($data = $sth->fetch()) {
             $rows[] = $data;
             while ($data = $sth->fetch()) {
                 $rows[] = $data;
             }
         } else {
             return null;
         }
     } else {
         return null;
     }
     $return_from_array = function ($array) use(&$return_from_array) {
         if (!is_array($array)) {
             return $array;
         } else {
             if (count($array) > 1) {
                 return array_map($return_from_array, $array);
             } else {
                 $result = reset($array);
                 if (is_array($result)) {
                     if (count($result) > 1) {
                         return array_map($return_from_array, $result);
                     } else {
                         return reset($result);
                     }
                 } else {
                     return $result;
                 }
             }
         }
     };
     return $return_from_array($rows);
 }
 /**
  * Fetch all returns columns typed as Recess expects:
  *  i.e. Dates become Unix Time Based and TinyInts are converted to Boolean
  *
  * TODO: Refactor this into the query code so that MySql does the type conversion
  * instead of doing it slow and manually in PHP.
  * 
  * @param PDOStatement $statement
  * @return array fetchAll() of statement
  */
 function fetchAll(PDOStatement $statement)
 {
     try {
         $columnCount = $statement->columnCount();
         $manualFetch = false;
         $booleanColumns = array();
         $dateColumns = array();
         $timeColumns = array();
         for ($i = 0; $i < $columnCount; $i++) {
             $meta = $statement->getColumnMeta($i);
             if (isset($meta['native_type'])) {
                 switch ($meta['native_type']) {
                     case 'TIMESTAMP':
                     case 'DATETIME':
                     case 'DATE':
                         $dateColumns[] = $meta['name'];
                         break;
                     case 'TIME':
                         $timeColumns[] = $meta['name'];
                         break;
                 }
             } else {
                 if ($meta['len'] == 1) {
                     $booleanColumns[] = $meta['name'];
                 }
             }
         }
         if (!empty($booleanColumns) || !empty($datetimeColumns) || !empty($dateColumns) || !empty($timeColumns)) {
             $manualFetch = true;
         }
     } catch (PDOException $e) {
         return $statement->fetchAll();
     }
     if (!$manualFetch) {
         return $statement->fetchAll();
     } else {
         $results = array();
         while ($result = $statement->fetch()) {
             foreach ($booleanColumns as $column) {
                 $result->{$column} = $result->{$column} == 1;
             }
             foreach ($dateColumns as $column) {
                 $result->{$column} = strtotime($result->{$column});
             }
             foreach ($timeColumns as $column) {
                 $result->{$column} = strtotime('1970-01-01 ' . $result->{$column});
             }
             $results[] = $result;
         }
         return $results;
     }
 }
Beispiel #26
0
    public function bind(PDOStatement $stmt, YokazeDb_Vo $vo)
    {
        $columnCount = $stmt->columnCount();
        $columnTypes = array();
        $columnNames = array();
        $VoNames     = array();
        for ($i = 0; $i < $columnCount; $i++){
            $meta = $stmt->getColumnMeta($i);
            if (!$meta)
                break;
            //if (isset($meta['pdo_type']))
                $columnTypes[$i] = $meta['pdo_type'];
            $columnNames[$i] = $meta['name'];
            $name = implode('', array_map('ucfirst', explode('_', $meta['name'])));
            $name[0] = strtolower($name[0]);
            $voNames[$i] = $name;
        }


        for($i = 0; $i < $columnCount; $i++){
            $name = $voNames[$i];
            $vo->$name = null;
            $stmt->bindColumn($columnNames[$i], $vo->$name, $columnTypes[$i]);
        }
    }
Beispiel #27
0
 function get_convertors(\PDOStatement $statement)
 {
     $convertors = array();
     $column_count = $statement->columnCount();
     for ($i = 0; $i < $column_count; $i++) {
         $column_meta = $statement->getColumnMeta($i);
         if ($column_meta) {
             $convertor = null;
             switch ($column_meta['native_type']) {
                 case 'TINY':
                     $convertor = $column_meta['len'] === 1 ? 'boolval' : 'intval';
                     break;
                 case 'LONGLONG':
                     if ($column_meta['len'] <= PHP_INT_MAX) {
                         $convertor = 'intval';
                     }
                     break;
                 case 'SHORT':
                 case 'LONG':
                 case 'INT24':
                 case 'BIT':
                     $convertor = 'intval';
                     break;
                 case 'FLOAT':
                 case 'DOUBLE':
                 case 'NEWDECIMAL':
                     $convertor = 'floatval';
                     break;
             }
             $convertors[$column_meta['name']] = $convertor;
         }
     }
     return $convertors;
 }
Beispiel #28
0
 /**
 	 233:  * Builds a map of the columns contained in a result
 	 234:  *
 	 235:  * @param PDOStatement $results
 	 236:  * @return void
 	 237:  */
 public function resultSet($results)
 {
     $this->map = array();
     $numFields = $results->columnCount();
     $index = 0;
     while ($numFields-- > 0) {
         $column = $results->getColumnMeta($index);
         if ($column['len'] === 1 && (empty($column['native_type']) || $column['native_type'] === 'TINY')) {
             $type = 'boolean';
         } else {
             $type = empty($column['native_type']) ? 'string' : $column['native_type'];
         }
         if (!empty($column['table']) && strpos($column['name'], $this->virtualFieldSeparator) === false) {
             $this->map[$index++] = array($column['table'], $column['name'], $type);
         } else {
             $this->map[$index++] = array(0, $column['name'], $type);
         }
     }
 }
Beispiel #29
0
 /**
  * Is query result
  *
  * @return boolean
  */
 public function isQueryResult()
 {
     return $this->resource->columnCount() > 0;
 }
 /**
  * 获得列数
  *
  * @access public
  * @return int $count 统计列数
  */
 public function get_column_count()
 {
     return parent::columnCount();
 }