Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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_STRING,
  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. * Returns all table names in the database.
  88. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  89. * @return array all table names in the database. The names have NO schema name prefix.
  90. */
  91. protected function findTableNames($schema = '')
  92. {
  93. $sql = "SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence'";
  94. return $this->db->createCommand($sql)->queryColumn();
  95. }
  96. /**
  97. * Loads the metadata for the specified table.
  98. * @param string $name table name
  99. * @return TableSchema driver dependent table metadata. Null if the table does not exist.
  100. */
  101. protected function loadTableSchema($name)
  102. {
  103. $table = new TableSchema;
  104. $table->name = $name;
  105. $table->fullName = $name;
  106. if ($this->findColumns($table)) {
  107. $this->findConstraints($table);
  108. return $table;
  109. } else {
  110. return null;
  111. }
  112. }
  113. /**
  114. * Collects the table column metadata.
  115. * @param TableSchema $table the table metadata
  116. * @return boolean whether the table exists in the database
  117. */
  118. protected function findColumns($table)
  119. {
  120. $sql = "PRAGMA table_info(" . $this->quoteSimpleTableName($table->name) . ')';
  121. $columns = $this->db->createCommand($sql)->queryAll();
  122. if (empty($columns)) {
  123. return false;
  124. }
  125. foreach ($columns as $info) {
  126. $column = $this->loadColumnSchema($info);
  127. $table->columns[$column->name] = $column;
  128. if ($column->isPrimaryKey) {
  129. $table->primaryKey[] = $column->name;
  130. }
  131. }
  132. if (count($table->primaryKey) === 1 && !strncasecmp($table->columns[$table->primaryKey[0]]->dbType, 'int', 3)) {
  133. $table->sequenceName = '';
  134. $table->columns[$table->primaryKey[0]]->autoIncrement = true;
  135. }
  136. return true;
  137. }
  138. /**
  139. * Collects the foreign key column details for the given table.
  140. * @param TableSchema $table the table metadata
  141. */
  142. protected function findConstraints($table)
  143. {
  144. $sql = "PRAGMA foreign_key_list(" . $this->quoteSimpleTableName($table->name) . ')';
  145. $keys = $this->db->createCommand($sql)->queryAll();
  146. foreach ($keys as $key) {
  147. $id = (int) $key['id'];
  148. if (!isset($table->foreignKeys[$id])) {
  149. $table->foreignKeys[$id] = [$key['table'], $key['from'] => $key['to']];
  150. } else {
  151. // composite FK
  152. $table->foreignKeys[$id][$key['from']] = $key['to'];
  153. }
  154. }
  155. }
  156. /**
  157. * Returns all unique indexes for the given table.
  158. * Each array element is of the following structure:
  159. *
  160. * ~~~
  161. * [
  162. * 'IndexName1' => ['col1' [, ...]],
  163. * 'IndexName2' => ['col2' [, ...]],
  164. * ]
  165. * ~~~
  166. *
  167. * @param TableSchema $table the table metadata
  168. * @return array all unique indexes for the given table.
  169. */
  170. public function findUniqueIndexes($table)
  171. {
  172. $sql = "PRAGMA index_list(" . $this->quoteSimpleTableName($table->name) . ')';
  173. $indexes = $this->db->createCommand($sql)->queryAll();
  174. $uniqueIndexes = [];
  175. foreach ($indexes as $index) {
  176. $indexName = $index['name'];
  177. $indexInfo = $this->db->createCommand("PRAGMA index_info(" . $this->quoteValue($index['name']) . ")")->queryAll();
  178. if ($index['unique']) {
  179. $uniqueIndexes[$indexName] = [];
  180. foreach ($indexInfo as $row) {
  181. $uniqueIndexes[$indexName][] = $row['name'];
  182. }
  183. }
  184. }
  185. return $uniqueIndexes;
  186. }
  187. /**
  188. * Loads the column information into a [[ColumnSchema]] object.
  189. * @param array $info column information
  190. * @return ColumnSchema the column schema object
  191. */
  192. protected function loadColumnSchema($info)
  193. {
  194. $column = $this->createColumnSchema();
  195. $column->name = $info['name'];
  196. $column->allowNull = !$info['notnull'];
  197. $column->isPrimaryKey = $info['pk'] != 0;
  198. $column->dbType = strtolower($info['type']);
  199. $column->unsigned = strpos($column->dbType, 'unsigned') !== false;
  200. $column->type = self::TYPE_STRING;
  201. if (preg_match('/^(\w+)(?:\(([^\)]+)\))?/', $column->dbType, $matches)) {
  202. $type = strtolower($matches[1]);
  203. if (isset($this->typeMap[$type])) {
  204. $column->type = $this->typeMap[$type];
  205. }
  206. if (!empty($matches[2])) {
  207. $values = explode(',', $matches[2]);
  208. $column->size = $column->precision = (int) $values[0];
  209. if (isset($values[1])) {
  210. $column->scale = (int) $values[1];
  211. }
  212. if ($column->size === 1 && ($type === 'tinyint' || $type === 'bit')) {
  213. $column->type = 'boolean';
  214. } elseif ($type === 'bit') {
  215. if ($column->size > 32) {
  216. $column->type = 'bigint';
  217. } elseif ($column->size === 32) {
  218. $column->type = 'integer';
  219. }
  220. }
  221. }
  222. }
  223. $column->phpType = $this->getColumnPhpType($column);
  224. if (!$column->isPrimaryKey) {
  225. if ($info['dflt_value'] === 'null' || $info['dflt_value'] === '' || $info['dflt_value'] === null) {
  226. $column->defaultValue = null;
  227. } elseif ($column->type === 'timestamp' && $info['dflt_value'] === 'CURRENT_TIMESTAMP') {
  228. $column->defaultValue = new Expression('CURRENT_TIMESTAMP');
  229. } else {
  230. $value = trim($info['dflt_value'], "'\"");
  231. $column->defaultValue = $column->phpTypecast($value);
  232. }
  233. }
  234. return $column;
  235. }
  236. /**
  237. * Sets the isolation level of the current transaction.
  238. * @param string $level The transaction isolation level to use for this transaction.
  239. * This can be either [[Transaction::READ_UNCOMMITTED]] or [[Transaction::SERIALIZABLE]].
  240. * @throws \yii\base\NotSupportedException when unsupported isolation levels are used.
  241. * SQLite only supports SERIALIZABLE and READ UNCOMMITTED.
  242. * @see http://www.sqlite.org/pragma.html#pragma_read_uncommitted
  243. */
  244. public function setTransactionIsolationLevel($level)
  245. {
  246. switch($level)
  247. {
  248. case Transaction::SERIALIZABLE:
  249. $this->db->createCommand("PRAGMA read_uncommitted = False;")->execute();
  250. break;
  251. case Transaction::READ_UNCOMMITTED:
  252. $this->db->createCommand("PRAGMA read_uncommitted = True;")->execute();
  253. break;
  254. default:
  255. throw new NotSupportedException(get_class($this) . ' only supports transaction isolation levels READ UNCOMMITTED and SERIALIZABLE.');
  256. }
  257. }
  258. }