Connection.php 18.6 KB
Newer Older
w  
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
w  
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

Qiang Xue committed
8
namespace yii\db;
w  
Qiang Xue committed
9

Qiang Xue committed
10 11
use PDO;
use Yii;
12
use yii\base\Component;
Qiang Xue committed
13 14
use yii\base\InvalidConfigException;
use yii\base\NotSupportedException;
15
use yii\caching\Cache;
w  
Qiang Xue committed
16

w  
Qiang Xue committed
17
/**
w  
Qiang Xue committed
18
 * Connection represents a connection to a database via [PDO](http://www.php.net/manual/en/ref.pdo.php).
w  
Qiang Xue committed
19
 *
w  
Qiang Xue committed
20 21 22
 * Connection works together with [[Command]], [[DataReader]] and [[Transaction]]
 * to provide data access to various DBMS in a common set of APIs. They are a thin wrapper
 * of the [[PDO PHP extension]](http://www.php.net/manual/en/ref.pdo.php).
w  
Qiang Xue committed
23
 *
w  
Qiang Xue committed
24
 * To establish a DB connection, set [[dsn]], [[username]] and [[password]], and then
25
 * call [[open()]] to be true.
w  
Qiang Xue committed
26 27
 *
 * The following example shows how to create a Connection instance and establish
w  
Qiang Xue committed
28
 * the DB connection:
w  
Qiang Xue committed
29
 *
w  
Qiang Xue committed
30
 * ~~~
Alexander Makarov committed
31
 * $connection = new \yii\db\Connection([
Qiang Xue committed
32 33 34
 *     'dsn' => $dsn,
 *     'username' => $username,
 *     'password' => $password,
Alexander Makarov committed
35
 * ]);
36
 * $connection->open();
w  
Qiang Xue committed
37 38
 * ~~~
 *
Qiang Xue committed
39
 * After the DB connection is established, one can execute SQL statements like the following:
w  
Qiang Xue committed
40 41 42
 *
 * ~~~
 * $command = $connection->createCommand('SELECT * FROM tbl_post');
Qiang Xue committed
43 44 45
 * $posts = $command->queryAll();
 * $command = $connection->createCommand('UPDATE tbl_post SET status=1');
 * $command->execute();
w  
Qiang Xue committed
46 47
 * ~~~
 *
Qiang Xue committed
48 49 50
 * One can also do prepared SQL execution and bind parameters to the prepared SQL.
 * When the parameters are coming from user input, you should use this approach
 * to prevent SQL injection attacks. The following is an example:
w  
Qiang Xue committed
51
 *
w  
Qiang Xue committed
52 53 54 55 56
 * ~~~
 * $command = $connection->createCommand('SELECT * FROM tbl_post WHERE id=:id');
 * $command->bindValue(':id', $_GET['id']);
 * $post = $command->query();
 * ~~~
w  
Qiang Xue committed
57
 *
Qiang Xue committed
58 59 60 61
 * For more information about how to perform various DB queries, please refer to [[Command]].
 *
 * If the underlying DBMS supports transactions, you can perform transactional SQL queries
 * like the following:
w  
Qiang Xue committed
62
 *
w  
Qiang Xue committed
63 64 65
 * ~~~
 * $transaction = $connection->beginTransaction();
 * try {
66 67 68 69
 *     $connection->createCommand($sql1)->execute();
 *     $connection->createCommand($sql2)->execute();
 *     // ... executing other SQL statements ...
 *     $transaction->commit();
Qiang Xue committed
70
 * } catch(Exception $e) {
71
 *     $transaction->rollBack();
w  
Qiang Xue committed
72
 * }
w  
Qiang Xue committed
73
 * ~~~
w  
Qiang Xue committed
74
 *
75
 * Connection is often used as an application component and configured in the application
Qiang Xue committed
76
 * configuration like the following:
w  
Qiang Xue committed
77 78
 *
 * ~~~
Alexander Makarov committed
79 80 81
 * [
 *	 'components' => [
 *		 'db' => [
Qiang Xue committed
82
 *			 'class' => '\yii\db\Connection',
Qiang Xue committed
83 84 85 86
 *			 'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
 *			 'username' => 'root',
 *			 'password' => '',
 *			 'charset' => 'utf8',
Alexander Makarov committed
87 88 89
 *		 ],
 *	 ],
 * ]
w  
Qiang Xue committed
90
 * ~~~
w  
Qiang Xue committed
91
 *
92
 * @property string $driverName Name of the DB driver. This property is read-only.
93
 * @property boolean $isActive Whether the DB connection is established. This property is read-only.
94 95 96 97 98 99 100 101
 * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the
 * sequence object. This property is read-only.
 * @property QueryBuilder $queryBuilder The query builder for the current DB connection. This property is
 * read-only.
 * @property Schema $schema The schema information for the database opened by this connection. This property
 * is read-only.
 * @property Transaction $transaction The currently active transaction. Null if no active transaction. This
 * property is read-only.
Qiang Xue committed
102
 *
w  
Qiang Xue committed
103 104 105
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
106
class Connection extends Component
w  
Qiang Xue committed
107
{
108 109 110 111 112
	/**
	 * @event Event an event that is triggered after a DB connection is established
	 */
	const EVENT_AFTER_OPEN = 'afterOpen';

