1<?php
2/**
3 * CDbSchema 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 * CDbSchema is the base class for retrieving metadata information.
13 *
14 * @property CDbConnection $dbConnection Database connection. The connection is active.
15 * @property array $tables The metadata for all tables in the database.
16 * Each array element is an instance of {@link CDbTableSchema} (or its child class).
17 * The array keys are table names.
18 * @property array $tableNames All table names in the database.
19 * @property CDbCommandBuilder $commandBuilder The SQL command builder for this connection.
20 *
21 * @author Qiang Xue <qiang.xue@gmail.com>
22 * @package system.db.schema
23 * @since 1.0
24 */
25abstract class CDbSchema extends CComponent
26{
27	/**
28	 * @var array the abstract column types mapped to physical column types.
29	 * @since 1.1.6
30	 */
31	public $columnTypes=array();
32
33	private $_tableNames=array();
34	private $_tables=array();
35	private $_connection;
36	private $_builder;
37	private $_cacheExclude=array();
38
39	/**
40	 * Loads the metadata for the specified table.
41	 * @param string $name table name
42	 * @return CDbTableSchema driver dependent table metadata, null if the table does not exist.
43	 */
44	abstract protected function loadTable($name);
45
46	/**
47	 * Constructor.
48	 * @param CDbConnection $conn database connection.
49	 */
50	public function __construct($conn)
51	{
52		$this->_connection=$conn;
53		foreach($conn->schemaCachingExclude as $name)
54			$this->_cacheExclude[$name]=true;
55	}
56
57	/**
58	 * @return CDbConnection database connection. The connection is active.
59	 */
60	public function getDbConnection()
61	{
62		return $this->_connection;
63	}
64
65	/**
66	 * Obtains the metadata for the named table.
67	 * @param string $name table name
68	 * @param boolean $refresh if we need to refresh schema cache for a table.
69	 * Parameter available since 1.1.9
70	 * @return CDbTableSchema table metadata. Null if the named table does not exist.
71	 */
72	public function getTable($name,$refresh=false)
73	{
74		if($refresh===false && isset($this->_tables[$name]))
75			return $this->_tables[$name];
76		else
77		{
78			if($this->_connection->tablePrefix!==null && strpos($name,'{{')!==false)
79				$realName=preg_replace('/\{\{(.*?)\}\}/',$this->_connection->tablePrefix.'$1',$name);
80			else
81				$realName=$name;
82
83			// temporarily disable query caching
84			if($this->_connection->queryCachingDuration>0)
85			{
86				$qcDuration=$this->_connection->queryCachingDuration;
87				$this->_connection->queryCachingDuration=0;
88			}
89
90			if(!isset($this->_cacheExclude[$name]) && ($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
91			{
92				$key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
93				$table=$cache->get($key);
94				if($refresh===true || $table===false)
95				{
96					$table=$this->loadTable($realName);
97					if($table!==null)
98						$cache->set($key,$table,$duration);
99				}
100				$this->_tables[$name]=$table;
101			}
102			else
103				$this->_tables[$name]=$table=$this->loadTable($realName);
104
105			if(isset($qcDuration))  // re-enable query caching
106				$this->_connection->queryCachingDuration=$qcDuration;
107
108			return $table;
109		}
110	}
111
112	/**
113	 * Returns the metadata for all tables in the database.
114	 * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
115	 * @return array the metadata for all tables in the database.
116	 * Each array element is an instance of {@link CDbTableSchema} (or its child class).
117	 * The array keys are table names.
118	 */
119	public function getTables($schema='')
120	{
121		$tables=array();
122		foreach($this->getTableNames($schema) as $name)
123		{
124			if(($table=$this->getTable($name))!==null)
125				$tables[$name]=$table;
126		}
127		return $tables;
128	}
129
130	/**
131	 * Returns all table names in the database.
132	 * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
133	 * If not empty, the returned table names will be prefixed with the schema name.
134	 * @return array all table names in the database.
135	 */
136	public function getTableNames($schema='')
137	{
138		if(!isset($this->_tableNames[$schema]))
139			$this->_tableNames[$schema]=$this->findTableNames($schema);
140		return $this->_tableNames[$schema];
141	}
142
143	/**
144	 * @return CDbCommandBuilder the SQL command builder for this connection.
145	 */
146	public function getCommandBuilder()
147	{
148		if($this->_builder!==null)
149			return $this->_builder;
150		else
151			return $this->_builder=$this->createCommandBuilder();
152	}
153
154	/**
155	 * Refreshes the schema.
156	 * This method resets the loaded table metadata and command builder
157	 * so that they can be recreated to reflect the change of schema.
158	 */
159	public function refresh()
160	{
161		if(($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
162		{
163			foreach(array_keys($this->_tables) as $name)
164			{
165				if(!isset($this->_cacheExclude[$name]))
166				{
167					$key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
168					$cache->delete($key);
169				}
170			}
171		}
172		$this->_tables=array();
173		$this->_tableNames=array();
174		$this->_builder=null;
175	}
176
177	/**
178	 * Quotes a table name for use in a query.
179	 * If the table name contains schema prefix, the prefix will also be properly quoted.
180	 * @param string $name table name
181	 * @return string the properly quoted table name
182	 * @see quoteSimpleTableName
183	 */
184	public function quoteTableName($name)
185	{
186		if(strpos($name,'.')===false)
187			return $this->quoteSimpleTableName($name);
188		$parts=explode('.',$name);
189		foreach($parts as $i=>$part)
190			$parts[$i]=$this->quoteSimpleTableName($part);
191		return implode('.',$parts);
192
193	}
194
195	/**
196	 * Quotes a simple table name for use in a query.
197	 * A simple table name does not schema prefix.
198	 * @param string $name table name
199	 * @return string the properly quoted table name
200	 * @since 1.1.6
201	 */
202	public function quoteSimpleTableName($name)
203	{
204		return "'".$name."'";
205	}
206
207	/**
208	 * Quotes a column name for use in a query.
209	 * If the column name contains prefix, the prefix will also be properly quoted.
210	 * @param string $name column name
211	 * @return string the properly quoted column name
212	 * @see quoteSimpleColumnName
213	 */
214	public function quoteColumnName($name)
215	{
216		if(($pos=strrpos($name,'.'))!==false)
217		{
218			$prefix=$this->quoteTableName(substr($name,0,$pos)).'.';
219			$name=substr($name,$pos+1);
220		}
221		else
222			$prefix='';
223		return $prefix . ($name==='*' ? $name : $this->quoteSimpleColumnName($name));
224	}
225
226	/**
227	 * Quotes a simple column name for use in a query.
228	 * A simple column name does not contain prefix.
229	 * @param string $name column name
230	 * @return string the properly quoted column name
231	 * @since 1.1.6
232	 */
233	public function quoteSimpleColumnName($name)
234	{
235		return '"'.$name.'"';
236	}
237
238	/**
239	 * Compares two table names.
240	 * The table names can be either quoted or unquoted. This method
241	 * will consider both cases.
242	 * @param string $name1 table name 1
243	 * @param string $name2 table name 2
244	 * @return boolean whether the two table names refer to the same table.
245	 */
246	public function compareTableNames($name1,$name2)
247	{
248		$name1=str_replace(array('"','`',"'"),'',$name1);
249		$name2=str_replace(array('"','`',"'"),'',$name2);
250		if(($pos=strrpos($name1,'.'))!==false)
251			$name1=substr($name1,$pos+1);
252		if(($pos=strrpos($name2,'.'))!==false)
253			$name2=substr($name2,$pos+1);
254		if($this->_connection->tablePrefix!==null)
255		{
256			if(strpos($name1,'{')!==false)
257				$name1=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name1);
258			if(strpos($name2,'{')!==false)
259				$name2=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name2);
260		}
261		return $name1===$name2;
262	}
263
264	/**
265	 * Resets the sequence value of a table's primary key.
266	 * The sequence will be reset such that the primary key of the next new row inserted
267	 * will have the specified value or max value of a primary key plus one (i.e. sequence trimming).
268	 * @param CDbTableSchema $table the table schema whose primary key sequence will be reset
269	 * @param integer|null $value the value for the primary key of the next new row inserted.
270	 * If this is not set, the next new row's primary key will have the max value of a primary
271	 * key plus one (i.e. sequence trimming).
272	 * @since 1.1
273	 */
274	public function resetSequence($table,$value=null)
275	{
276	}
277
278	/**
279	 * Enables or disables integrity check.
280	 * @param boolean $check whether to turn on or off the integrity check.
281	 * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
282	 * @since 1.1
283	 */
284	public function checkIntegrity($check=true,$schema='')
285	{
286	}
287
288	/**
289	 * Creates a command builder for the database.
290	 * This method may be overridden by child classes to create a DBMS-specific command builder.
291	 * @return CDbCommandBuilder command builder instance
292	 */
293	protected function createCommandBuilder()
294	{
295		return new CDbCommandBuilder($this);
296	}
297
298	/**
299	 * Returns all table names in the database.
300	 * This method should be overridden by child classes in order to support this feature
301	 * because the default implementation simply throws an exception.
302	 * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
303	 * If not empty, the returned table names will be prefixed with the schema name.
304	 * @throws CDbException if current schema does not support fetching all table names
305	 * @return array all table names in the database.
306	 */
307	protected function findTableNames($schema='')
308	{
309		throw new CDbException(Yii::t('yii','{class} does not support fetching all table names.',
310			array('{class}'=>get_class($this))));
311	}
312
313	/**
314	 * Converts an abstract column type into a physical column type.
315	 * The conversion is done using the type map specified in {@link columnTypes}.
316	 * These abstract column types are supported (using MySQL as example to explain the corresponding
317	 * physical types):
318	 * <ul>
319	 * <li>pk and bigpk: an auto-incremental primary key type, will be converted into "int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY" or "bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY"</li>
320	 * <li>string: string type, will be converted into "varchar(255)"</li>
321	 * <li>text: a long string type, will be converted into "text"</li>
322	 * <li>integer: integer type, will be converted into "int(11)"</li>
323	 * <li>bigint: integer type, will be converted into "bigint(20)"</li>
324	 * <li>boolean: boolean type, will be converted into "tinyint(1)"</li>
325	 * <li>float: float number type, will be converted into "float"</li>
326	 * <li>decimal: decimal number type, will be converted into "decimal"</li>
327	 * <li>datetime: datetime type, will be converted into "datetime"</li>
328	 * <li>timestamp: timestamp type, will be converted into "timestamp"</li>
329	 * <li>time: time type, will be converted into "time"</li>
330	 * <li>date: date type, will be converted into "date"</li>
331	 * <li>binary: binary data type, will be converted into "blob"</li>
332	 * </ul>
333	 *
334	 * If the abstract type contains two or more parts separated by spaces (e.g. "string NOT NULL"), then only
335	 * the first part will be converted, and the rest of the parts will be appended to the conversion result.
336	 * For example, 'string NOT NULL' is converted to 'varchar(255) NOT NULL'.
337	 * @param string $type abstract column type
338	 * @return string physical column type.
339	 * @since 1.1.6
340	 */
341	public function getColumnType($type)
342	{
343		if(isset($this->columnTypes[$type]))
344			return $this->columnTypes[$type];
345		elseif(($pos=strpos($type,' '))!==false)
346		{
347			$t=substr($type,0,$pos);
348			return (isset($this->columnTypes[$t]) ? $this->columnTypes[$t] : $t).substr($type,$pos);
349		}
350		else
351			return $type;
352	}
353
354	/**
355	 * Builds a SQL statement for creating a new DB table.
356	 *
357	 * The columns in the new  table should be specified as name-definition pairs (e.g. 'name'=>'string'),
358	 * where name stands for a column name which will be properly quoted by the method, and definition
359	 * stands for the column type which can contain an abstract DB type.
360	 * The {@link getColumnType} method will be invoked to convert any abstract type into a physical one.
361	 *
362	 * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
363	 * inserted into the generated SQL.
364	 *
365	 * @param string $table the name of the table to be created. The name will be properly quoted by the method.
366	 * @param array $columns the columns (name=>definition) in the new table.
367	 * @param string $options additional SQL fragment that will be appended to the generated SQL.
368	 * @return string the SQL statement for creating a new DB table.
369	 * @since 1.1.6
370	 */
371	public function createTable($table,$columns,$options=null)
372	{
373		$cols=array();
374		foreach($columns as $name=>$type)
375		{
376			if(is_string($name))
377				$cols[]="\t".$this->quoteColumnName($name).' '.$this->getColumnType($type);
378			else
379				$cols[]="\t".$type;
380		}
381		$sql="CREATE TABLE ".$this->quoteTableName($table)." (\n".implode(",\n",$cols)."\n)";
382		return $options===null ? $sql : $sql.' '.$options;
383	}
384
385	/**
386	 * Builds a SQL statement for renaming a DB table.
387	 * @param string $table the table to be renamed. The name will be properly quoted by the method.
388	 * @param string $newName the new table name. The name will be properly quoted by the method.
389	 * @return string the SQL statement for renaming a DB table.
390	 * @since 1.1.6
391	 */
392	public function renameTable($table,$newName)
393	{
394		return 'RENAME TABLE ' . $this->quoteTableName($table) . ' TO ' . $this->quoteTableName($newName);
395	}
396
397	/**
398	 * Builds a SQL statement for dropping a DB table.
399	 * @param string $table the table to be dropped. The name will be properly quoted by the method.
400	 * @return string the SQL statement for dropping a DB table.
401	 * @since 1.1.6
402	 */
403	public function dropTable($table)
404	{
405		return "DROP TABLE ".$this->quoteTableName($table);
406	}
407
408	/**
409	 * Builds a SQL statement for truncating a DB table.
410	 * @param string $table the table to be truncated. The name will be properly quoted by the method.
411	 * @return string the SQL statement for truncating a DB table.
412	 * @since 1.1.6
413	 */
414	public function truncateTable($table)
415	{
416		return "TRUNCATE TABLE ".$this->quoteTableName($table);
417	}
418
419	/**
420	 * Builds a SQL statement for adding a new DB column.
421	 * @param string $table the table that the new column will be added to. The table name will be properly quoted by the method.
422	 * @param string $column the name of the new column. The name will be properly quoted by the method.
423	 * @param string $type the column type. The {@link getColumnType} method will be invoked to convert abstract column type (if any)
424	 * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
425	 * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
426	 * @return string the SQL statement for adding a new column.
427	 * @since 1.1.6
428	 */
429	public function addColumn($table,$column,$type)
430	{
431		return 'ALTER TABLE ' . $this->quoteTableName($table)
432			. ' ADD ' . $this->quoteColumnName($column) . ' '
433			. $this->getColumnType($type);
434	}
435
436	/**
437	 * Builds a SQL statement for dropping a DB column.
438	 * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
439	 * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
440	 * @return string the SQL statement for dropping a DB column.
441	 * @since 1.1.6
442	 */
443	public function dropColumn($table,$column)
444	{
445		return "ALTER TABLE ".$this->quoteTableName($table)
446			." DROP COLUMN ".$this->quoteColumnName($column);
447	}
448
449	/**
450	 * Builds a SQL statement for renaming a column.
451	 * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
452	 * @param string $name the old name of the column. The name will be properly quoted by the method.
453	 * @param string $newName the new name of the column. The name will be properly quoted by the method.
454	 * @return string the SQL statement for renaming a DB column.
455	 * @since 1.1.6
456	 */
457	public function renameColumn($table,$name,$newName)
458	{
459		return "ALTER TABLE ".$this->quoteTableName($table)
460			. " RENAME COLUMN ".$this->quoteColumnName($name)
461			. " TO ".$this->quoteColumnName($newName);
462	}
463
464	/**
465	 * Builds a SQL statement for changing the definition of a column.
466	 * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
467	 * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
468	 * @param string $type the new column type. The {@link getColumnType} method will be invoked to convert abstract column type (if any)
469	 * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
470	 * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
471	 * @return string the SQL statement for changing the definition of a column.
472	 * @since 1.1.6
473	 */
474	public function alterColumn($table,$column,$type)
475	{
476		return 'ALTER TABLE ' . $this->quoteTableName($table) . ' CHANGE '
477			. $this->quoteColumnName($column) . ' '
478			. $this->quoteColumnName($column) . ' '
479			. $this->getColumnType($type);
480	}
481
482	/**
483	 * Builds a SQL statement for adding a foreign key constraint to an existing table.
484	 * The method will properly quote the table and column names.
485	 * @param string $name the name of the foreign key constraint.
486	 * @param string $table the table that the foreign key constraint will be added to.
487	 * @param string|array $columns the name of the column to that the constraint will be added on. If there are multiple columns, separate them with commas or pass as an array of column names.
488	 * @param string $refTable the table that the foreign key references to.
489	 * @param string|array $refColumns the name of the column that the foreign key references to. If there are multiple columns, separate them with commas or pass as an array of column names.
490	 * @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
491	 * @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
492	 * @return string the SQL statement for adding a foreign key constraint to an existing table.
493	 * @since 1.1.6
494	 */
495	public function addForeignKey($name,$table,$columns,$refTable,$refColumns,$delete=null,$update=null)
496	{
497		if(is_string($columns))
498			$columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
499		foreach($columns as $i=>$col)
500			$columns[$i]=$this->quoteColumnName($col);
501		if(is_string($refColumns))
502			$refColumns=preg_split('/\s*,\s*/',$refColumns,-1,PREG_SPLIT_NO_EMPTY);
503		foreach($refColumns as $i=>$col)
504			$refColumns[$i]=$this->quoteColumnName($col);
505		$sql='ALTER TABLE '.$this->quoteTableName($table)
506			.' ADD CONSTRAINT '.$this->quoteColumnName($name)
507			.' FOREIGN KEY ('.implode(', ',$columns).')'
508			.' REFERENCES '.$this->quoteTableName($refTable)
509			.' ('.implode(', ',$refColumns).')';
510		if($delete!==null)
511			$sql.=' ON DELETE '.$delete;
512		if($update!==null)
513			$sql.=' ON UPDATE '.$update;
514		return $sql;
515	}
516
517	/**
518	 * Builds a SQL statement for dropping a foreign key constraint.
519	 * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
520	 * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
521	 * @return string the SQL statement for dropping a foreign key constraint.
522	 * @since 1.1.6
523	 */
524	public function dropForeignKey($name,$table)
525	{
526		return 'ALTER TABLE '.$this->quoteTableName($table)
527			.' DROP CONSTRAINT '.$this->quoteColumnName($name);
528	}
529
530	/**
531	 * Builds a SQL statement for creating a new index.
532	 * @param string $name the name of the index. The name will be properly quoted by the method.
533	 * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
534	 * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns, please separate them
535	 * by commas or pass as an array of column names. Each column name will be properly quoted by the method, unless a parenthesis is found in the name.
536	 * @param boolean $unique whether to add UNIQUE constraint on the created index.
537	 * @return string the SQL statement for creating a new index.
538	 * @since 1.1.6
539	 */
540	public function createIndex($name,$table,$columns,$unique=false)
541	{
542		$cols=array();
543		if(is_string($columns))
544			$columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
545		foreach($columns as $col)
546		{
547			if(strpos($col,'(')!==false)
548				$cols[]=$col;
549			else
550				$cols[]=$this->quoteColumnName($col);
551		}
552		return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
553			. $this->quoteTableName($name).' ON '
554			. $this->quoteTableName($table).' ('.implode(', ',$cols).')';
555	}
556
557	/**
558	 * Builds a SQL statement for dropping an index.
559	 * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
560	 * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
561	 * @return string the SQL statement for dropping an index.
562	 * @since 1.1.6
563	 */
564	public function dropIndex($name,$table)
565	{
566		return 'DROP INDEX '.$this->quoteTableName($name).' ON '.$this->quoteTableName($table);
567	}
568
569	/**
570	 * Builds a SQL statement for adding a primary key constraint to an existing table.
571	 * @param string $name the name of the primary key constraint.
572	 * @param string $table the table that the primary key constraint will be added to.
573	 * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
574	 * Array value can be passed since 1.1.14.
575	 * @return string the SQL statement for adding a primary key constraint to an existing table.
576	 * @since 1.1.13
577	 */
578	public function addPrimaryKey($name,$table,$columns)
579	{
580		if(is_string($columns))
581			$columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
582		foreach($columns as $i=>$col)
583			$columns[$i]=$this->quoteColumnName($col);
584		return 'ALTER TABLE ' . $this->quoteTableName($table) . ' ADD CONSTRAINT '
585			. $this->quoteColumnName($name) . '  PRIMARY KEY ('
586			. implode(', ',$columns). ' )';
587	}
588
589	/**
590	 * Builds a SQL statement for removing a primary key constraint to an existing table.
591	 * @param string $name the name of the primary key constraint to be removed.
592	 * @param string $table the table that the primary key constraint will be removed from.
593	 * @return string the SQL statement for removing a primary key constraint from an existing table.
594	 * @since 1.1.13
595	 */
596	public function dropPrimaryKey($name,$table)
597	{
598		return 'ALTER TABLE ' . $this->quoteTableName($table) . ' DROP CONSTRAINT '
599			. $this->quoteColumnName($name);
600	}
601}
602