Schema.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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\db\TableSchema;
  9. use yii\db\ColumnSchema;
  10. /**
  11. * Schema is the class for retrieving metadata from a SQLite (2/3) database.
  12. *
  13. * @author Qiang Xue <[email protected]>
  14. * @since 2.0
  15. */
  16. class Schema extends \yii\db\Schema
  17. {
  18. /**
  19. * @var array mapping from physical column types (keys) to abstract column types (values)
  20. */
  21. public $typeMap = [
  22. 'tinyint' => self::TYPE_SMALLINT,
  23. 'bit' => self::TYPE_SMALLINT,
  24. 'smallint' => self::TYPE_SMALLINT,
  25. 'mediumint' => self::TYPE_INTEGER,
  26. 'int' => self::TYPE_INTEGER,
  27. 'integer' => self::TYPE_INTEGER,
  28. 'bigint' => self::TYPE_BIGINT,
  29. 'float' => self::TYPE_FLOAT,
  30. 'double' => self::TYPE_FLOAT,
  31. 'real' => self::TYPE_FLOAT,
  32. 'decimal' => self::TYPE_DECIMAL,
  33. 'numeric' => self::TYPE_DECIMAL,
  34. 'tinytext' => self::TYPE_TEXT,
  35. 'mediumtext' => self::TYPE_TEXT,
  36. 'longtext' => self::TYPE_TEXT,
  37. 'text' => self::TYPE_TEXT,
  38. 'varchar' => self::TYPE_STRING,
  39. 'string' => self::TYPE_STRING,
  40. 'char' => self::TYPE_STRING,
  41. 'datetime' => self::TYPE_DATETIME,
  42. 'year' => self::TYPE_DATE,
  43. 'date' => self::TYPE_DATE,
  44. 'time' => self::TYPE_TIME,
  45. 'timestamp' => self::TYPE_TIMESTAMP,
  46. 'enum' => self::TYPE_STRING,
  47. ];
  48. /**
  49. * Quotes a table name for use in a query.
  50. * A simple table name has no schema prefix.
  51. * @param string $name table name
  52. * @return string the properly quoted table name
  53. */
  54. public function quoteSimpleTableName($name)
  55. {
  56. return strpos($name, "`") !== false ? $name : "`" . $name . "`";
  57. }
  58. /**
  59. * Quotes a column name for use in a query.
  60. * A simple column name has no prefix.
  61. * @param string $name column name
  62. * @return string the properly quoted column name
  63. */
  64. public function quoteSimpleColumnName($name)
  65. {
  66. return strpos($name, '`') !== false || $name === '*' ? $name : '`' . $name . '`';
  67. }
  68. /**
  69. * Creates a query builder for the MySQL database.
  70. * This method may be overridden by child classes to create a DBMS-specific query builder.
  71. * @return QueryBuilder query builder instance
  72. */
  73. public function createQueryBuilder()
  74. {
  75. return new QueryBuilder($this->db);
  76. }
  77. /**
  78. * Returns all table names in the database.
  79. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  80. * @return array all table names in the database. The names have NO schema name prefix.
  81. */
  82. protected function findTableNames($schema = '')
  83. {
  84. $sql = "SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence'";
  85. return $this->db->createCommand($sql)->queryColumn();
  86. }
  87. /**
  88. * Loads the metadata for the specified table.
  89. * @param string $name table name
  90. * @return TableSchema driver dependent table metadata. Null if the table does not exist.
  91. */
  92. protected function loadTableSchema($name)
  93. {
  94. $table = new TableSchema;
  95. $table->name = $name;
  96. $table->fullName = $name;
  97. if ($this->findColumns($table)) {
  98. $this->findConstraints($table);
  99. return $table;
  100. } else {
  101. return null;
  102. }
  103. }
  104. /**
  105. * Collects the table column metadata.
  106. * @param TableSchema $table the table metadata
  107. * @return boolean whether the table exists in the database
  108. */
  109. protected function findColumns($table)
  110. {
  111. $sql = "PRAGMA table_info(" . $this->quoteSimpleTableName($table->name) . ')';
  112. $columns = $this->db->createCommand($sql)->queryAll();
  113. if (empty($columns)) {
  114. return false;
  115. }
  116. foreach ($columns as $info) {
  117. $column = $this->loadColumnSchema($info);
  118. $table->columns[$column->name] = $column;
  119. if ($column->isPrimaryKey) {
  120. $table->primaryKey[] = $column->name;
  121. }
  122. }
  123. if (count($table->primaryKey) === 1 && !strncasecmp($table->columns[$table->primaryKey[0]]->dbType, 'int', 3)) {
  124. $table->sequenceName = '';
  125. $table->columns[$table->primaryKey[0]]->autoIncrement = true;
  126. }
  127. return true;
  128. }
  129. /**
  130. * Collects the foreign key column details for the given table.
  131. * @param TableSchema $table the table metadata
  132. */
  133. protected function findConstraints($table)
  134. {
  135. $sql = "PRAGMA foreign_key_list(" . $this->quoteSimpleTableName($table->name) . ')';
  136. $keys = $this->db->createCommand($sql)->queryAll();
  137. foreach ($keys as $key) {
  138. $id = (int)$key['id'];
  139. if (!isset($table->foreignKeys[$id])) {
  140. $table->foreignKeys[$id] = [$key['table'], $key['from'] => $key['to']];
  141. } else {
  142. // composite FK
  143. $table->foreignKeys[$id][$key['from']] = $key['to'];
  144. }
  145. }
  146. }
  147. /**
  148. * Returns all unique indexes for the given table.
  149. * Each array element is of the following structure:
  150. *
  151. * ~~~
  152. * [
  153. * 'IndexName1' => ['col1' [, ...]],
  154. * 'IndexName2' => ['col2' [, ...]],
  155. * ]
  156. * ~~~
  157. *
  158. * @param TableSchema $table the table metadata
  159. * @return array all unique indexes for the given table.
  160. */
  161. public function findUniqueIndexes($table)
  162. {
  163. $sql = "PRAGMA index_list(" . $this->quoteSimpleTableName($table->name) . ')';
  164. $indexes = $this->db->createCommand($sql)->queryAll();
  165. $uniqueIndexes = [];
  166. foreach ($indexes as $index) {
  167. $indexName = $index['name'];
  168. $indexInfo = $this->db->createCommand("PRAGMA index_info(" . $this->quoteValue($index['name']) . ")")->queryAll();
  169. if ($index['unique']) {
  170. $uniqueIndexes[$indexName] = [];
  171. foreach ($indexInfo as $row) {
  172. $uniqueIndexes[$indexName][] = $row['name'];
  173. }
  174. }
  175. }
  176. return $uniqueIndexes;
  177. }
  178. /**
  179. * Loads the column information into a [[ColumnSchema]] object.
  180. * @param array $info column information
  181. * @return ColumnSchema the column schema object
  182. */
  183. protected function loadColumnSchema($info)
  184. {
  185. $column = new ColumnSchema;
  186. $column->name = $info['name'];
  187. $column->allowNull = !$info['notnull'];
  188. $column->isPrimaryKey = $info['pk'] != 0;
  189. $column->dbType = $info['type'];
  190. $column->unsigned = strpos($column->dbType, 'unsigned') !== false;
  191. $column->type = self::TYPE_STRING;
  192. if (preg_match('/^(\w+)(?:\(([^\)]+)\))?/', $column->dbType, $matches)) {
  193. $type = strtolower($matches[1]);
  194. if (isset($this->typeMap[$type])) {
  195. $column->type = $this->typeMap[$type];
  196. }
  197. if (!empty($matches[2])) {
  198. $values = explode(',', $matches[2]);
  199. $column->size = $column->precision = (int)$values[0];
  200. if (isset($values[1])) {
  201. $column->scale = (int)$values[1];
  202. }
  203. if ($column->size === 1 && ($type === 'tinyint' || $type === 'bit')) {
  204. $column->type = 'boolean';
  205. } elseif ($type === 'bit') {
  206. if ($column->size > 32) {
  207. $column->type = 'bigint';
  208. } elseif ($column->size === 32) {
  209. $column->type = 'integer';
  210. }
  211. }
  212. }
  213. }
  214. $column->phpType = $this->getColumnPhpType($column);
  215. $value = $info['dflt_value'];
  216. if ($column->type === 'string') {
  217. $column->defaultValue = trim($value, "'\"");
  218. } else {
  219. $column->defaultValue = $column->typecast(strcasecmp($value, 'null') ? $value : null);
  220. }
  221. return $column;
  222. }
  223. }