CSqliteSchema.php 13 KB

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