CSqliteSchema.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. <?php
  2. /**
  3. * CSqliteSchema class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright 2008-2013 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CSqliteSchema is the class for retrieving metadata information from a SQLite (2/3) database.
  12. *
  13. * @author Qiang Xue <qiang.xue@gmail.com>
  14. * @package system.db.schema.sqlite
  15. * @since 1.0
  16. */
  17. class CSqliteSchema extends CDbSchema
  18. {
  19. /**
  20. * @var array the abstract column types mapped to physical column types.
  21. * @since 1.1.6
  22. */
  23. public $columnTypes=array(
  24. 'pk' => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
  25. 'string' => 'varchar(255)',
  26. 'text' => 'text',
  27. 'integer' => 'integer',
  28. 'float' => 'float',
  29. 'decimal' => 'decimal',
  30. 'datetime' => 'datetime',
  31. 'timestamp' => 'timestamp',
  32. 'time' => 'time',
  33. 'date' => 'date',
  34. 'binary' => 'blob',
  35. 'boolean' => 'tinyint(1)',
  36. 'money' => 'decimal(19,4)',
  37. );
  38. /**
  39. * Resets the sequence value of a table's primary key.
  40. * The sequence will be reset such that the primary key of the next new row inserted
  41. * will have the specified value or max value of a primary key plus one (i.e. sequence trimming).
  42. * @param CDbTableSchema $table the table schema whose primary key sequence will be reset
  43. * @param integer|null $value the value for the primary key of the next new row inserted.
  44. * If this is not set, the next new row's primary key will have the max value of a primary
  45. * key plus one (i.e. sequence trimming).
  46. * @since 1.1
  47. */
  48. public function resetSequence($table,$value=null)
  49. {
  50. if($table->sequenceName===null)
  51. return;
  52. if($value!==null)
  53. $value=(int)($value)-1;
  54. else
  55. $value=(int)$this->getDbConnection()
  56. ->createCommand("SELECT MAX(`{$table->primaryKey}`) FROM {$table->rawName}")
  57. ->queryScalar();
  58. try
  59. {
  60. // it's possible that 'sqlite_sequence' does not exist
  61. $this->getDbConnection()
  62. ->createCommand("UPDATE sqlite_sequence SET seq='$value' WHERE name='{$table->name}'")
  63. ->execute();
  64. }
  65. catch(Exception $e)
  66. {
  67. }
  68. }
  69. /**
  70. * Enables or disables integrity check. Note that this method used to do nothing before 1.1.14. Since 1.1.14
  71. * it changes integrity check state as expected.
  72. * @param boolean $check whether to turn on or off the integrity check.
  73. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  74. * @since 1.1
  75. */
  76. public function checkIntegrity($check=true,$schema='')
  77. {
  78. $this->getDbConnection()->createCommand('PRAGMA foreign_keys='.(int)$check)->execute();
  79. }
  80. /**
  81. * Returns all table names in the database.
  82. * @param string $schema the schema of the tables. This is not used for sqlite database.
  83. * @return array all table names in the database.
  84. */
  85. protected function findTableNames($schema='')
  86. {
  87. $sql="SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence'";
  88. return $this->getDbConnection()->createCommand($sql)->queryColumn();
  89. }
  90. /**
  91. * Creates a command builder for the database.
  92. * @return CSqliteCommandBuilder command builder instance
  93. */
  94. protected function createCommandBuilder()
  95. {
  96. return new CSqliteCommandBuilder($this);
  97. }
  98. /**
  99. * Loads the metadata for the specified table.
  100. * @param string $name table name
  101. * @return CDbTableSchema driver dependent table metadata. Null if the table does not exist.
  102. */
  103. protected function loadTable($name)
  104. {
  105. $table=new CDbTableSchema;
  106. $table->name=$name;
  107. $table->rawName=$this->quoteTableName($name);
  108. if($this->findColumns($table))
  109. {
  110. $this->findConstraints($table);
  111. return $table;
  112. }
  113. else
  114. return null;
  115. }
  116. /**
  117. * Collects the table column metadata.
  118. * @param CDbTableSchema $table the table metadata
  119. * @return boolean whether the table exists in the database
  120. */
  121. protected function findColumns($table)
  122. {
  123. $sql="PRAGMA table_info({$table->rawName})";
  124. $columns=$this->getDbConnection()->createCommand($sql)->queryAll();
  125. if(empty($columns))
  126. return false;
  127. foreach($columns as $column)
  128. {
  129. $c=$this->createColumn($column);
  130. $table->columns[$c->name]=$c;
  131. if($c->isPrimaryKey)
  132. {
  133. if($table->primaryKey===null)
  134. $table->primaryKey=$c->name;
  135. elseif(is_string($table->primaryKey))
  136. $table->primaryKey=array($table->primaryKey,$c->name);
  137. else
  138. $table->primaryKey[]=$c->name;
  139. }
  140. }
  141. if(is_string($table->primaryKey) && !strncasecmp($table->columns[$table->primaryKey]->dbType,'int',3))
  142. {
  143. $table->sequenceName='';
  144. $table->columns[$table->primaryKey]->autoIncrement=true;
  145. }
  146. return true;
  147. }
  148. /**
  149. * Collects the foreign key column details for the given table.
  150. * @param CDbTableSchema $table the table metadata
  151. */
  152. protected function findConstraints($table)
  153. {
  154. $foreignKeys=array();
  155. $sql="PRAGMA foreign_key_list({$table->rawName})";
  156. $keys=$this->getDbConnection()->createCommand($sql)->queryAll();
  157. foreach($keys as $key)
  158. {
  159. $column=$table->columns[$key['from']];
  160. $column->isForeignKey=true;
  161. $foreignKeys[$key['from']]=array($key['table'],$key['to']);
  162. }
  163. $table->foreignKeys=$foreignKeys;
  164. }
  165. /**
  166. * Creates a table column.
  167. * @param array $column column metadata
  168. * @return CDbColumnSchema normalized column metadata
  169. */
  170. protected function createColumn($column)
  171. {
  172. $c=new CSqliteColumnSchema;
  173. $c->name=$column['name'];
  174. $c->rawName=$this->quoteColumnName($c->name);
  175. $c->allowNull=!$column['notnull'];
  176. $c->isPrimaryKey=$column['pk']!=0;
  177. $c->isForeignKey=false;
  178. $c->comment=null; // SQLite does not support column comments at all
  179. $c->init(strtolower($column['type']),$column['dflt_value']);
  180. return $c;
  181. }
  182. /**
  183. * Builds a SQL statement for renaming a DB table.
  184. * @param string $table the table to be renamed. The name will be properly quoted by the method.
  185. * @param string $newName the new table name. The name will be properly quoted by the method.
  186. * @return string the SQL statement for renaming a DB table.
  187. * @since 1.1.13
  188. */
  189. public function renameTable($table, $newName)
  190. {
  191. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' RENAME TO ' . $this->quoteTableName($newName);
  192. }
  193. /**
  194. * Builds a SQL statement for truncating a DB table.
  195. * @param string $table the table to be truncated. The name will be properly quoted by the method.
  196. * @return string the SQL statement for truncating a DB table.
  197. * @since 1.1.6
  198. */
  199. public function truncateTable($table)
  200. {
  201. return "DELETE FROM ".$this->quoteTableName($table);
  202. }
  203. /**
  204. * Builds a SQL statement for dropping a DB column.
  205. * Because SQLite does not support dropping a DB column, calling this method will throw an exception.
  206. * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
  207. * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
  208. * @return string the SQL statement for dropping a DB column.
  209. * @since 1.1.6
  210. */
  211. public function dropColumn($table, $column)
  212. {
  213. throw new CDbException(Yii::t('yii', 'Dropping DB column is not supported by SQLite.'));
  214. }
  215. /**
  216. * Builds a SQL statement for renaming a column.
  217. * Because SQLite does not support renaming a DB column, calling this method will throw an exception.
  218. * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
  219. * @param string $name the old name of the column. The name will be properly quoted by the method.
  220. * @param string $newName the new name of the column. The name will be properly quoted by the method.
  221. * @return string the SQL statement for renaming a DB column.
  222. * @since 1.1.6
  223. */
  224. public function renameColumn($table, $name, $newName)
  225. {
  226. throw new CDbException(Yii::t('yii', 'Renaming a DB column is not supported by SQLite.'));
  227. }
  228. /**
  229. * Builds a SQL statement for adding a foreign key constraint to an existing table.
  230. * Because SQLite does not support adding foreign key to an existing table, calling this method will throw an exception.
  231. * @param string $name the name of the foreign key constraint.
  232. * @param string $table the table that the foreign key constraint will be added to.
  233. * @param string $columns the name of the column to that the constraint will be added on. If there are multiple columns, separate them with commas.
  234. * @param string $refTable the table that the foreign key references to.
  235. * @param string $refColumns the name of the column that the foreign key references to. If there are multiple columns, separate them with commas.
  236. * @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
  237. * @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
  238. * @return string the SQL statement for adding a foreign key constraint to an existing table.
  239. * @since 1.1.6
  240. */
  241. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  242. {
  243. throw new CDbException(Yii::t('yii', 'Adding a foreign key constraint to an existing table is not supported by SQLite.'));
  244. }
  245. /**
  246. * Builds a SQL statement for dropping a foreign key constraint.
  247. * Because SQLite does not support dropping a foreign key constraint, calling this method will throw an exception.
  248. * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
  249. * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
  250. * @return string the SQL statement for dropping a foreign key constraint.
  251. * @since 1.1.6
  252. */
  253. public function dropForeignKey($name, $table)
  254. {
  255. throw new CDbException(Yii::t('yii', 'Dropping a foreign key constraint is not supported by SQLite.'));
  256. }
  257. /**
  258. * Builds a SQL statement for changing the definition of a column.
  259. * Because SQLite does not support altering a DB column, calling this method will throw an exception.
  260. * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
  261. * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
  262. * @param string $type the new column type. The {@link getColumnType} method will be invoked to convert abstract column type (if any)
  263. * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
  264. * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
  265. * @return string the SQL statement for changing the definition of a column.
  266. * @since 1.1.6
  267. */
  268. public function alterColumn($table, $column, $type)
  269. {
  270. throw new CDbException(Yii::t('yii', 'Altering a DB column is not supported by SQLite.'));
  271. }
  272. /**
  273. * Builds a SQL statement for dropping an index.
  274. * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
  275. * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
  276. * @return string the SQL statement for dropping an index.
  277. * @since 1.1.6
  278. */
  279. public function dropIndex($name, $table)
  280. {
  281. return 'DROP INDEX '.$this->quoteTableName($name);
  282. }
  283. /**
  284. * Builds a SQL statement for adding a primary key constraint to an existing table.
  285. * Because SQLite does not support adding a primary key on an existing table this method will throw an exception.
  286. * @param string $name the name of the primary key constraint.
  287. * @param string $table the table that the primary key constraint will be added to.
  288. * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
  289. * @return string the SQL statement for adding a primary key constraint to an existing table.
  290. * @since 1.1.13
  291. */
  292. public function addPrimaryKey($name,$table,$columns)
  293. {
  294. throw new CDbException(Yii::t('yii', 'Adding a primary key after table has been created is not supported by SQLite.'));
  295. }
  296. /**
  297. * Builds a SQL statement for removing a primary key constraint to an existing table.
  298. * Because SQLite does not support dropping a primary key from an existing table this method will throw an exception
  299. * @param string $name the name of the primary key constraint to be removed.
  300. * @param string $table the table that the primary key constraint will be removed from.
  301. * @return string the SQL statement for removing a primary key constraint from an existing table.
  302. * @since 1.1.13
  303. */
  304. public function dropPrimaryKey($name,$table)
  305. {
  306. throw new CDbException(Yii::t('yii', 'Removing a primary key after table has been created is not supported by SQLite.'));
  307. }
  308. }