w  
Qiang Xue committed
113
	/**
w  
Qiang Xue committed
114 115 116
	 * @var string the Data Source Name, or DSN, contains the information required to connect to the database.
	 * Please refer to the [PHP manual](http://www.php.net/manual/en/function.PDO-construct.php) on
	 * the format of the DSN string.
Qiang Xue committed
117
	 * @see charset
w  
Qiang Xue committed
118 119 120
	 */
	public $dsn;
	/**
121
	 * @var string the username for establishing DB connection. Defaults to `null` meaning no username to use.
w  
Qiang Xue committed
122
	 */
123
	public $username;
w  
Qiang Xue committed
124
	/**
125
	 * @var string the password for establishing DB connection. Defaults to `null` meaning no password to use.
w  
Qiang Xue committed
126
	 */
127
	public $password;
w  
Qiang Xue committed
128
	/**
resurtm committed
129
	 * @var array PDO attributes (name => value) that should be set when calling [[open()]]
w  
Qiang Xue committed
130 131 132 133 134 135
	 * to establish a DB connection. Please refer to the
	 * [PHP manual](http://www.php.net/manual/en/function.PDO-setAttribute.php) for
	 * details about available attributes.
	 */
	public $attributes;
	/**
Qiang Xue committed
136
	 * @var PDO the PHP PDO instance associated with this DB connection.
137
	 * This property is mainly managed by [[open()]] and [[close()]] methods.
w  
Qiang Xue committed
138 139 140 141
	 * When a DB connection is active, this property will represent a PDO instance;
	 * otherwise, it will be null.
	 */
	public $pdo;
142 143 144
	/**
	 * @var boolean whether to enable schema caching.
	 * Note that in order to enable truly schema caching, a valid cache component as specified
145
	 * by [[schemaCache]] must be enabled and [[enableSchemaCache]] must be set true.
146 147
	 * @see schemaCacheDuration
	 * @see schemaCacheExclude
148
	 * @see schemaCache
149 150
	 */
	public $enableSchemaCache = false;
w  
Qiang Xue committed
151 152
	/**
	 * @var integer number of seconds that table metadata can remain valid in cache.
w  
Qiang Xue committed
153
	 * Use 0 to indicate that the cached data will never expire.
154
	 * @see enableSchemaCache
w  
Qiang Xue committed
155
	 */
156
	public $schemaCacheDuration = 3600;
w  
Qiang Xue committed
157 158
	/**
	 * @var array list of tables whose metadata should NOT be cached. Defaults to empty array.
Qiang Xue committed
159
	 * The table names may contain schema prefix, if any. Do not quote the table names.
160
	 * @see enableSchemaCache
w  
Qiang Xue committed
161
	 */
