dbo_postgres.php

来自「Cake Framwork , Excellent」· PHP 代码 · 共 687 行 · 第 1/2 页

PHP
687
字号
<?php/* SVN FILE: $Id: dbo_postgres.php 7118 2008-06-04 20:49:29Z gwoo $ *//** * PostgreSQL layer for DBO. * * Long description for file * * PHP versions 4 and 5 * * CakePHP(tm) :  Rapid Development Framework <http://www.cakephp.org/> * Copyright 2005-2008, Cake Software Foundation, Inc. *								1785 E. Sahara Avenue, Suite 490-204 *								Las Vegas, Nevada 89104 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright		Copyright 2005-2008, Cake Software Foundation, Inc. * @link				http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project * @package			cake * @subpackage		cake.cake.libs.model.datasources.dbo * @since			CakePHP(tm) v 0.9.1.114 * @version			$Revision: 7118 $ * @modifiedby		$LastChangedBy: gwoo $ * @lastmodified	$Date: 2008-06-04 13:49:29 -0700 (Wed, 04 Jun 2008) $ * @license			http://www.opensource.org/licenses/mit-license.php The MIT License *//** * PostgreSQL layer for DBO. * * Long description for class * * @package		cake * @subpackage	cake.cake.libs.model.datasources.dbo */class DboPostgres extends DboSource {/** * Driver description * * @var string * @access public */	var $description = "PostgreSQL DBO Driver";/** * Index of basic SQL commands * * @var array * @access protected */	var $_commands = array(		'begin'    => 'BEGIN',		'commit'   => 'COMMIT',		'rollback' => 'ROLLBACK'	);/** * Base driver configuration settings.  Merged with user settings. * * @var array * @access protected */	var $_baseConfig = array(		'connect'	=> 'pg_pconnect',		'persistent' => true,		'host' => 'localhost',		'login' => 'root',		'password' => '',		'database' => 'cake',		'schema' => 'public',		'port' => 5432,		'encoding' => ''	);	var $columns = array(		'primary_key' => array('name' => 'serial NOT NULL'),		'string' => array('name'  => 'varchar', 'limit' => '255'),		'text' => array('name' => 'text'),		'integer' => array('name' => 'integer', 'formatter' => 'intval'),		'float' => array('name' => 'float', 'formatter' => 'floatval'),		'datetime' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),		'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),		'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),		'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),		'binary' => array('name' => 'bytea'),		'boolean' => array('name' => 'boolean'),		'number' => array('name' => 'numeric'),		'inet' => array('name'  => 'inet')	);	var $startQuote = '"';	var $endQuote = '"';/** * Contains mappings of custom auto-increment sequences, if a table uses a sequence name * other than what is dictated by convention. * * @var array */	var $_sequenceMap = array();/** * Connects to the database using options in the given configuration array. * * @return True if successfully connected. */	function connect() {		$config = $this->config;		$conn  = "host='{$config['host']}' port='{$config['port']}' dbname='{$config['database']}' ";		$conn .= "user='{$config['login']}' password='{$config['password']}'";		if (!$config['persistent']) {			$this->connection = pg_connect($conn, PGSQL_CONNECT_FORCE_NEW);		} else {			$this->connection = pg_pconnect($conn);		}		$this->connected = false;		if ($this->connection) {			$this->connected = true;			$this->_execute("SET search_path TO " . $config['schema']);		}		if (!empty($config['encoding'])) {			$this->setEncoding($config['encoding']);		}		return $this->connected;	}/** * Disconnects from database. * * @return boolean True if the database could be disconnected, else false */	function disconnect() {		if (is_resource($this->_result)) {			pg_free_result($this->_result);		}		if (is_resource($this->connection)) {			$this->connected = !pg_close($this->connection);		} else {			$this->connected = false;		}		return !$this->connected;	}/** * Executes given SQL statement. * * @param string $sql SQL statement * @return resource Result resource identifier */	function _execute($sql) {		return pg_query($this->connection, $sql);	}/** * Returns an array of tables in the database. If there are no tables, an error is raised and the application exits. * * @return array Array of tablenames in the database */	function listSources() {		$cache = parent::listSources();		if ($cache != null) {			return $cache;		}		$schema = $this->config['schema'];		$sql = "SELECT table_name as name FROM INFORMATION_SCHEMA.tables WHERE table_schema = '{$schema}';";		$result = $this->fetchAll($sql, false);		if (!$result) {			return array();		} else {			$tables = array();			foreach ($result as $item) {				$tables[] = $item[0]['name'];			}			parent::listSources($tables);			return $tables;		}	}/** * Returns an array of the fields in given table name. * * @param string $tableName Name of database table to inspect * @return array Fields in table. Keys are name and type */	function &describe(&$model) {		$fields = parent::describe($model);		$table = $this->fullTableName($model, false);		$this->_sequenceMap[$table] = array();		if ($fields === null) {			$cols = $this->fetchAll("SELECT DISTINCT column_name AS name, data_type AS type, is_nullable AS null, column_default AS default, ordinal_position AS position, character_maximum_length AS char_length, character_octet_length AS oct_length FROM information_schema.columns WHERE table_name =" . $this->value($table) . " ORDER BY position", false);			foreach ($cols as $column) {				$colKey = array_keys($column);				if (isset($column[$colKey[0]]) && !isset($column[0])) {					$column[0] = $column[$colKey[0]];				}				if (isset($column[0])) {					$c = $column[0];					if (!empty($c['char_length'])) {						$length = intval($c['char_length']);					} elseif (!empty($c['oct_length'])) {						$length = intval($c['oct_length']);					} else {						$length = $this->length($c['type']);					}					$fields[$c['name']] = array(						'type'    => $this->column($c['type']),						'null'    => ($c['null'] == 'NO' ? false : true),						'default' => preg_replace("/^'(.*)'$/", "$1", preg_replace('/::.*/', '', $c['default'])),						'length'  => $length					);					if ($c['name'] == $model->primaryKey) {						$fields[$c['name']]['key'] = 'primary';						if ($fields[$c['name']]['type'] !== 'string') {							$fields[$c['name']]['length'] = 11;						}					}					if ($fields[$c['name']]['default'] == 'NULL' || preg_match('/nextval\([\'"]?(\w+)/', $c['default'], $seq)) {						$fields[$c['name']]['default'] = null;						if (!empty($seq) && isset($seq[1])) {							$this->_sequenceMap[$table][$c['name']] = $seq[1];						}					}				}			}			$this->__cacheDescription($table, $fields);		}		if (isset($model->sequence)) {			$this->_sequenceMap[$table][$model->primaryKey] = $model->sequence;		}		return $fields;	}/** * Returns a quoted and escaped string of $data for use in an SQL statement. * * @param string $data String to be prepared for use in an SQL statement * @param string $column The column into which this data will be inserted * @return string Quoted and escaped * @todo Add logic that formats/escapes data based on column type */	function value($data, $column = null) {		$parent = parent::value($data, $column);		if ($parent != null) {			return $parent;		}		if ($data === null) {			return 'NULL';		}		if (empty($column)) {			$column = $this->introspectType($data);		}		switch($column) {			case 'inet':			case 'float':			case 'integer':				if ($data === '') {					return 'DEFAULT';				}			case 'binary':				$data = pg_escape_bytea($data);			break;			case 'boolean':				if ($data === true) {					return 'TRUE';				} elseif ($data === false) {					return 'FALSE';				}				return 'DEFAULT';			break;			default:				$data = pg_escape_string($data);			break;		}		return "'" . $data . "'";	}/** * Returns a formatted error message from previous database operation. * * @return string Error message */	function lastError() {		$error = pg_last_error($this->connection);		if ($error) {			return $error;		}		return null;	}/** * Returns number of affected rows in previous database operation. If no previous operation exists, this returns false. * * @return integer Number of affected rows */	function lastAffected() {		if ($this->_result) {			$return = pg_affected_rows($this->_result);			return $return;		}		return false;	}/** * Returns number of rows in previous resultset. If no previous resultset exists, * this returns false. * * @return integer Number of rows in resultset */	function lastNumRows() {		if ($this->_result) {			$return = pg_num_rows($this->_result);			return $return;		}		return false;	}/** * Returns the ID generated from the previous INSERT operation. * * @param string $source Name of the database table * @param string $field Name of the ID database field. Defaults to "id" * @return integer */	function lastInsertId($source, $field = 'id') {		$seq = $this->getSequence($source, $field);		$data = $this->fetchRow("SELECT last_value AS max FROM \"{$seq}\"");		return $data[0]['max'];	}/** * Gets the associated sequence for the given table/field * * @param mixed $table Either a full table name (with prefix) as a string, or a model object * @param string $field Name of the ID database field. Defaults to "id" * @return string The associated sequence name from the sequence map, defaults to "{$table}_{$field}_seq" */

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?