Skip to content
PHP Ecosystem
Explore

Connection

API reference › yii › db › Connection

classyii\db\Connection
Extendsyii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Since2.0
Sourceframework/db/Connection.php

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',
],
],
PropertyTypeDescriptionDefined by
$attributesarrayPDO attributes (name => value) that should be set when calling open() to establish a DB connection. Default: null.Connection
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$charsetstring|nullThe charset used for database connection. Default: null.Connection
$commandMaparrayMapping between PDO driver names and Command classes. Default: ['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']. Available since 2.0.14.Connection
$driverNamestringName of the DB driver.Connection
$dsnstringThe Data Source Name, or DSN, contains the information required to connect to the database. Default: null.Connection
$effectiveCharset read-onlystring|nullThe effective connection charset, or null when the connection relies on the database server defaults.Connection
$emulatePreparebool|nullWhether to turn on prepare emulation. Default: null.Connection
$enableLoggingboolWhether to enable logging of database queries. Default: true. Available since 2.0.12.Connection
$enableProfilingboolWhether to enable profiling of opening database connection and database queries. Default: true. Available since 2.0.12.Connection
$enableQueryCacheboolWhether to enable query caching. Default: true.Connection
$enableSavepointboolWhether to enable savepoint. Default: true.Connection
$enableSchemaCacheboolWhether to enable schema caching. Default: false.Connection
$enableSlavesboolWhether to enable read/write splitting by using $slaves to read data. Default: true.Connection
$isActive read-onlyboolWhether the DB connection is established.Connection
$isSybaseboolIf the database connected via pdo_dblib is SyBase. Default: false. Available since 2.0.38.Connection
$lastInsertID read-onlystringThe row ID of the last row inserted, or the last value retrieved from the sequence object.Connection
$master read-onlyConnection|nullThe currently active master connection. null is returned if there is no master available.Connection
$masterConfigarrayThe configuration that should be merged with every master configuration listed in $masters. Default: [].Connection
$masterPdo read-onlyPDOThe PDO instance for the currently active master connection.Connection
$mastersarrayList of master connection configurations. Default: [].Connection
$passwordstring|nullThe password for establishing DB connection. Default: null.Connection
$pdoPDO|nullThe PHP PDO instance associated with this DB connection. Default: null.Connection
$pdoClassstring|nullCustom PDO wrapper class. Default: null.Connection
$queryBuilderarrayThe QueryBuilder properties to be configured.Connection
$queryCacheyii\caching\CacheInterface|stringThe cache object or the ID of the cache application component that is used for query caching. Default: 'cache'.Connection
$queryCacheDurationintThe default number of seconds that query results can remain valid in cache. Default: 3600.Connection
$schema read-onlyyii\db\TSchemaThe schema information for the database opened by this connection.Connection
$schemaCacheyii\caching\CacheInterface|stringThe cache object or the ID of the cache application component that is used to cache the table metadata. Default: 'cache'.Connection
$schemaCacheDurationintNumber of seconds that table metadata can remain valid in cache. Default: 3600.Connection
$schemaCacheExcludearrayList of tables whose metadata should NOT be cached. Default: [].Connection
$schemaMaparrayMapping between PDO driver names and Schema classes. Default: ['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'].Connection
$serverRetryIntervalintThe retry interval in seconds for dead servers listed in $masters and $slaves. Default: 600.Connection
$serverStatusCacheyii\caching\CacheInterface|string|falseThe 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-onlystringServer version as a string.Connection
$shuffleMastersboolWhether to shuffle $masters before getting one. Default: true. Available since 2.0.11.Connection
$slave read-onlyConnection|nullThe currently active slave connection. null is returned if there is no slave available and $fallbackToMaster is false.Connection
$slaveConfigarrayThe configuration that should be merged with every slave configuration listed in $slaves. Default: [].Connection
$slavePdo read-onlyPDO|nullThe PDO instance for the currently active slave connection. null is returned if no slave connection is available and $fallbackToMaster is false.Connection
$slavesarrayList of slave connection configurations. Default: [].Connection
$tablePrefixstringThe common prefix or suffix for table names. Default: ''.Connection
$transaction read-onlyTransaction|nullThe currently active transaction.Connection
$transactionMaparray<string, class-string<Transaction>|array<string, mixed>>Mapping between PDO driver names and Transaction classes or configurations. Default: ['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]. Available since 22.0.Connection
$usernamestring|nullThe username for establishing DB connection. Default: null.Connection
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__call()Calls the named method which is not a class method.yii\base\Component
__clone()Reset the connection after cloning.Connection
__get()Returns the value of a component property.yii\base\Component
__isset()Checks if a property is set, i.e. defined and not null.yii\base\Component
__set()Sets the value of a component property.yii\base\Component
__sleep()Close the connection before serializing.Connection
__unset()Sets a component property to be null.yii\base\Component
attachBehavior()Attaches a behavior to this component.yii\base\Component
attachBehaviors()Attaches a list of behaviors to the component.yii\base\Component
beginTransaction()Starts a transaction.Connection
behaviors()Returns a list of behaviors that this component should behave as.yii\base\Component
cache()Uses query cache for the queries performed with the callable.Connection
canGetProperty()Returns a value indicating whether a property can be read.yii\base\Component
canSetProperty()Returns a value indicating whether a property can be set.yii\base\Component
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
close()Closes the currently active DB connection.Connection
createCommand()Creates a command for execution.Connection
detachBehavior()Detaches a behavior from the component.yii\base\Component
detachBehaviors()Detaches all behaviors from the component.yii\base\Component
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.yii\base\Component
getBehavior()Returns the named behavior object.yii\base\Component
getBehaviors()Returns all behaviors attached to this component.yii\base\Component
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\base\Component
hasMethod()Returns a value indicating whether a method is defined.yii\base\Component
hasProperty()Returns a value indicating whether a property is defined for this component.yii\base\Component
init()Initializes the object.yii\base\BaseObject
noCache()Disables query cache temporarily.Connection
off()Detaches an existing event handler from this component.yii\base\Component
on()Attaches an event handler to an event.yii\base\Component
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\base\Component
useMaster()Executes the provided callback by using the master connection.Connection
createPdoInstance() protectedCreates the PDO instance.Connection
initConnection() protectedInitializes the DB connection.Connection
openFromPool() protectedOpens the connection to a server in the pool.Connection
openFromPoolSequentially() protectedOpens the connection to a server in the pool.Connection
EventTypeDescriptionDefined by
EVENT_AFTER_OPENyii\base\EventAn event that is triggered after a DB connection is established Event name: 'afterOpen'.Connection
EVENT_BEGIN_TRANSACTIONyii\base\EventAn event that is triggered right before a top-level transaction is started Event name: 'beginTransaction'.Connection
EVENT_COMMIT_TRANSACTIONyii\base\EventAn event that is triggered right after a top-level transaction is committed Event name: 'commitTransaction'.Connection
EVENT_ROLLBACK_TRANSACTIONyii\base\EventAn event that is triggered right after a top-level transaction is rolled back Event name: 'rollbackTransaction'.Connection
public array $attributes = null

PDO 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.

public string|null $charset = null

The 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;'.

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 = null

The 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.

public bool|null $emulatePrepare = null

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 the buggy native prepare support. The default value is null, which means the PDO ATTR_EMULATE_PREPARES value will not be changed.

public bool $enableLogging = true

Whether 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

public bool $enableProfiling = true

Whether 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

public bool $enableQueryCache = true

Whether 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.

public bool $enableSavepoint = true

Whether to enable savepoint.

Note that if the underlying DBMS does not support savepoint, setting this property to be true will have no effect.

public bool $enableSchemaCache = false

Whether 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.

public bool $enableSlaves = true

Whether 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.

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,
],
]
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.