Alexander Makarov committed
162
	public $schemaCacheExclude = [];
w  
Qiang Xue committed
163
	/**
164 165
	 * @var Cache|string the cache object or the ID of the cache application component that
	 * is used to cache the table metadata.
166
	 * @see enableSchemaCache
w  
Qiang Xue committed
167
	 */
168
	public $schemaCache = 'cache';
w  
Qiang Xue committed
169
	/**
170
	 * @var boolean whether to enable query caching.
w  
Qiang Xue committed
171
	 * Note that in order to enable query caching, a valid cache component as specified
172
	 * by [[queryCache]] must be enabled and [[enableQueryCache]] must be set true.
w  
Qiang Xue committed
173
	 *
174 175 176
	 * Methods [[beginCache()]] and [[endCache()]] can be used as shortcuts to turn on
	 * and off query caching on the fly.
	 * @see queryCacheDuration
177
	 * @see queryCache
178 179 180
	 * @see queryCacheDependency
	 * @see beginCache()
	 * @see endCache()
w  
Qiang Xue committed
181
	 */
182
	public $enableQueryCache = false;
w  
Qiang Xue committed
183
	/**
184
	 * @var integer number of seconds that query results can remain valid in cache.
185
	 * Defaults to 3600, meaning 3600 seconds, or one hour.
186 187
	 * Use 0 to indicate that the cached data will never expire.
	 * @see enableQueryCache
w  
Qiang Xue committed
188
	 */
189
	public $queryCacheDuration = 3600;
w  
Qiang Xue committed
190
	/**
191 192 193
	 * @var \yii\caching\Dependency the dependency that will be used when saving query results into cache.
	 * Defaults to null, meaning no dependency.
	 * @see enableQueryCache
w  
Qiang Xue committed
194
	 */
195
	public $queryCacheDependency;
w  
Qiang Xue committed
196
	/**
197 198
	 * @var Cache|string the cache object or the ID of the cache application component
	 * that is used for query caching.
199
	 * @see enableQueryCache
w  
Qiang Xue committed
200
	 */
201
	public $queryCache = 'cache';
w  
Qiang Xue committed
202 203
	/**
	 * @var string the charset used for database connection. The property is only used
204
	 * for MySQL, PostgreSQL and CUBRID databases. Defaults to null, meaning using default charset
w  
Qiang Xue committed
205 206 207
	 * as specified by the database.
	 *
	 * Note that if you're using GBK or BIG5 then it's highly recommended to
208
	 * specify charset via DSN like 'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'.
w  
Qiang Xue committed
209 210 211 212 213 214
	 */
	public $charset;
	/**
	 * @var boolean whether to turn on prepare emulation. Defaults to false, meaning PDO
	 * will use the native prepare support if available. For some databases (such as MySQL),
	 * this may need to be set true so that PDO can emulate the prepare support to bypass
Qiang Xue committed
215 216
	 * the buggy native prepare support.
	 * The default value is null, which means the PDO ATTR_EMULATE_PREPARES value will not be changed.
w  
Qiang Xue committed
217 218 219
	 */
	public $emulatePrepare;
	/**
220 221
	 * @var string the common prefix or suffix for table names. If a table name is given
	 * as `{{%TableName}}`, then the percentage character `%` will be replaced with this
222
	 * property value. For example, `{{%post}}` becomes `{{tbl_post}}`.
w  
Qiang Xue committed
223
	 */
224
	public $tablePrefix = 'tbl_';
w  
Qiang Xue committed
225
	/**
Qiang Xue committed
226
	 * @var array mapping between PDO driver names and [[Schema]] classes.
w  
Qiang Xue committed
227
	 * The keys of the array are PDO driver names while the values the corresponding
Qiang Xue committed
228
	 * schema class name or configuration. Please refer to [[Yii::createObject()]] for
w  
Qiang Xue committed
229 230
	 * details on how to specify a configuration.
	 *
Qiang Xue committed
231
	 * This property is mainly used by [[getSchema()]] when fetching the database schema information.
Qiang Xue committed
232
	 * You normally do not need to set this property unless you want to use your own
Qiang Xue committed
233 234
	 * [[Schema]] class to support DBMS that is not supported by Yii.
	 */
