Schema.php 8.08 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\db\cubrid;

use yii\db\Expression;
use yii\db\TableSchema;
use yii\db\ColumnSchema;

/**
 * Schema is the class for retrieving metadata from a CUBRID database (version 9.1.x and higher).
 *
 * @author Carsten Brandt <mail@cebe.cc>
 * @since 2.0
 */
class Schema extends \yii\db\Schema
{
	/**
	 * @var array mapping from physical column types (keys) to abstract column types (values)
	 * Please refer to [CUBRID manual](http://www.cubrid.org/manual/91/en/sql/datatype.html) for
	 * details on data types.
	 */
Alexander Makarov committed
27
	public $typeMap = [
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
		// Numeric data types
		'short' => self::TYPE_SMALLINT,
		'smallint' => self::TYPE_SMALLINT,
		'int' => self::TYPE_INTEGER,
		'integer' => self::TYPE_INTEGER,
		'bigint' => self::TYPE_BIGINT,
		'numeric' => self::TYPE_DECIMAL,
		'decimal' => self::TYPE_DECIMAL,
		'float' => self::TYPE_FLOAT,
		'real' => self::TYPE_FLOAT,
		'double' => self::TYPE_FLOAT,
		'double precision' => self::TYPE_FLOAT,
		'monetary' => self::TYPE_MONEY,
		// Date/Time data types
		'date' => self::TYPE_DATE,
		'time' => self::TYPE_TIME,
		'timestamp' => self::TYPE_TIMESTAMP,
		'datetime' => self::TYPE_DATETIME,
		// String data types
		'char' => self::TYPE_STRING,
		'varchar' => self::TYPE_STRING,
		'char varying' => self::TYPE_STRING,
		'nchar' => self::TYPE_STRING,
		'nchar varying' => self::TYPE_STRING,
		'string' => self::TYPE_STRING,
		// BLOB/CLOB data types
		'blob' => self::TYPE_BINARY,
		'clob' => self::TYPE_BINARY,
56
		// Bit string data types
Carsten Brandt committed
57 58
		'bit' => self::TYPE_STRING,
		'bit varying' => self::TYPE_STRING,
59
		// Collection data types (considered strings for now)
Carsten Brandt committed
60 61 62 63 64
		'set' => self::TYPE_STRING,
		'multiset' => self::TYPE_STRING,
		'list' => self::TYPE_STRING,
		'sequence' => self::TYPE_STRING,
		'enum' => self::TYPE_STRING,
Alexander Makarov committed
65
	];
66

67 68 69 70 71 72 73 74 75

	/**
	 * @inheritdoc
	 */
	public function releaseSavepoint($name)
	{
		// does nothing as cubrid does not support this
	}

76 77 78 79 80 81 82 83
	/**
	 * Quotes a table name for use in a query.
	 * A simple table name has no schema prefix.
	 * @param string $name table name
	 * @return string the properly quoted table name
	 */
	public function quoteSimpleTableName($name)
	{
84
		return strpos($name, '"') !== false ? $name : '"' . $name . '"';
85 86 87 88 89 90 91 92 93 94
	}

	/**
	 * Quotes a column name for use in a query.
	 * A simple column name has no prefix.
	 * @param string $name column name
	 * @return string the properly quoted column name
	 */
	public function quoteSimpleColumnName($name)
	{
95
		return strpos($name, '"') !== false || $name === '*' ? $name : '"' . $name . '"';
96 97
	}

98 99 100 101 102 103 104 105 106
	/**
	 * Quotes a string value for use in a query.
	 * Note that if the parameter is not a string, it will be returned without change.
	 * @param string $str string to be quoted
	 * @return string the properly quoted string
	 * @see http://www.php.net/manual/en/function.PDO-quote.php
	 */
	public function quoteValue($str)
	{
107
		if (!is_string($str)) {
108 109 110 111
			return $str;
		}

		$this->db->open();
112
		// workaround for broken PDO::quote() implementation in CUBRID 9.1.0 http://jira.cubrid.org/browse/APIS-658
113 114
		$version = $this->db->pdo->getAttribute(\PDO::ATTR_CLIENT_VERSION);
		if (version_compare($version, '8.4.4.0002', '<') || $version[0] == '9' && version_compare($version, '9.2.0.0002', '<=')) {
115
			return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
116 117 118
		} else {
			return $this->db->pdo->quote($str);
		}
119 120
	}

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
	/**
	 * Creates a query builder for the CUBRID database.
	 * @return QueryBuilder query builder instance
	 */
	public function createQueryBuilder()
	{
		return new QueryBuilder($this->db);
	}

