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