Alexander Makarov committed
235
	public $schemaMap = [
236 237 238 239
		'pgsql' => 'yii\db\pgsql\Schema',    // PostgreSQL
		'mysqli' => 'yii\db\mysql\Schema',   // MySQL
		'mysql' => 'yii\db\mysql\Schema',    // MySQL
		'sqlite' => 'yii\db\sqlite\Schema',  // sqlite 3
Qiang Xue committed
240
		'sqlite2' => 'yii\db\sqlite\Schema', // sqlite 2
resurtm committed
241
		'sqlsrv' => 'yii\db\mssql\Schema',   // newer MSSQL driver on MS Windows hosts
242
		'oci' => 'yii\db\oci\Schema',        // Oracle driver
resurtm committed
243 244
		'mssql' => 'yii\db\mssql\Schema',    // older MSSQL driver on MS Windows hosts
		'dblib' => 'yii\db\mssql\Schema',    // dblib drivers on GNU/Linux (and maybe other OSes) hosts
245
		'cubrid' => 'yii\db\cubrid\Schema',  // CUBRID
Alexander Makarov committed
246
	];
Carsten Brandt committed
247 248 249 250
	/**
	 * @var string Custom PDO wrapper class. If not set, it will use "PDO" or "yii\db\mssql\PDO" when MSSQL is used.
	 */
	public $pdoClass;
251 252 253 254 255
	/**
	 * @var boolean whether to enable [savepoint](http://en.wikipedia.org/wiki/Savepoint).
	 * Note that if the underlying DBMS does not support savepoint, setting this property to be true will have no effect.
	 */
	public $enableSavepoint = true;
Qiang Xue committed
256 257 258
	/**
	 * @var Transaction the currently active transaction
	 */
w  
Qiang Xue committed
259
	private $_transaction;
Qiang Xue committed
260
	/**
Qiang Xue committed
261
	 * @var Schema the database schema
Qiang Xue committed
262
	 */
Qiang Xue committed
263
	private $_schema;
Carsten Brandt committed
264

265

w  
Qiang Xue committed
266
	/**
w  
Qiang Xue committed
267
	 * Returns a value indicating whether the DB connection is established.
w  
Qiang Xue committed
268 269
	 * @return boolean whether the DB connection is established
	 */
270
	public function getIsActive()
w  
Qiang Xue committed
271
	{
w  
Qiang Xue committed
272
		return $this->pdo !== null;
w  
Qiang Xue committed
273 274 275
	}

	/**
276 277 278
	 * Turns on query caching.
	 * This method is provided as a shortcut to setting two properties that are related
	 * with query caching: [[queryCacheDuration]] and [[queryCacheDependency]].
w  
Qiang Xue committed
279
	 * @param integer $duration the number of seconds that query results may remain valid in cache.
280
	 * If not set, it will use the value of [[queryCacheDuration]]. See [[queryCacheDuration]] for more details.
Qiang Xue committed
281
	 * @param \yii\caching\Dependency $dependency the dependency for the cached query result.
282 283 284 285 286 287 288 289 290 291 292 293 294
	 * See [[queryCacheDependency]] for more details.
	 */
	public function beginCache($duration = null, $dependency = null)
	{
		$this->enableQueryCache = true;
		if ($duration !== null) {
			$this->queryCacheDuration = $duration;
		}
		$this->queryCacheDependency = $dependency;
	}

	/**
	 * Turns off query caching.
w  
Qiang Xue committed
295
	 */
296
	public function endCache()
w  
Qiang Xue committed
297
	{
298
		$this->enableQueryCache = false;
w  
Qiang Xue committed
299 300 301
	}

	/**
w  
Qiang Xue committed
302 303 304
	 * Establishes a DB connection.
	 * It does nothing if a DB connection has already been established.
	 * @throws Exception if connection fails
w  
Qiang Xue committed
305
	 */
