dbo_postgres.php

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

PHP
687
字号
	function getSequence($table, $field = 'id') {		if (is_object($table)) {			$table = $this->fullTableName($table, false);		}		if (isset($this->_sequenceMap[$table]) && isset($this->_sequenceMap[$table][$field])) {			return $this->_sequenceMap[$table][$field];		} else {			return "{$table}_{$field}_seq";		}	}/** * Deletes all the records in a table and drops all associated auto-increment sequences * * @param mixed $table A string or model class representing the table to be truncated * @param integer $reset If -1, sequences are dropped, if 0 (default), sequences are reset, *						and if 1, sequences are not modified * @return boolean	SQL TRUNCATE TABLE statement, false if not applicable. * @access public */	function truncate($table, $reset = 0) {		if (parent::truncate($table)) {			$table = $this->fullTableName($table, false);			if (isset($this->_sequenceMap[$table]) && $reset !== 1) {				foreach ($this->_sequenceMap[$table] as $field => $sequence) {					if ($reset === 0) {						$this->execute("ALTER SEQUENCE \"{$sequence}\" RESTART WITH 1");					} elseif ($reset === -1) {						$this->execute("DROP SEQUENCE IF EXISTS \"{$sequence}\"");					}				}			}			return true;		}		return false;	}/** * Prepares field names to be quoted by parent * * @param string $data * @return string SQL field */	function name($data) {		return parent::name(str_replace('"__"', '__', $data));	}/** * Generates the fields list of an SQL query. * * @param Model $model * @param string $alias Alias tablename * @param mixed $fields * @return array */	function fields(&$model, $alias = null, $fields = array(), $quote = true) {		if (empty($alias)) {			$alias = $model->alias;		}		$fields = parent::fields($model, $alias, $fields, false);		if (!$quote) {			return $fields;		}		$count = count($fields);		if ($count >= 1 && $fields[0] != '*' && strpos($fields[0], 'COUNT(*)') === false) {			for ($i = 0; $i < $count; $i++) {				if (!preg_match('/^.+\\(.*\\)/', $fields[$i]) && !preg_match('/\s+AS\s+/', $fields[$i])) {					$prepend = '';					if (strpos($fields[$i], 'DISTINCT') !== false) {						$prepend = 'DISTINCT ';						$fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));					}					if (strrpos($fields[$i], '.') === false) {						$fields[$i] = $prepend . $this->name($alias) . '.' . $this->name($fields[$i]) . ' AS ' . $this->name($alias . '__' . $fields[$i]);					} else {						$build = explode('.', $fields[$i]);						$fields[$i] = $prepend . $this->name($build[0]) . '.' . $this->name($build[1]) . ' AS ' . $this->name($build[0] . '__' . $build[1]);					}				}			}		}		return $fields;	}/** * Returns a limit statement in the correct format for the particular database. * * @param integer $limit Limit of results returned * @param integer $offset Offset from which to start results * @return string SQL limit/offset statement */	function limit($limit, $offset = null) {		if ($limit) {			$rt = '';			if (!strpos(strtolower($limit), 'limit') || strpos(strtolower($limit), 'limit') === 0) {				$rt = ' LIMIT';			}			$rt .= ' ' . $limit;			if ($offset) {				$rt .= ' OFFSET ' . $offset;			}			return $rt;		}		return null;	}/** * Converts database-layer column types to basic types * * @param string $real Real database-layer column type (i.e. "varchar(255)") * @return string Abstract column type (i.e. "string") */	function column($real) {		if (is_array($real)) {			$col = $real['name'];			if (isset($real['limit'])) {				$col .= '(' . $real['limit'] . ')';			}			return $col;		}		$col = str_replace(')', '', $real);		$limit = null;		if (strpos($col, '(') !== false) {			list($col, $limit) = explode('(', $col);		}		if (in_array($col, array('date', 'time'))) {			return $col;		}		if (strpos($col, 'timestamp') !== false) {			return 'datetime';		}		if (strpos($col, 'time') === 0) {			return 'time';		}		if ($col == 'inet') {			return('inet');		}		if ($col == 'boolean') {			return 'boolean';		}		if (strpos($col, 'int') !== false && $col != 'interval') {			return 'integer';		}		if (strpos($col, 'char') !== false) {			return 'string';		}		if (strpos($col, 'text') !== false) {			return 'text';		}		if (strpos($col, 'bytea') !== false) {			return 'binary';		}		if (in_array($col, array('float', 'float4', 'float8', 'double', 'double precision', 'decimal', 'real', 'numeric'))) {			return 'float';		}		return 'text';	}/** * Gets the length of a database-native column description, or null if no length * * @param string $real Real database-layer column type (i.e. "varchar(255)") * @return int An integer representing the length of the column */	function length($real) {		$col = str_replace(array(')', 'unsigned'), '', $real);		$limit = null;		if (strpos($col, '(') !== false) {			list($col, $limit) = explode('(', $col);		}		if ($limit != null) {			return intval($limit);		}		return null;	}/** * Enter description here... * * @param unknown_type $results */	function resultSet(&$results) {		$this->results =& $results;		$this->map = array();		$num_fields = pg_num_fields($results);		$index = 0;		$j = 0;		while ($j < $num_fields) {			$columnName = pg_field_name($results, $j);			if (strpos($columnName, '__')) {				$parts = explode('__', $columnName);				$this->map[$index++] = array($parts[0], $parts[1]);			} else {				$this->map[$index++] = array(0, $columnName);			}			$j++;		}	}/** * Fetches the next row from the current result set * * @return unknown */	function fetchResult() {		if ($row = pg_fetch_row($this->results)) {			$resultRow = array();			$i = 0;			foreach ($row as $index => $field) {				list($table, $column) = $this->map[$index];				$resultRow[$table][$column] = $row[$index];				$i++;			}			return $resultRow;		} else {			return false;		}	}/** * Translates between PHP boolean values and PostgreSQL boolean values * * @param mixed $data Value to be translated * @param boolean $quote	True to quote value, false otherwise * @return mixed Converted boolean value */	function boolean($data, $quote = true) {		switch (true) {			case ($data === true || $data === false):				return $data;			case ($data === 't' || $data === 'f'):				return ($data === 't');			default:				return (bool)$data;			break;		}	}/** * Sets the database encoding * * @param mixed $enc Database encoding * @return boolean True on success, false on failure */	function setEncoding($enc) {		return pg_set_client_encoding($this->connection, $enc) == 0;	}/** * Gets the database encoding * * @return string The database encoding */	function getEncoding() {		return pg_client_encoding($this->connection);	}/** * Generate a Postgres-native column schema string * * @param array $column An array structured like the following: array('name'=>'value', 'type'=>'value'[, options]), *                      where options can be 'default', 'length', or 'key'. * @return string */	function buildColumn($column) {		$out = preg_replace('/integer\([0-9]+\)/', 'integer', parent::buildColumn($column));		$out = str_replace('integer serial', 'serial', $out);		if (strpos($out, 'DEFAULT DEFAULT')) {			if (isset($column['null']) && $column['null']) {				$out = str_replace('DEFAULT DEFAULT', 'DEFAULT NULL', $out);			} elseif (in_array($column['type'], array('integer', 'float'))) {				$out = str_replace('DEFAULT DEFAULT', 'DEFAULT 0', $out);			} elseif ($column['type'] == 'boolean') {				$out = str_replace('DEFAULT DEFAULT', 'DEFAULT FALSE', $out);			}		}		return $out;	}/** * Format indexes for create table * * @param array $indexes * @param string $table * @return string */	function buildIndex($indexes, $table = null) {		$join = array();		foreach ($indexes as $name => $value) {			if ($name == 'PRIMARY') {				$out = 'PRIMARY KEY  (' . $this->name($value['column']) . ')';			} else {				$out = 'CREATE ';				if (!empty($value['unique'])) {					$out .= 'UNIQUE ';				}				if (is_array($value['column'])) {					$value['column'] = join(', ', array_map(array(&$this, 'name'), $value['column']));				} else {					$value['column'] = $this->name($value['column']);				}				$out .= "INDEX {$name} ON {$table}({$value['column']});";			}			$join[] = $out;		}		return $join;	}/** * Overrides DboSource::renderStatement to handle schema generation with Postgres-style indexes * * @param string $type * @param array $data * @return string */	function renderStatement($type, $data) {		switch (strtolower($type)) {			case 'schema':				extract($data);				foreach ($indexes as $i => $index) {					if (preg_match('/PRIMARY KEY/', $index)) {						unset($indexes[$i]);						$columns[] = $index;						break;					}				}				foreach (array('columns', 'indexes') as $var) {					if (is_array(${$var})) {						${$var} = "\t" . join(",\n\t", array_filter(${$var}));					}				}				return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}";			break;			default:				return parent::renderStatement($type, $data);			break;		}	}}?>

⌨️ 快捷键说明

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