public string|null $password = null

The password for establishing DB connection.

Defaults to null meaning no password to use.

public PDO|null $pdo = null

The 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.

public string|null $pdoClass = null

Custom PDO wrapper class.

If not set, it will use PDO or PDO when MSSQL is used.

public int $queryCacheDuration = 3600

The 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.

public int $schemaCacheDuration = 3600

Number of seconds that table metadata can remain valid in cache.

Use 0 to indicate that the cached data will never expire.

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.

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.

public int $serverRetryInterval = 600

The retry interval in seconds for dead servers listed in $masters and $slaves.

This is used together with $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.

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,
],
]
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.

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}}.

public yii\db\Transaction|null $transaction

The currently active transaction.

Null if no active transaction.

Access

Read-only (virtual property).

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

public string|null $username = null

The username for establishing DB connection.

Defaults to null meaning no username to use.

public function __clone(): mixed

Reset the connection after cloning.

Returns

mixed

public function __sleep(): array

Close the connection before serializing.

Returns

array

public function beginTransaction(string|null $isolationLevel = null): yii\db\Transaction

Starts a transaction.

Parameters

ParameterTypeDescription
$isolationLevelstring|nullThe isolation level to use for this transaction. See Transaction::begin() for details.

Returns

Transaction: The transaction initiated

public function cache(callable $callable, int|null $duration = null, yii\caching\Dependency|null $dependency = null): mixed

Uses 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

ParameterTypeDescription
$callablecallableA PHP callable that contains DB queries which will make use of query cache. The signature of the callable is function (Connection $db).
$durationint|nullThe 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.
$dependencyyii\caching\Dependency|nullThe 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