w  
Qiang Xue committed
306
	public function open()
w  
Qiang Xue committed
307
	{
w  
Qiang Xue committed
308 309
		if ($this->pdo === null) {
			if (empty($this->dsn)) {
310
				throw new InvalidConfigException('Connection::dsn cannot be empty.');
w  
Qiang Xue committed
311
			}
312
			$token = 'Opening DB connection: ' . $this->dsn;
w  
Qiang Xue committed
313
			try {
314 315
				Yii::trace($token, __METHOD__);
				Yii::beginProfile($token, __METHOD__);
w  
Qiang Xue committed
316
				$this->pdo = $this->createPdoInstance();
Qiang Xue committed
317
				$this->initConnection();
318
				Yii::endProfile($token, __METHOD__);
resurtm committed
319
			} catch (\PDOException $e) {
320
				Yii::endProfile($token, __METHOD__);
321
				throw new Exception($e->getMessage(), $e->errorInfo, (int)$e->getCode(), $e);
w  
Qiang Xue committed
322 323 324 325 326 327 328 329
			}
		}
	}

	/**
	 * Closes the currently active DB connection.
	 * It does nothing if the connection is already closed.
	 */
w  
Qiang Xue committed
330
	public function close()
w  
Qiang Xue committed
331
	{
w  
Qiang Xue committed
332
		if ($this->pdo !== null) {
Qiang Xue committed
333
			Yii::trace('Closing DB connection: ' . $this->dsn, __METHOD__);
w  
Qiang Xue committed
334
			$this->pdo = null;
Qiang Xue committed
335
			$this->_schema = null;
Qiang Xue committed
336
			$this->_transaction = null;
w  
Qiang Xue committed
337
		}
w  
Qiang Xue committed
338 339 340 341
	}

	/**
	 * Creates the PDO instance.
w  
Qiang Xue committed
342
	 * This method is called by [[open]] to establish a DB connection.
Qiang Xue committed
343 344
	 * The default implementation will create a PHP PDO instance.
	 * You may override this method if the default PDO needs to be adapted for certain DBMS.
Qiang Xue committed
345
	 * @return PDO the pdo instance
w  
Qiang Xue committed
346 347 348
	 */
	protected function createPdoInstance()
	{
349 350 351 352 353 354 355 356
		$pdoClass = $this->pdoClass;
		if ($pdoClass === null) {
			$pdoClass = 'PDO';
			if (($pos = strpos($this->dsn, ':')) !== false) {
				$driver = strtolower(substr($this->dsn, 0, $pos));
				if ($driver === 'mssql' || $driver === 'dblib' || $driver === 'sqlsrv') {
					$pdoClass = 'yii\db\mssql\PDO';
				}
w  
Qiang Xue committed
357
			}
w  
Qiang Xue committed
358
		}
359

w  
Qiang Xue committed
360
		return new $pdoClass($this->dsn, $this->username, $this->password, $this->attributes);
w  
Qiang Xue committed
361 362 363
	}

	/**
w  
Qiang Xue committed
364 365
	 * Initializes the DB connection.
	 * This method is invoked right after the DB connection is established.
Qiang Xue committed
366 367
	 * The default implementation turns on `PDO::ATTR_EMULATE_PREPARES`
	 * if [[emulatePrepare]] is true, and sets the database [[charset]] if it is not empty.
Qiang Xue committed
368
	 * It then triggers an [[EVENT_AFTER_OPEN]] event.
w  
Qiang Xue committed
369
	 */
w  
Qiang Xue committed
370
	protected function initConnection()
w  
Qiang Xue committed
371
	{
Qiang Xue committed
372 373 374
		$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		if ($this->emulatePrepare !== null && constant('PDO::ATTR_EMULATE_PREPARES')) {
			$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare);
w  
Qiang Xue committed
375
		}
Alexander Makarov committed
376
		if ($this->charset !== null && in_array($this->getDriverName(), ['pgsql', 'mysql', 'mysqli', 'cubrid'])) {
Qiang Xue committed
377
			$this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset));
