Schema.php 5.67 KB
Newer Older
Qiang Xue committed
1 2 3 4 5
<?php
/**
 * Driver class file.
 *
 * @link http://www.yiiframework.com/
Qiang Xue committed
6
 * @copyright Copyright &copy; 2008 Yii Software LLC
Qiang Xue committed
7 8 9
 * @license http://www.yiiframework.com/license/
 */

Qiang Xue committed
10
namespace yii\db\sqlite;
Qiang Xue committed
11

Qiang Xue committed
12 13
use yii\db\TableSchema;
use yii\db\ColumnSchema;
Qiang Xue committed
14 15 16 17 18 19 20

/**
 * Driver is the class for retrieving metadata from a SQLite (2/3) database.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
21
class Schema extends \yii\db\Schema
Qiang Xue committed
22 23 24 25 26 27 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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
{
	/**
	 * @var array mapping from physical column types (keys) to abstract column types (values)
	 */
	public $typeMap = array(
		'tinyint' => self::TYPE_SMALLINT,
		'bit' => self::TYPE_SMALLINT,
		'smallint' => self::TYPE_SMALLINT,
		'mediumint' => self::TYPE_INTEGER,
		'int' => self::TYPE_INTEGER,
		'integer' => self::TYPE_INTEGER,
		'bigint' => self::TYPE_BIGINT,
		'float' => self::TYPE_FLOAT,
		'double' => self::TYPE_FLOAT,
		'real' => self::TYPE_FLOAT,
		'decimal' => self::TYPE_DECIMAL,
		'numeric' => self::TYPE_DECIMAL,
		'tinytext' => self::TYPE_TEXT,
		'mediumtext' => self::TYPE_TEXT,
		'longtext' => self::TYPE_TEXT,
		'text' => self::TYPE_TEXT,
		'varchar' => self::TYPE_STRING,
		'string' => self::TYPE_STRING,
		'char' => self::TYPE_STRING,
		'datetime' => self::TYPE_DATETIME,
		'year' => self::TYPE_DATE,
		'date' => self::TYPE_DATE,
		'time' => self::TYPE_TIME,
		'timestamp' => self::TYPE_TIMESTAMP,
		'enum' => self::TYPE_STRING,
	);

	/**
	 * Creates a query builder for the MySQL database.
	 * This method may be overridden by child classes to create a DBMS-specific query builder.
	 * @return QueryBuilder query builder instance
	 */
	public function createQueryBuilder()
	{
		return new QueryBuilder($this->connection);
	}

	/**
	 * 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.
	 * If not empty, the returned table names will be prefixed with the schema name.
	 * @return array all table names in the database.
	 */
	protected function findTableNames($schema = '')
	{
		$sql = "SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence'";
		return $this->connection->createCommand($sql)->queryColumn();
	}

	/**
	 * Loads the metadata for the specified table.
	 * @param string $name table name
Qiang Xue committed
79
	 * @return \yii\db\TableSchema driver dependent table metadata. Null if the table does not exist.
Qiang Xue committed
80 81 82 83 84 85 86 87 88 89 90 91 92 93
	 */
	protected function loadTableSchema($name)
	{
		$table = new TableSchema;
		$table->name = $name;

		if ($this->findColumns($table)) {
			$this->findConstraints($table);
			return $table;
		}
	}

	/**
	 * Collects the table column metadata.
Qiang Xue committed
94
	 * @param \yii\db\TableSchema $table the table metadata
Qiang Xue committed
95 96 97 98
	 * @return boolean whether the table exists in the database
	 */
	protected function findColumns($table)
	{
Qiang Xue committed
99
		$sql = "PRAGMA table_info(" . $this->quoteSimpleTableName($table->name) . ')';
Qiang Xue committed
100 101 102 103 104 105 106 107 108
		$columns = $this->connection->createCommand($sql)->queryAll();
		if (empty($columns)) {
			return false;
		}

		foreach ($columns as $column) {
			$column = $this->createColumn($column);
			$table->columns[$column->name] = $column;
			if ($column->isPrimaryKey) {
Qiang Xue committed
109
				$table->primaryKey[] = $column->name;
Qiang Xue committed
110 111
			}
		}
Qiang Xue committed
112
		if (count($table->primaryKey) === 1 && !strncasecmp($table->columns[$table->primaryKey[0]]->dbType, 'int', 3)) {
Qiang Xue committed
113
			$table->sequenceName = '';
Qiang Xue committed
114
			$table->columns[$table->primaryKey[0]]->autoIncrement = true;
Qiang Xue committed
115 116 117 118 119 120 121
		}

		return true;
	}

	/**
	 * Collects the foreign key column details for the given table.
Qiang Xue committed
122
	 * @param \yii\db\TableSchema $table the table metadata
Qiang Xue committed
123 124 125
	 */
	protected function findConstraints($table)
	{
Qiang Xue committed
126
		$sql = "PRAGMA foreign_key_list(" . $this->quoteSimpleTableName($table->name) . ')';
Qiang Xue committed
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
		$keys = $this->connection->createCommand($sql)->queryAll();
		foreach ($keys as $key) {
			$table->foreignKeys[] = array($key['table'], $key['from'] => $key['to']);
		}
	}

	/**
	 * Creates a table column.
	 * @param array $column column metadata
	 * @return ColumnSchema normalized column metadata
	 */
	protected function createColumn($column)
	{
		$c = new ColumnSchema;
		$c->name = $column['name'];
		$c->allowNull = !$column['notnull'];
		$c->isPrimaryKey = $column['pk'] != 0;

		$c->dbType = $column['type'];
		$this->resolveColumnType($c);
Qiang Xue committed
147
		$c->phpType = $this->getColumnPhpType($this->type);
Qiang Xue committed
148 149 150 151 152 153 154 155

		$this->resolveColumnDefault($c, $column['dflt_value']);

		return $c;
	}

	/**
	 * Resolves the abstract data type for the column.
Qiang Xue committed
156
	 * @param \yii\db\ColumnSchema $column the column metadata object
Qiang Xue committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
	 */
	public function resolveColumnType($column)
	{
		$column->type = self::TYPE_STRING;
		$column->unsigned = strpos($column->dbType, 'unsigned') !== false;

		if (preg_match('/^(\w+)(?:\(([^\)]+)\))?/', $column->dbType, $matches)) {
			$type = $matches[1];
			if (isset($this->typeMap[$type])) {
				$column->type = $this->typeMap[$type];
			}

			if (!empty($matches[2])) {
				$values = explode(',', $matches[2]);
				$column->size = $column->precision = (int)$values[0];
				if (isset($values[1])) {
					$column->scale = (int)$values[1];
				}
				if ($column->size === 1 && ($type === 'tinyint' || $type === 'bit')) {
					$column->type = 'boolean';
				} elseif ($type === 'bit') {
					if ($column->size > 32) {
						$column->type = 'bigint';
					} elseif ($column->size === 32) {
						$column->type = 'integer';
					}
				}
			}
		}
	}

	/**
	 * Resolves the default value for the column.
Qiang Xue committed
190
	 * @param \yii\db\ColumnSchema $column the column metadata object
Qiang Xue committed
191 192 193 194 195 196 197 198 199 200 201
	 * @param string $value the default value fetched from database
	 */
	protected function resolveColumnDefault($column, $value)
	{
		if ($column->type === 'string') {
			$column->defaultValue = trim($value, "'\"");
		} else {
			$column->defaultValue = $column->typecast(strcasecmp($value, 'null') ? $value : null);
		}
	}
}