public function close(): mixed

Closes the currently active DB connection.

It does nothing if the connection is already closed.

Returns

mixed

public function createCommand(string|null $sql = null, array $params = []): yii\db\Command

Creates a command for execution.

Parameters

ParameterTypeDescription
$sqlstring|nullThe SQL statement to be executed
$paramsarrayThe parameters to be bound to the SQL statement

Returns

Command: The DB command

public function getDriverName(): string|null

Returns 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

public function getEffectiveCharset(): string|null

Returns 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

public function getIsActive(): bool

Returns a value indicating whether the DB connection is established.

Returns

bool: Whether the DB connection is established

public function getLastInsertID(string $sequenceName = ''): string

Returns the ID of the last inserted row or sequence value.

Parameters

ParameterTypeDescription
$sequenceNamestringName 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

public function getMaster(): yii\db\Connection|null

Returns 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

public function getMasterPdo(): PDO

Returns 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.

public function getQueryBuilder(): yii\db\TQueryBuilder

Returns the query builder for the current DB connection.

Returns

yii\db\TQueryBuilder: The query builder for the current DB connection.

public function getSchema(): yii\db\TSchema

Returns 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

public function getServerVersion(): string

Returns a server version as a string comparable by version_compare().

Returns

string: Server version as a string.

Since

2.0.14

public function getSlave(bool $fallbackToMaster = true): yii\db\Connection|null

Returns 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

ParameterTypeDescription
$fallbackToMasterboolWhether 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.

public function getSlavePdo(bool $fallbackToMaster = true): PDO|null

Returns 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

ParameterTypeDescription
$fallbackToMasterboolWhether 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.

public function getTableSchema(string $name, bool $refresh = false): yii\db\TableSchema|null

Obtains the schema information for the named table.

Parameters

ParameterTypeDescription
$namestringTable name.
$refreshboolWhether 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.

public function getTransaction(): yii\db\Transaction|null

Returns the currently active transaction.

Returns

Transaction|null: The currently active transaction. Null if no active transaction.

public function noCache(callable $callable): mixed

Disables 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

ParameterTypeDescription
$callablecallableA 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

public function open(): mixed

Establishes a DB connection.

It does nothing if a DB connection has already been established.

Returns

mixed

Throws

public function quoteColumnName(string $name): string

Quotes 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

ParameterTypeDescription
$namestringColumn name

Returns

string: The properly quoted column name

public function quoteSql(string $sql): string

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. Also, the percentage character ”%” at the beginning or ending of a table name will be replaced with $tablePrefix.

Parameters

ParameterTypeDescription
$sqlstringThe SQL to be quoted

Returns

string: The quoted SQL

public function quoteTableName(string $name): string

Quotes 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

ParameterTypeDescription
$namestringTable name

Returns

string: The properly quoted table name

public function quoteValue(string $value): string

Quotes a string value for use in a query.

Note that if the parameter is not a string, it will be returned without change.

Parameters

ParameterTypeDescription
$valuestringString to be quoted

Returns

string: The properly quoted string

See also

public function setDriverName(string $driverName): mixed

Changes the current driver name.

Parameters

ParameterTypeDescription
$driverNamestringName of the DB driver

Returns

mixed

public function setQueryBuilder(array $value): mixed

Can be used to set QueryBuilder configuration via Connection configuration array.

Parameters

ParameterTypeDescription
$valuearrayThe QueryBuilder properties to be configured.

Returns

mixed

Since

2.0.14

public function transaction(callable $callback, string|null $isolationLevel = null): mixed

Executes callback provided in a transaction.

Parameters

ParameterTypeDescription
$callbackcallableA valid PHP callback that performs the job. Accepts connection instance as parameter.
$isolationLevelstring|nullThe 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.
public function useMaster(callable $callback): mixed

Executes 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

ParameterTypeDescription
$callbackcallableA 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
protected function createPdoInstance(): PDO

Creates 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

protected function initConnection(): mixed

Initializes 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

protected function openFromPool(array $pool, array $sharedConfig): yii\db\Connection|null

Opens 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

ParameterTypeDescription
$poolarrayThe list of connection configurations in the server pool
$sharedConfigarrayThe configuration common to those given in $pool.

Returns

Connection|null: The opened DB connection, or null if no server is available

Throws

See also

protected function openFromPoolSequentially(array $pool, array $sharedConfig): yii\db\Connection|null

Opens 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

ParameterTypeDescription
$poolarrayThe list of connection configurations in the server pool
$sharedConfigarrayThe configuration common to those given in $pool.

Returns

Connection|null: The opened DB connection, or null if no server is available

Throws

Since

2.0.11

See also