Connection
API reference › yii › db › Connection
Connection represents a connection to a database via PDO.
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.
Connection supports database replication and read-write splitting. In particular, a Connection component
can be configured with multiple $masters and $slaves. It will do load balancing and failover by choosing
appropriate servers. It will also automatically direct read operations to the slaves and write operations to
the masters.
To establish a DB connection, set $dsn, $username and $password, and then
call open() to connect to the database server. The current state of the connection can be checked using $isActive.
The following example shows how to create a Connection instance and establish the DB connection:
$connection = new \yii\db\Connection([ 'dsn' => $dsn, 'username' => $username, 'password' => $password,]);$connection->open();After the DB connection is established, one can execute SQL statements like the following:
$command = $connection->createCommand('SELECT * FROM post');$posts = $command->queryAll();$command = $connection->createCommand('UPDATE post SET status=1');$command->execute();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:
$command = $connection->createCommand('SELECT * FROM post WHERE id=:id');$command->bindValue(':id', $_GET['id']);$post = $command->query();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:
$transaction = $connection->beginTransaction();try { $connection->createCommand($sql1)->execute(); $connection->createCommand($sql2)->execute(); // ... executing other SQL statements ... $transaction->commit();} catch (Exception $e) { $transaction->rollBack();}You also can use shortcut for the above like the following:
$connection->transaction(function () { $order = new Order($customer); $order->save(); $order->addItems($items);});If needed you can pass transaction isolation level as a second parameter:
$connection->transaction(function (Connection $db) { //return $db->...}, Transaction::READ_UNCOMMITTED);Connection is often used as an application component and configured in the application configuration like the following:
'components' => [ 'db' => [ 'class' => '\yii\db\Connection', 'dsn' => 'mysql:host=127.0.0.1;dbname=demo', 'username' => 'root', 'password' => '', 'charset' => 'utf8mb4', ],],Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$attributes | array | PDO attributes (name => value) that should be set when calling open() to establish a DB connection. Default: null. | Connection |
$behaviors read-only | array<yii\<static>> | List of behaviors attached to this component. | yii\ |
$charset | string| | The charset used for database connection. Default: null. | Connection |
$commandMap | array | Mapping between PDO driver names and Command classes. Default: ['pgsql' => 'yii\. Available since 2.0.14. | Connection |
$driverName | string | Name of the DB driver. | Connection |
$dsn | string | The Data Source Name, or DSN, contains the information required to connect to the database. Default: null. | Connection |
$effectiveCharset read-only | string| | The effective connection charset, or null when the connection relies on the database server defaults. | Connection |
$emulatePrepare | bool| | Whether to turn on prepare emulation. Default: null. | Connection |
$enableLogging | bool | Whether to enable logging of database queries. Default: true. Available since 2.0.12. | Connection |
$enableProfiling | bool | Whether to enable profiling of opening database connection and database queries. Default: true. Available since 2.0.12. | Connection |
$enableQueryCache | bool | Whether to enable query caching. Default: true. | Connection |
$enableSavepoint | bool | Whether to enable savepoint. Default: true. | Connection |
$enableSchemaCache | bool | Whether to enable schema caching. Default: false. | Connection |
$enableSlaves | bool | Whether to enable read/write splitting by using $slaves to read data. Default: true. | Connection |
$isActive read-only | bool | Whether the DB connection is established. | Connection |
$isSybase | bool | If the database connected via pdo_dblib is SyBase. Default: false. Available since 2.0.38. | Connection |
$lastInsertID read-only | string | The row ID of the last row inserted, or the last value retrieved from the sequence object. | Connection |
$master read-only | Connection| | The currently active master connection. null is returned if there is no master available. | Connection |
$masterConfig | array | The configuration that should be merged with every master configuration listed in $masters. Default: []. | Connection |
$masterPdo read-only | PDO | The PDO instance for the currently active master connection. | Connection |
$masters | array | List of master connection configurations. Default: []. | Connection |
$password | string| | The password for establishing DB connection. Default: null. | Connection |
$pdo | PDO| | The PHP PDO instance associated with this DB connection. Default: null. | Connection |
$pdoClass | string| | Custom PDO wrapper class. Default: null. | Connection |
$queryBuilder | array | The QueryBuilder properties to be configured. | Connection |
$queryCache | yii\| | The cache object or the ID of the cache application component that is used for query caching. Default: 'cache'. | Connection |
$queryCacheDuration | int | The default number of seconds that query results can remain valid in cache. Default: 3600. | Connection |
$schema read-only | yii\ | The schema information for the database opened by this connection. | Connection |
$schemaCache | yii\| | The cache object or the ID of the cache application component that is used to cache the table metadata. Default: 'cache'. | Connection |
$schemaCacheDuration | int | Number of seconds that table metadata can remain valid in cache. Default: 3600. | Connection |
$schemaCacheExclude | array | List of tables whose metadata should NOT be cached. Default: []. | Connection |
$schemaMap | array | Mapping between PDO driver names and Schema classes. Default: ['pgsql' => 'yii\. | Connection |
$serverRetryInterval | int | The retry interval in seconds for dead servers listed in $masters and $slaves. Default: 600. | Connection |
$serverStatusCache | yii\| | The cache object or the ID of the cache application component that is used to store the health status of the DB servers specified in $masters and $slaves. Default: 'cache'. | Connection |
$serverVersion read-only | string | Server version as a string. | Connection |
$shuffleMasters | bool | Whether to shuffle $masters before getting one. Default: true. Available since 2.0.11. | Connection |
$slave read-only | Connection| | The currently active slave connection. null is returned if there is no slave available and $fallbackToMaster is false. | Connection |
$slaveConfig | array | The configuration that should be merged with every slave configuration listed in $slaves. Default: []. | Connection |
$slavePdo read-only | PDO| | The PDO instance for the currently active slave connection. null is returned if no slave connection is available and $fallbackToMaster is false. | Connection |
$slaves | array | List of slave connection configurations. Default: []. | Connection |
$tablePrefix | string | The common prefix or suffix for table names. Default: ''. | Connection |
$transaction read-only | Transaction| | The currently active transaction. | Connection |
$transactionMap | array<string,Transaction>| | Mapping between PDO driver names and Transaction classes or configurations. Default: ['pgsql' => \. Available since 22.0. | Connection |
$username | string| | The username for establishing DB connection. Default: null. | Connection |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | yii\ |
__call() | Calls the named method which is not a class method. | yii\ |
__clone() | Reset the connection after cloning. | Connection |
__get() | Returns the value of a component property. | yii\ |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
__set() | Sets the value of a component property. | yii\ |
__sleep() | Close the connection before serializing. | Connection |
__unset() | Sets a component property to be null. | yii\ |
attachBehavior() | Attaches a behavior to this component. | yii\ |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\ |
beginTransaction() | Starts a transaction. | Connection |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\ |
cache() | Uses query cache for the queries performed with the callable. | Connection |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\ |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
className() static | Returns the fully qualified name of this class. | yii\ |
close() | Closes the currently active DB connection. | Connection |
createCommand() | Creates a command for execution. | Connection |
detachBehavior() | Detaches a behavior from the component. | yii\ |
detachBehaviors() | Detaches all behaviors from the component. | yii\ |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\ |
getBehavior() | Returns the named behavior object. | yii\ |
getBehaviors() | Returns all behaviors attached to this component. | yii\ |
getDriverName() | Returns the name of the DB driver. Based on the the current $dsn, in case it was not set explicitly by an end user. | Connection |
getEffectiveCharset() | Returns the charset the connection effectively uses. | Connection |
getIsActive() | Returns a value indicating whether the DB connection is established. | Connection |
getLastInsertID() | Returns the ID of the last inserted row or sequence value. | Connection |
getMaster() | Returns the currently active master connection. | Connection |
getMasterPdo() | Returns the PDO instance for the currently active master connection. | Connection |
getQueryBuilder() | Returns the query builder for the current DB connection. | Connection |
getSchema() | Returns the schema information for the database opened by this connection. | Connection |
getServerVersion() | Returns a server version as a string comparable by version_compare(). | Connection |
getSlave() | Returns the currently active slave connection. | Connection |
getSlavePdo() | Returns the PDO instance for the currently active slave connection. | Connection |
getTableSchema() | Obtains the schema information for the named table. | Connection |
getTransaction() | Returns the currently active transaction. | Connection |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. | yii\ |
hasMethod() | Returns a value indicating whether a method is defined. | yii\ |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\ |
init() | Initializes the object. | yii\ |
noCache() | Disables query cache temporarily. | Connection |
off() | Detaches an existing event handler from this component. | yii\ |
on() | Attaches an event handler to an event. | yii\ |
open() | Establishes a DB connection. | Connection |
quoteColumnName() | Quotes a column name for use in a query. | Connection |
quoteSql() | Processes a SQL statement by quoting table and column names that are enclosed within double brackets. | Connection |
quoteTableName() | Quotes a table name for use in a query. | Connection |
quoteValue() | Quotes a string value for use in a query. | Connection |
setDriverName() | Changes the current driver name. | Connection |
setQueryBuilder() | Can be used to set QueryBuilder configuration via Connection configuration array. | Connection |
transaction() | Executes callback provided in a transaction. | Connection |
trigger() | Triggers an event. | yii\ |
useMaster() | Executes the provided callback by using the master connection. | Connection |
createPdoInstance() protected | Creates the PDO instance. | Connection |
initConnection() protected | Initializes the DB connection. | Connection |
openFromPool() protected | Opens the connection to a server in the pool. | Connection |
openFromPoolSequentially() protected | Opens the connection to a server in the pool. | Connection |
Events
Section titled “Events”| Event | Type | Description | Defined by |
|---|---|---|---|
EVENT_AFTER_OPEN | yii\ | An event that is triggered after a DB connection is established Event name: 'afterOpen'. | Connection |
EVENT_BEGIN_TRANSACTION | yii\ | An event that is triggered right before a top-level transaction is started Event name: 'beginTransaction'. | Connection |
EVENT_COMMIT_TRANSACTION | yii\ | An event that is triggered right after a top-level transaction is committed Event name: 'commitTransaction'. | Connection |
EVENT_ROLLBACK_TRANSACTION | yii\ | An event that is triggered right after a top-level transaction is rolled back Event name: 'rollbackTransaction'. | Connection |
Property details
Section titled “Property details”$attributes
Section titled “$attributes ”public array $attributes = nullPDO attributes (name => value) that should be set when calling open() to establish a DB connection.
Please refer to the PHP manual for details about available attributes.
$charset
Section titled “$charset ”public string|null $charset = nullThe charset used for database connection.
The property is only used for MySQL and PostgreSQL
databases. Defaults to null. MySQL and MariaDB connections use utf8mb4 when neither this property nor the
$dsn specifies a charset. PostgreSQL connections use the default charset configured by the database.
For Oracle Database, the charset must be specified in the $dsn, for example for UTF-8 by appending
;charset=UTF-8 to the DSN string.
The same applies for if you’re using GBK or BIG5 charset with MySQL, then it’s highly recommended to specify
charset via $dsn like 'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'.
$commandMap
Section titled “$commandMap ”public array $commandMap = ['pgsql' => 'yii\db\Command', 'mysqli' => 'yii\db\Command', 'mysql' => 'yii\db\Command', 'sqlite' => 'yii\db\sqlite\Command', 'sqlite2' => 'yii\db\sqlite\Command', 'sqlsrv' => 'yii\db\mssql\Command', 'oci' => 'yii\db\oci\Command', 'mssql' => 'yii\db\mssql\Command', 'dblib' => 'yii\db\mssql\Command']Mapping between PDO driver names and Command classes.
The keys of the array are PDO driver names while the values are either the corresponding
command class names or configurations. Please refer to Yii::createObject() for
details on how to specify a configuration.
This property is mainly used by createCommand() to create new database Command objects.
You normally do not need to set this property unless you want to use your own
Command class or support DBMS that is not supported by Yii.
Since
2.0.14
public string $dsn = nullThe Data Source Name, or DSN, contains the information required to connect to the database.
Please refer to the PHP manual on the format of the DSN string.
For SQLite you may use a path alias
for specifying the database path, e.g. sqlite:@app/data/db.sql.
$emulatePrepare
Section titled “$emulatePrepare ”public bool|null $emulatePrepare = nullWhether 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 the buggy native prepare support. The default value is null, which means the PDO ATTR_EMULATE_PREPARES value will not be changed.
$enableLogging
Section titled “$enableLogging ”public bool $enableLogging = trueWhether to enable logging of database queries.
Defaults to true. You may want to disable this option in a production environment to gain performance if you do not need the information being logged.
Since
2.0.12
$enableProfiling
Section titled “$enableProfiling ”public bool $enableProfiling = trueWhether to enable profiling of opening database connection and database queries.
Defaults to true. You may want to disable this option in a production environment to gain performance if you do not need the information being logged.
Since
2.0.12
$enableQueryCache
Section titled “$enableQueryCache ”public bool $enableQueryCache = trueWhether to enable query caching.
Note that in order to enable query caching, a valid cache component as specified
by $queryCache must be enabled and $enableQueryCache must be set true.
Also, only the results of the queries enclosed within cache() will be cached.
$enableSavepoint
Section titled “$enableSavepoint ”public bool $enableSavepoint = trueWhether to enable savepoint.
Note that if the underlying DBMS does not support savepoint, setting this property to be true will have no effect.
$enableSchemaCache
Section titled “$enableSchemaCache ”public bool $enableSchemaCache = falseWhether to enable schema caching.
Note that in order to enable truly schema caching, a valid cache component as specified
by $schemaCache must be enabled and $enableSchemaCache must be set true.
$enableSlaves
Section titled “$enableSlaves ”public bool $enableSlaves = trueWhether to enable read/write splitting by using $slaves to read data.
Note that if $slaves is empty, read/write splitting will NOT be enabled no matter what value this property takes.
$masterConfig
Section titled “$masterConfig ”public array $masterConfig = []The configuration that should be merged with every master configuration listed in $masters.
For example,
[ 'username' => 'master', 'password' => 'master', 'attributes' => [ // use a smaller connection timeout PDO::ATTR_TIMEOUT => 10, ],]$masters
Section titled “$masters ”public array $masters = []List of master connection configurations.
Each configuration is used to create a master DB connection.
When open() is called, one of these configurations will be chosen and used to create a DB connection
which will be used by this object.
Note that when this property is not empty, the connection setting (e.g. “dsn”, “username”) of this object will
be ignored.
$password
Section titled “$password ”public string|null $password = nullThe password for establishing DB connection.
Defaults to null meaning no password to use.
public PDO|null $pdo = nullThe PHP PDO instance associated with this DB connection.
This property is mainly managed by open() and close() methods.
When a DB connection is active, this property will represent a PDO instance;
otherwise, it will be null.
$queryCacheDuration
Section titled “$queryCacheDuration ”public int $queryCacheDuration = 3600The default number of seconds that query results can remain valid in cache.
Defaults to 3600, meaning 3600 seconds, or one hour. Use 0 to indicate that the cached data will never expire.
The value of this property will be used when cache() is called without a cache duration.
$schemaCacheDuration
Section titled “$schemaCacheDuration ”public int $schemaCacheDuration = 3600Number of seconds that table metadata can remain valid in cache.
Use 0 to indicate that the cached data will never expire.
$schemaCacheExclude
Section titled “$schemaCacheExclude ”public array $schemaCacheExclude = []List of tables whose metadata should NOT be cached.
Defaults to empty array. The table names may contain schema prefix, if any. Do not quote the table names.
$schemaMap
Section titled “$schemaMap ”public array $schemaMap = ['pgsql' => 'yii\db\pgsql\Schema', 'mysqli' => 'yii\db\mysql\Schema', 'mysql' => 'yii\db\mysql\Schema', 'sqlite' => 'yii\db\sqlite\Schema', 'sqlite2' => 'yii\db\sqlite\Schema', 'sqlsrv' => 'yii\db\mssql\Schema', 'oci' => 'yii\db\oci\Schema', 'mssql' => 'yii\db\mssql\Schema', 'dblib' => 'yii\db\mssql\Schema']Mapping between PDO driver names and Schema classes.
The keys of the array are PDO driver names while the values are either the corresponding
schema class names or configurations. Please refer to Yii::createObject() for
details on how to specify a configuration.
This property is mainly used by getSchema() when fetching the database schema information.
You normally do not need to set this property unless you want to use your own
Schema class to support DBMS that is not supported by Yii.
$serverRetryInterval
Section titled “$serverRetryInterval ”public int $serverRetryInterval = 600The retry interval in seconds for dead servers listed in $masters and $slaves.
This is used together with $serverStatusCache.
$serverStatusCache
Section titled “$serverStatusCache ”public yii\caching\CacheInterface|string|false $serverStatusCache = 'cache'The cache object or the ID of the cache application component that is used to store the health status of the DB servers specified in $masters and $slaves.
This is used only when read/write splitting is enabled or $masters is not empty.
Set boolean false to disabled server status caching.
$slaveConfig
Section titled “$slaveConfig ”public array $slaveConfig = []The configuration that should be merged with every slave configuration listed in $slaves.
For example,
[ 'username' => 'slave', 'password' => 'slave', 'attributes' => [ // use a smaller connection timeout PDO::ATTR_TIMEOUT => 10, ],]$slaves
Section titled “$slaves ”public array $slaves = []List of slave connection configurations.
Each configuration is used to create a slave DB connection.
When $enableSlaves is true, one of these configurations will be chosen and used to create a DB connection
for performing read queries only.
$tablePrefix
Section titled “$tablePrefix ”public string $tablePrefix = ''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
property value. For example, {{%post}} becomes {{tbl_post}}.
$transaction
Section titled “$transaction ”public yii\db\Transaction|null $transactionThe currently active transaction.
Null if no active transaction.
Access
Read-only (virtual property).
$transactionMap
Section titled “$transactionMap ”public array<string, class-string<yii\db\Transaction>|array<string, mixed>> $transactionMap = ['pgsql' => \yii\db\pgsql\Transaction::class, 'mysqli' => \yii\db\Transaction::class, 'mysql' => \yii\db\Transaction::class, 'sqlite' => \yii\db\Transaction::class, 'sqlite2' => \yii\db\Transaction::class, 'sqlsrv' => \yii\db\Transaction::class, 'oci' => \yii\db\Transaction::class, 'mssql' => \yii\db\Transaction::class, 'dblib' => \yii\db\Transaction::class]Mapping between PDO driver names and Transaction classes or configurations.
The keys of the array are PDO driver names while the values are either the corresponding transaction class names
or configurations. Please refer to Yii::createObject() for details on how to specify a configuration.
This property is mainly used by beginTransaction() to start new database Transaction objects.
You normally do not need to set this property unless you want to use your own Transaction class or support
DBMS that is not supported by Yii.
Since
22.0
$username
Section titled “$username ”public string|null $username = nullThe username for establishing DB connection.
Defaults to null meaning no username to use.
Method details
Section titled “Method details”__clone()
Section titled “__clone() ”public function __clone(): mixedReset the connection after cloning.
Returns
mixed
__sleep()
Section titled “__sleep() ”public function __sleep(): arrayClose the connection before serializing.
Returns
array
beginTransaction()
Section titled “beginTransaction() ”public function beginTransaction(string|null $isolationLevel = null): yii\db\TransactionStarts a transaction.
Parameters
| Parameter | Type | Description |
|---|---|---|
$isolationLevel | string| | The isolation level to use for this transaction. See Transaction::begin() for details. |
Returns
Transaction: The transaction initiated
cache()
Section titled “cache() ”public function cache(callable $callable, int|null $duration = null, yii\caching\Dependency|null $dependency = null): mixedUses query cache for the queries performed with the callable.
When query caching is enabled ($enableQueryCache is true and $queryCache refers to a valid cache),
queries performed within the callable will be cached and their results will be fetched from cache if available.
For example,
// The customer will be fetched from cache if available.// If not, the query will be made against DB and cached for use next time.$customer = $db->cache(function (Connection $db) { return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();});Note that query cache is only meaningful for queries that return results. For queries performed with
Command::execute(), query cache will not be used.
Parameters
| Parameter | Type | Description |
|---|---|---|
$callable | callable | A PHP callable that contains DB queries which will make use of query cache. The signature of the callable is function (Connection $db). |
$duration | int| | The number of seconds that query results can remain valid in the cache. If this is not set, the value of $queryCacheDuration will be used instead. Use 0 to indicate that the cached data will never expire. |
$dependency | yii\| | The cache dependency associated with the cached query results. |
Returns
mixed: The return result of the callable
Throws
Throwable: if there is any exception during query
See also
close()
Section titled “close() ”public function close(): mixedCloses the currently active DB connection.
It does nothing if the connection is already closed.
Returns
mixed
createCommand()
Section titled “createCommand() ”public function createCommand(string|null $sql = null, array $params = []): yii\db\CommandCreates a command for execution.
Parameters
| Parameter | Type | Description |
|---|---|---|
$sql | string| | The SQL statement to be executed |
$params | array | The parameters to be bound to the SQL statement |
Returns
Command: The DB command
getDriverName()
Section titled “getDriverName() ”public function getDriverName(): string|nullReturns the name of the DB driver. Based on the the current $dsn, in case it was not set explicitly
by an end user.
Returns
string|null: Name of the DB driver
getEffectiveCharset()
Section titled “getEffectiveCharset() ”public function getEffectiveCharset(): string|nullReturns the charset the connection effectively uses.
Resolution order: $charset when set, then a charset element in the $dsn, then utf8mb4 for MySQL and
MariaDB. The value derives from the configuration only, so it is available before the connection is opened.
Returns
string|null: The effective connection charset, or null when the connection relies on the database server defaults.
Since
22.0
getIsActive()
Section titled “getIsActive() ”public function getIsActive(): boolReturns a value indicating whether the DB connection is established.
Returns
bool: Whether the DB connection is established
getLastInsertID()
Section titled “getLastInsertID() ”public function getLastInsertID(string $sequenceName = ''): stringReturns the ID of the last inserted row or sequence value.
Parameters
| Parameter | Type | Description |
|---|---|---|
$sequenceName | string | Name of the sequence object (required by some DBMS) |
Returns
string: The row ID of the last row inserted, or the last value retrieved from the sequence object
See also
getMaster()
Section titled “getMaster() ”public function getMaster(): yii\db\Connection|nullReturns the currently active master connection.
If this method is called for the first time, it will try to open a master connection.
Returns
Connection|null: The currently active master connection. null is returned if there is no master available.
Since
2.0.11
getMasterPdo()
Section titled “getMasterPdo() ”public function getMasterPdo(): PDOReturns the PDO instance for the currently active master connection.
This method will open the master DB connection and then return $pdo.
Returns
PDO: The PDO instance for the currently active master connection.
getQueryBuilder()
Section titled “getQueryBuilder() ”public function getQueryBuilder(): yii\db\TQueryBuilderReturns the query builder for the current DB connection.
Returns
yii\db\TQueryBuilder: The query builder for the current DB connection.
getSchema()
Section titled “getSchema() ”public function getSchema(): yii\db\TSchemaReturns the schema information for the database opened by this connection.
Returns
yii\db\TSchema: The schema information for the database opened by this connection.
Throws
yii\base\NotSupportedException: if there is no support for the current driver type
getServerVersion()
Section titled “getServerVersion() ”public function getServerVersion(): stringReturns a server version as a string comparable by version_compare().
Returns
string: Server version as a string.
Since
2.0.14
getSlave()
Section titled “getSlave() ”public function getSlave(bool $fallbackToMaster = true): yii\db\Connection|nullReturns the currently active slave connection.
If this method is called for the first time, it will try to open a slave connection when $enableSlaves is true.
Parameters
| Parameter | Type | Description |
|---|---|---|
$fallbackToMaster | bool | Whether to return a master connection in case there is no slave connection available. |
Returns
Connection|null: The currently active slave connection. null is returned if there is no slave available and $fallbackToMaster is false.
getSlavePdo()
Section titled “getSlavePdo() ”public function getSlavePdo(bool $fallbackToMaster = true): PDO|nullReturns the PDO instance for the currently active slave connection.
When $enableSlaves is true, one of the slaves will be used for read queries, and its PDO instance
will be returned by this method.
Parameters
| Parameter | Type | Description |
|---|---|---|
$fallbackToMaster | bool | Whether to return a master PDO in case none of the slave connections is available. |
Returns
PDO|null: The PDO instance for the currently active slave connection. null is returned if no slave connection is available and $fallbackToMaster is false.
getTableSchema()
Section titled “getTableSchema() ”public function getTableSchema(string $name, bool $refresh = false): yii\db\TableSchema|nullObtains the schema information for the named table.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | Table name. |
$refresh | bool | Whether to reload the table schema even if it is found in the cache. |
Returns
TableSchema|null: Table schema information. Null if the named table does not exist.
getTransaction()
Section titled “getTransaction() ”public function getTransaction(): yii\db\Transaction|nullReturns the currently active transaction.
Returns
Transaction|null: The currently active transaction. Null if no active transaction.
noCache()
Section titled “noCache() ”public function noCache(callable $callable): mixedDisables query cache temporarily.
Queries performed within the callable will not use query cache at all. For example,
$db->cache(function (Connection $db) {
// ... queries that use query cache ...
return $db->noCache(function (Connection $db) { // this query will not use query cache return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne(); });});Parameters
| Parameter | Type | Description |
|---|---|---|
$callable | callable | A PHP callable that contains DB queries which should not use query cache. The signature of the callable is function (Connection $db). |
Returns
mixed: The return result of the callable
Throws
Throwable: if there is any exception during query
See also
open()
Section titled “open() ”public function open(): mixedEstablishes a DB connection.
It does nothing if a DB connection has already been established.
quoteColumnName()
Section titled “quoteColumnName() ”public function quoteColumnName(string $name): stringQuotes a column name for use in a query.
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.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | Column name |
Returns
string: The properly quoted column name
quoteSql()
Section titled “quoteSql() ”public function quoteSql(string $sql): stringProcesses 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.
Also, the percentage character ”%” at the beginning or ending of a table name will be replaced
with $tablePrefix.
Parameters
| Parameter | Type | Description |
|---|---|---|
$sql | string | The SQL to be quoted |
Returns
string: The quoted SQL
quoteTableName()
Section titled “quoteTableName() ”public function quoteTableName(string $name): stringQuotes a table name for use in a query.
If the table name contains schema prefix, the prefix will also be properly quoted. If the table name is already quoted or contains special characters including ’(’, ’[[’ and ’{{’, then this method will do nothing.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | Table name |
Returns
string: The properly quoted table name
quoteValue()
Section titled “quoteValue() ”public function quoteValue(string $value): stringQuotes a string value for use in a query.
Note that if the parameter is not a string, it will be returned without change.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string | String to be quoted |
Returns
string: The properly quoted string
See also
setDriverName()
Section titled “setDriverName() ”public function setDriverName(string $driverName): mixedChanges the current driver name.
Parameters
| Parameter | Type | Description |
|---|---|---|
$driverName | string | Name of the DB driver |
Returns
mixed
setQueryBuilder()
Section titled “setQueryBuilder() ”public function setQueryBuilder(array $value): mixedCan be used to set QueryBuilder configuration via Connection configuration array.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | array | The QueryBuilder properties to be configured. |
Returns
mixed
Since
2.0.14
transaction()
Section titled “transaction() ”public function transaction(callable $callback, string|null $isolationLevel = null): mixedExecutes callback provided in a transaction.
Parameters
| Parameter | Type | Description |
|---|---|---|
$callback | callable | A valid PHP callback that performs the job. Accepts connection instance as parameter. |
$isolationLevel | string| | The isolation level to use for this transaction. See Transaction::begin() for details. |
Returns
mixed: Result of callback function
Throws
Throwable: if there is any exception during query. In this case the transaction will be rolled back.
useMaster()
Section titled “useMaster() ”public function useMaster(callable $callback): mixedExecutes the provided callback by using the master connection.
This method is provided so that you can temporarily force using the master connection to perform DB operations even if they are read queries. For example,
$result = $db->useMaster(function ($db) { return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();});Parameters
| Parameter | Type | Description |
|---|---|---|
$callback | callable | A PHP callable to be executed by this method. Its signature is function (Connection $db). Its return value will be returned by this method. |
Returns
mixed: The return value of the callback
Throws
Throwable: if there is any exception thrown from the callback
createPdoInstance()
Section titled “createPdoInstance() ”protected function createPdoInstance(): PDOCreates the PDO instance.
This method is called by open() to establish a DB connection.
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.
Returns
PDO: The pdo instance
initConnection()
Section titled “initConnection() ”protected function initConnection(): mixedInitializes the DB connection.
This method is invoked right after the DB connection is established.
The default implementation turns on PDO::ATTR_EMULATE_PREPARES
if $emulatePrepare is true, and sets the database $charset if it is not empty. MySQL and MariaDB
connections fall back to utf8mb4 when neither $charset nor the $dsn specifies a charset.
For PostgreSQL, an explicitly configured Schema::$defaultSchema is applied as the session search_path.
It then triggers an EVENT_AFTER_OPEN event.
Returns
mixed
openFromPool()
Section titled “openFromPool() ”protected function openFromPool(array $pool, array $sharedConfig): yii\db\Connection|nullOpens the connection to a server in the pool.
This method implements load balancing and failover among the given list of the servers.
Connections will be tried in random order.
For details about the failover behavior, see openFromPoolSequentially().
Parameters
| Parameter | Type | Description |
|---|---|---|
$pool | array | The list of connection configurations in the server pool |
$sharedConfig | array | The configuration common to those given in $pool. |
Returns
Connection|null: The opened DB connection, or null if no server is available
Throws
yii\base\InvalidConfigException: if a configuration does not specify “dsn”
See also
openFromPoolSequentially()
Section titled “openFromPoolSequentially() ”protected function openFromPoolSequentially(array $pool, array $sharedConfig): yii\db\Connection|nullOpens the connection to a server in the pool.
This method implements failover among the given list of servers. Connections will be tried in sequential order. The first successful connection will return.
If $serverStatusCache is configured, this method will cache information about
unreachable servers and does not try to connect to these for the time configured in $serverRetryInterval.
This helps to keep the application stable when some servers are unavailable. Avoiding
connection attempts to unavailable servers saves time when the connection attempts fail due to timeout.
If none of the servers are available the status cache is ignored and connection attempts are made to all servers (Since version 2.0.35). This is to avoid downtime when all servers are unavailable for a short time. After a successful connection attempt the server is marked as available again.
Parameters
| Parameter | Type | Description |
|---|---|---|
$pool | array | The list of connection configurations in the server pool |
$sharedConfig | array | The configuration common to those given in $pool. |
Returns
Connection|null: The opened DB connection, or null if no server is available
Throws
yii\base\InvalidConfigException: if a configuration does not specify “dsn”
Since
2.0.11
See also