w  
Qiang Xue committed
378
		}
379
		$this->trigger(self::EVENT_AFTER_OPEN);
w  
Qiang Xue committed
380 381 382 383
	}

	/**
	 * Creates a command for execution.
Qiang Xue committed
384 385
	 * @param string $sql the SQL statement to be executed
	 * @param array $params the parameters to be bound to the SQL statement
w  
Qiang Xue committed
386
	 * @return Command the DB command
w  
Qiang Xue committed
387
	 */
Alexander Makarov committed
388
	public function createCommand($sql = null, $params = [])
w  
Qiang Xue committed
389
	{
w  
Qiang Xue committed
390
		$this->open();
Alexander Makarov committed
391
		$command = new Command([
Qiang Xue committed
392
			'db' => $this,
393
			'sql' => $sql,
Alexander Makarov committed
394
		]);
Qiang Xue committed
395
		return $command->bindValues($params);
w  
Qiang Xue committed
396 397 398 399
	}

	/**
	 * Returns the currently active transaction.
w  
Qiang Xue committed
400
	 * @return Transaction the currently active transaction. Null if no active transaction.
w  
Qiang Xue committed
401
	 */
Qiang Xue committed
402
	public function getTransaction()
w  
Qiang Xue committed
403
	{
404
		return $this->_transaction && $this->_transaction->getIsActive() ? $this->_transaction : null;
w  
Qiang Xue committed
405 406 407 408
	}

	/**
	 * Starts a transaction.
Qiang Xue committed
409
	 * @return Transaction the transaction initiated
w  
Qiang Xue committed
410 411 412
	 */
	public function beginTransaction()
	{
w  
Qiang Xue committed
413
		$this->open();
414 415 416 417 418 419

		if (($transaction = $this->getTransaction()) === null) {
			$transaction = $this->_transaction = new Transaction(['db' => $this]);
		}
		$transaction->begin();
		return $transaction;
w  
Qiang Xue committed
420 421 422
	}

	/**
Qiang Xue committed
423 424
	 * Returns the schema information for the database opened by this connection.
	 * @return Schema the schema information for the database opened by this connection.
Qiang Xue committed
425
	 * @throws NotSupportedException if there is no support for the current driver type
w  
Qiang Xue committed
426
	 */
Qiang Xue committed
427
	public function getSchema()
w  
Qiang Xue committed
428
	{
Qiang Xue committed
429 430
		if ($this->_schema !== null) {
			return $this->_schema;
Qiang Xue committed
431
		} else {
w  
Qiang Xue committed
432
			$driver = $this->getDriverName();
Qiang Xue committed
433
			if (isset($this->schemaMap[$driver])) {
434 435 436
				$config = !is_array($this->schemaMap[$driver]) ? ['class' => $this->schemaMap[$driver]] : $this->schemaMap[$driver];
				$config['db'] = $this;
				return $this->_schema = Yii::createObject($config);
Qiang Xue committed
437
			} else {
Qiang Xue committed
438
				throw new NotSupportedException("Connection does not support reading schema information for '$driver' DBMS.");
w  
Qiang Xue committed
439
			}
w  
Qiang Xue committed
440 441 442
		}
	}

Qiang Xue committed
443 444 445 446
	/**
	 * Returns the query builder for the current DB connection.
	 * @return QueryBuilder the query builder for the current DB connection.
	 */
w  
Qiang Xue committed
447 448
	public function getQueryBuilder()
	{
Qiang Xue committed
449
		return $this->getSchema()->getQueryBuilder();
w  
Qiang Xue committed
450 451
	}

Qiang Xue committed
452
	/**
Qiang Xue committed
453 454
	 * Obtains the schema information for the named table.
	 * @param string $name table name.
Qiang Xue committed
455
	 * @param boolean $refresh whether to reload the table schema even if it is found in the cache.
Qiang Xue committed
456
	 * @return TableSchema table schema information. Null if the named table does not exist.
Qiang Xue committed
457 458 459
	 */
	public function getTableSchema($name, $refresh = false)
	{
Qiang Xue committed
460
		return $this->getSchema()->getTableSchema($name, $refresh);
Qiang Xue committed
461 462
	}