	/**
	 * Loads the metadata for the specified table.
	 * @param string $name table name
	 * @return TableSchema driver dependent table metadata. Null if the table does not exist.
	 */
	protected function loadTableSchema($name)
	{
		$this->db->open();
		$tableInfo = $this->db->pdo->cubrid_schema(\PDO::CUBRID_SCH_TABLE, $name);

140 141 142
		if (!isset($tableInfo[0]['NAME'])) {
			return null;
		}
143

144 145
		$table = new TableSchema();
		$table->fullName = $table->name = $tableInfo[0]['NAME'];
146

147 148
		$sql = 'SHOW FULL COLUMNS FROM ' . $this->quoteSimpleTableName($table->name);
		$columns = $this->db->createCommand($sql)->queryAll();
149

150 151 152 153
		foreach ($columns as $info) {
			$column = $this->loadColumnSchema($info);
			$table->columns[$column->name] = $column;
		}
154

155 156 157 158 159 160 161
		$primaryKeys = $this->db->pdo->cubrid_schema(\PDO::CUBRID_SCH_PRIMARY_KEY, $table->name);
		foreach ($primaryKeys as $key) {
			$column = $table->columns[$key['ATTR_NAME']];
			$column->isPrimaryKey = true;
			$table->primaryKey[] = $column->name;
			if ($column->autoIncrement) {
				$table->sequenceName = '';
162
			}
163
		}
164

165 166 167 168 169 170 171 172 173 174
		$foreignKeys = $this->db->pdo->cubrid_schema(\PDO::CUBRID_SCH_IMPORTED_KEYS, $table->name);
		foreach ($foreignKeys as $key) {
			if (isset($table->foreignKeys[$key['FK_NAME']])) {
				$table->foreignKeys[$key['FK_NAME']][$key['FKCOLUMN_NAME']] = $key['PKCOLUMN_NAME'];
			} else {
				$table->foreignKeys[$key['FK_NAME']] = [
					$key['PKTABLE_NAME'],
					$key['FKCOLUMN_NAME'] => $key['PKCOLUMN_NAME']
				];
			}
175
		}
176 177 178
		$table->foreignKeys = array_values($table->foreignKeys);

		return $table;
179 180 181 182 183 184 185 186 187
	}

	/**
	 * Loads the column information into a [[ColumnSchema]] object.
	 * @param array $info column information
	 * @return ColumnSchema the column schema object
	 */
	protected function loadColumnSchema($info)
	{
188
		$column = new ColumnSchema();
189 190 191

		$column->name = $info['Field'];
		$column->allowNull = $info['Null'] === 'YES';
192
		$column->isPrimaryKey = false; // primary key will be set by loadTableSchema() later
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
		$column->autoIncrement = stripos($info['Extra'], 'auto_increment') !== false;

		$column->dbType = strtolower($info['Type']);
		$column->unsigned = strpos($column->dbType, 'unsigned') !== false;

		$column->type = self::TYPE_STRING;
		if (preg_match('/^([\w ]+)(?:\(([^\)]+)\))?/', $column->dbType, $matches)) {
			$type = $matches[1];
			if (isset($this->typeMap[$type])) {
				$column->type = $this->typeMap[$type];
			}
			if (!empty($matches[2])) {
				if ($type === 'enum') {
					$values = explode(',', $matches[2]);
					foreach ($values as $i => $value) {
						$values[$i] = trim($value, "'");
					}
					$column->enumValues = $values;
				} else {
					$values = explode(',', $matches[2]);
					$column->size = $column->precision = (int)$values[0];
					if (isset($values[1])) {
						$column->scale = (int)$values[1];
					}
				}
			}
		}

		$column->phpType = $this->getColumnPhpType($column);

		if ($column->type === 'timestamp' && $info['Default'] === 'CURRENT_TIMESTAMP' ||
			$column->type === 'datetime' && $info['Default'] === 'SYS_DATETIME' ||
			$column->type === 'date' && $info['Default'] === 'SYS_DATE' ||
Carsten Brandt committed
226 227
			$column->type === 'time' && $info['Default'] === 'SYS_TIME'
		) {
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
			$column->defaultValue = new Expression($info['Default']);
		} else {
			$column->defaultValue = $column->typecast($info['Default']);
		}

		return $column;
	}

	/**
	 * Returns all table names in the database.
	 * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
	 * @return array all table names in the database. The names have NO schema name prefix.
	 */
	protected function findTableNames($schema = '')
	{
		$this->db->open();
		$tables = $this->db->pdo->cubrid_schema(\PDO::CUBRID_SCH_TABLE);
Alexander Makarov committed
245
		$tableNames = [];
246
		foreach ($tables as $table) {
247
			// do not list system tables
Carsten Brandt committed
248
			if ($table['TYPE'] != 0) {
249 250 251 252 253
				$tableNames[] = $table['NAME'];
			}
		}
		return $tableNames;
	}
254 255 256 257 258 259 260 261 262

	/**
	 * Determines the PDO type for the given PHP data value.
	 * @param mixed $data the data whose PDO type is to be determined
	 * @return integer the PDO type
	 * @see http://www.php.net/manual/en/pdo.constants.php
	 */
	public function getPdoType($data)
	{
Alexander Makarov committed
263
		static $typeMap = [
264 265 266 267 268 269
			// php type => PDO type
			'boolean' => \PDO::PARAM_INT, // PARAM_BOOL is not supported by CUBRID PDO
			'integer' => \PDO::PARAM_INT,
			'string' => \PDO::PARAM_STR,
			'resource' => \PDO::PARAM_LOB,
			'NULL' => \PDO::PARAM_NULL,
Alexander Makarov committed
270
		];
271 272 273
		$type = gettype($data);
		return isset($typeMap[$type]) ? $typeMap[$type] : \PDO::PARAM_STR;
	}
274
}