Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

294 lines
10KB

  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\db\sqlite;
  8. use yii\base\NotSupportedException;
  9. use yii\db\Expression;
  10. use yii\db\TableSchema;
  11. use yii\db\ColumnSchema;
  12. use yii\db\Transaction;
  13. /**
  14. * Schema is the class for retrieving metadata from a SQLite (2/3) database.
  15. *
  16. * @property string $transactionIsolationLevel The transaction isolation level to use for this transaction.
  17. * This can be either [[Transaction::READ_UNCOMMITTED]] or [[Transaction::SERIALIZABLE]].
  18. *
  19. * @author Qiang Xue <qiang.xue@gmail.com>
  20. * @since 2.0
  21. */
  22. class Schema extends \yii\db\Schema
  23. {
  24. /**
  25. * @var array mapping from physical column types (keys) to abstract column types (values)
  26. */
  27. public $typeMap = [
  28. 'tinyint' => self::TYPE_SMALLINT,
  29. 'bit' => self::TYPE_SMALLINT,
  30. 'boolean' => self::TYPE_BOOLEAN,
  31. 'bool' => self::TYPE_BOOLEAN,
  32. 'smallint' => self::TYPE_SMALLINT,
  33. 'mediumint' => self::TYPE_INTEGER,
  34. 'int' => self::TYPE_INTEGER,
  35. 'integer' => self::TYPE_INTEGER,
  36. 'bigint' => self::TYPE_BIGINT,
  37. 'float' => self::TYPE_FLOAT,
  38. 'double' => self::TYPE_DOUBLE,
  39. 'real' => self::TYPE_FLOAT,
  40. 'decimal' => self::TYPE_DECIMAL,
  41. 'numeric' => self::TYPE_DECIMAL,
  42. 'tinytext' => self::TYPE_TEXT,
  43. 'mediumtext' => self::TYPE_TEXT,
  44. 'longtext' => self::TYPE_TEXT,
  45. 'text' => self::TYPE_TEXT,
  46. 'varchar' => self::TYPE_STRING,
  47. 'string' => self::TYPE_STRING,
  48. 'char' => self::TYPE_CHAR,
  49. 'blob' => self::TYPE_BINARY,
  50. 'datetime' => self::TYPE_DATETIME,
  51. 'year' => self::TYPE_DATE,
  52. 'date' => self::TYPE_DATE,
  53. 'time' => self::TYPE_TIME,
  54. 'timestamp' => self::TYPE_TIMESTAMP,
  55. 'enum' => self::TYPE_STRING,
  56. ];
  57. /**
  58. * Quotes a table name for use in a query.
  59. * A simple table name has no schema prefix.
  60. * @param string $name table name
  61. * @return string the properly quoted table name
  62. */
  63. public function quoteSimpleTableName($name)
  64. {
  65. return strpos($name, '`') !== false ? $name : "`$name`";
  66. }
  67. /**
  68. * Quotes a column name for use in a query.
  69. * A simple column name has no prefix.
  70. * @param string $name column name
  71. * @return string the properly quoted column name
  72. */
  73. public function quoteSimpleColumnName($name)
  74. {
  75. return strpos($name, '`') !== false || $name === '*' ? $name : "`$name`";
  76. }
  77. /**
  78. * Creates a query builder for the MySQL database.
  79. * This method may be overridden by child classes to create a DBMS-specific query builder.
  80. * @return QueryBuilder query builder instance
  81. */
  82. public function createQueryBuilder()
  83. {
  84. return new QueryBuilder($this->db);
  85. }
  86. /**
  87. * @inheritdoc
  88. * @return ColumnSchemaBuilder column schema builder instance
  89. */
  90. public function createColumnSchemaBuilder($type, $length = null)
  91. {
  92. return new ColumnSchemaBuilder($type, $length);
  93. }
  94. /**
  95. * Returns all table names in the database.
  96. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  97. * @return array all table names in the database. The names have NO schema name prefix.
  98. */
  99. protected function findTableNames($schema = '')
  100. {
  101. $sql = "SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence' ORDER BY tbl_name";
  102. return $this->db->createCommand($sql)->queryColumn();
  103. }
  104. /**
  105. * Loads the metadata for the specified table.
  106. * @param string $name table name
  107. * @return TableSchema driver dependent table metadata. Null if the table does not exist.
  108. */
  109. protected function loadTableSchema($name)
  110. {
  111. $table = new TableSchema;
  112. $table->name = $name;
  113. $table->fullName = $name;
  114. if ($this->findColumns($table)) {
  115. $this->findConstraints($table);
  116. return $table;
  117. } else {
  118. return null;
  119. }
  120. }
  121. /**
  122. * Collects the table column metadata.
  123. * @param TableSchema $table the table metadata
  124. * @return boolean whether the table exists in the database
  125. */
  126. protected function findColumns($table)
  127. {
  128. $sql = 'PRAGMA table_info(' . $this->quoteSimpleTableName($table->name) . ')';
  129. $columns = $this->db->createCommand($sql)->queryAll();
  130. if (empty($columns)) {
  131. return false;
  132. }
  133. foreach ($columns as $info) {
  134. $column = $this->loadColumnSchema($info);
  135. $table->columns[$column->name] = $column;
  136. if ($column->isPrimaryKey) {
  137. $table->primaryKey[] = $column->name;
  138. }
  139. }
  140. if (count($table->primaryKey) === 1 && !strncasecmp($table->columns[$table->primaryKey[0]]->dbType, 'int', 3)) {
  141. $table->sequenceName = '';
  142. $table->columns[$table->primaryKey[0]]->autoIncrement = true;
  143. }
  144. return true;
  145. }
  146. /**
  147. * Collects the foreign key column details for the given table.
  148. * @param TableSchema $table the table metadata
  149. */
  150. protected function findConstraints($table)
  151. {
  152. $sql = 'PRAGMA foreign_key_list(' . $this->quoteSimpleTableName($table->name) . ')';
  153. $keys = $this->db->createCommand($sql)->queryAll();
  154. foreach ($keys as $key) {
  155. $id = (int) $key['id'];
  156. if (!isset($table->foreignKeys[$id])) {
  157. $table->foreignKeys[$id] = [$key['table'], $key['from'] => $key['to']];
  158. } else {
  159. // composite FK
  160. $table->foreignKeys[$id][$key['from']] = $key['to'];
  161. }
  162. }
  163. }
  164. /**
  165. * Returns all unique indexes for the given table.
  166. * Each array element is of the following structure:
  167. *
  168. * ```php
  169. * [
  170. * 'IndexName1' => ['col1' [, ...]],
  171. * 'IndexName2' => ['col2' [, ...]],
  172. * ]
  173. * ```
  174. *
  175. * @param TableSchema $table the table metadata
  176. * @return array all unique indexes for the given table.
  177. */
  178. public function findUniqueIndexes($table)
  179. {
  180. $sql = 'PRAGMA index_list(' . $this->quoteSimpleTableName($table->name) . ')';
  181. $indexes = $this->db->createCommand($sql)->queryAll();
  182. $uniqueIndexes = [];
  183. foreach ($indexes as $index) {
  184. $indexName = $index['name'];
  185. $indexInfo = $this->db->createCommand('PRAGMA index_info(' . $this->quoteValue($index['name']) . ')')->queryAll();
  186. if ($index['unique']) {
  187. $uniqueIndexes[$indexName] = [];
  188. foreach ($indexInfo as $row) {
  189. $uniqueIndexes[$indexName][] = $row['name'];
  190. }
  191. }
  192. }
  193. return $uniqueIndexes;
  194. }
  195. /**
  196. * Loads the column information into a [[ColumnSchema]] object.
  197. * @param array $info column information
  198. * @return ColumnSchema the column schema object
  199. */
  200. protected function loadColumnSchema($info)
  201. {
  202. $column = $this->createColumnSchema();
  203. $column->name = $info['name'];
  204. $column->allowNull = !$info['notnull'];
  205. $column->isPrimaryKey = $info['pk'] != 0;
  206. $column->dbType = strtolower($info['type']);
  207. $column->unsigned = strpos($column->dbType, 'unsigned') !== false;
  208. $column->type = self::TYPE_STRING;
  209. if (preg_match('/^(\w+)(?:\(([^\)]+)\))?/', $column->dbType, $matches)) {
  210. $type = strtolower($matches[1]);
  211. if (isset($this->typeMap[$type])) {
  212. $column->type = $this->typeMap[$type];
  213. }
  214. if (!empty($matches[2])) {
  215. $values = explode(',', $matches[2]);
  216. $column->size = $column->precision = (int) $values[0];
  217. if (isset($values[1])) {
  218. $column->scale = (int) $values[1];
  219. }
  220. if ($column->size === 1 && ($type === 'tinyint' || $type === 'bit')) {
  221. $column->type = 'boolean';
  222. } elseif ($type === 'bit') {
  223. if ($column->size > 32) {
  224. $column->type = 'bigint';
  225. } elseif ($column->size === 32) {
  226. $column->type = 'integer';
  227. }
  228. }
  229. }
  230. }
  231. $column->phpType = $this->getColumnPhpType($column);
  232. if (!$column->isPrimaryKey) {
  233. if ($info['dflt_value'] === 'null' || $info['dflt_value'] === '' || $info['dflt_value'] === null) {
  234. $column->defaultValue = null;
  235. } elseif ($column->type === 'timestamp' && $info['dflt_value'] === 'CURRENT_TIMESTAMP') {
  236. $column->defaultValue = new Expression('CURRENT_TIMESTAMP');
  237. } else {
  238. $value = trim($info['dflt_value'], "'\"");
  239. $column->defaultValue = $column->phpTypecast($value);
  240. }
  241. }
  242. return $column;
  243. }
  244. /**
  245. * Sets the isolation level of the current transaction.
  246. * @param string $level The transaction isolation level to use for this transaction.
  247. * This can be either [[Transaction::READ_UNCOMMITTED]] or [[Transaction::SERIALIZABLE]].
  248. * @throws \yii\base\NotSupportedException when unsupported isolation levels are used.
  249. * SQLite only supports SERIALIZABLE and READ UNCOMMITTED.
  250. * @see http://www.sqlite.org/pragma.html#pragma_read_uncommitted
  251. */
  252. public function setTransactionIsolationLevel($level)
  253. {
  254. switch ($level) {
  255. case Transaction::SERIALIZABLE:
  256. $this->db->createCommand('PRAGMA read_uncommitted = False;')->execute();
  257. break;
  258. case Transaction::READ_UNCOMMITTED:
  259. $this->db->createCommand('PRAGMA read_uncommitted = True;')->execute();
  260. break;
  261. default:
  262. throw new NotSupportedException(get_class($this) . ' only supports transaction isolation levels READ UNCOMMITTED and SERIALIZABLE.');
  263. }
  264. }
  265. }