w  
Qiang Xue committed
463 464 465 466 467 468 469 470
	/**
	 * Returns the ID of the last inserted row or sequence value.
	 * @param string $sequenceName name of the sequence object (required by some DBMS)
	 * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
	 * @see http://www.php.net/manual/en/function.PDO-lastInsertId.php
	 */
	public function getLastInsertID($sequenceName = '')
	{
Qiang Xue committed
471
		return $this->getSchema()->getLastInsertID($sequenceName);
w  
Qiang Xue committed
472 473 474 475
	}

	/**
	 * Quotes a string value for use in a query.
Qiang Xue committed
476
	 * Note that if the parameter is not a string, it will be returned without change.
w  
Qiang Xue committed
477 478 479 480 481 482
	 * @param string $str string to be quoted
	 * @return string the properly quoted string
	 * @see http://www.php.net/manual/en/function.PDO-quote.php
	 */
	public function quoteValue($str)
	{
Qiang Xue committed
483
		return $this->getSchema()->quoteValue($str);
w  
Qiang Xue committed
484 485 486 487 488
	}

	/**
	 * Quotes a table name for use in a query.
	 * If the table name contains schema prefix, the prefix will also be properly quoted.
489 490
	 * If the table name is already quoted or contains special characters including '(', '[[' and '{{',
	 * then this method will do nothing.
w  
Qiang Xue committed
491 492 493
	 * @param string $name table name
	 * @return string the properly quoted table name
	 */
494
	public function quoteTableName($name)
w  
Qiang Xue committed
495
	{
Qiang Xue committed
496
		return $this->getSchema()->quoteTableName($name);
w  
Qiang Xue committed
497 498 499 500
	}

	/**
	 * Quotes a column name for use in a query.
501 502 503
	 * If the column name contains prefix, the prefix will also be properly quoted.
	 * If the column name is already quoted or contains special characters including '(', '[[' and '{{',
	 * then this method will do nothing.
w  
Qiang Xue committed
504 505 506
	 * @param string $name column name
	 * @return string the properly quoted column name
	 */
507
	public function quoteColumnName($name)
Qiang Xue committed
508
	{
Qiang Xue committed
509
		return $this->getSchema()->quoteColumnName($name);
Qiang Xue committed
510 511
	}

512 513 514 515
	/**
	 * Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
	 * Tokens enclosed within double curly brackets are treated as table names, while
	 * tokens enclosed within double square brackets are column names. They will be quoted accordingly.
Qiang Xue committed
516 517
	 * Also, the percentage character "%" at the beginning or ending of a table name will be replaced
	 * with [[tablePrefix]].
518 519 520 521 522
	 * @param string $sql the SQL to be quoted
	 * @return string the quoted SQL
	 */
	public function quoteSql($sql)
	{
Qiang Xue committed
523
		return preg_replace_callback('/(\\{\\{(%?[\w\-\. ]+%?)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/',
524
			function ($matches) {
525
				if (isset($matches[3])) {
526
					return $this->quoteColumnName($matches[3]);
527
				} else {
528
					return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
529 530 531 532
				}
			}, $sql);
	}

w  
Qiang Xue committed
533
	/**
w  
Qiang Xue committed
534
	 * Returns the name of the DB driver for the current [[dsn]].
w  
Qiang Xue committed
535 536 537 538
	 * @return string name of the DB driver
	 */
	public function getDriverName()
	{
w  
Qiang Xue committed
539 540
		if (($pos = strpos($this->dsn, ':')) !== false) {
			return strtolower(substr($this->dsn, 0, $pos));
Qiang Xue committed
541
		} else {
542
			$this->open();
Qiang Xue committed
543
			return strtolower($this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME));
w  
Qiang Xue committed
544
		}
w  
Qiang Xue committed
545 546
	}
}