Skip to content

Connection ​

Type
Class
Namespace
craft\db
Inherits
craft\db\Connection » yii\db\Connection » yii\base\Component » yii\base\BaseObject
Implements
yii\base\Configurable
Uses traits
craft\db\PrimaryReplicaTrait
Since
3.0.0

View source

Public Properties ​

PropertyDescription
attributesarray – PDO attributes (name => value) that should be set when calling open() to establish a DB connection.
backupFilePathstring
behaviorsyii\base\Behavior – List of behaviors attached to this component.
charsetstring, null – The charset used for database connection.
commandClassstring – The class used to create new database yii\db\Command objects.
commandMaparray – Mapping between PDO driver names and yii\db\Command classes.
driverLabelstring
driverNamestring, null – Name of the DB driver.
dsnstring – The Data Source Name, or DSN, contains the information required to connect to the database.
emulatePrepareboolean, null – Whether to turn on prepare emulation.
enableLoggingboolean – Whether to enable logging of database queries.
enableProfilingboolean – Whether to enable profiling of opening database connection and database queries.
enableQueryCacheboolean – Whether to enable query caching.
enableReplicasboolean – whether to enable read/write splitting by using replicas to read data.
enableSavepointboolean – Whether to enable savepoint.
enableSchemaCacheboolean – Whether to enable schema caching.
enableSlavesboolean – Whether to enable read/write splitting by using slaves to read data.
foreignKeyNamestring
ignoredBackupTablesstring[]
indexNamestring
isActiveboolean – Whether the DB connection is established.
isMariaboolean
isMysqlboolean
isPgsqlboolean
isSybaseboolean – If the database connected via pdo_dblib is SyBase.
lastInsertIDstring – The row ID of the last row inserted, or the last value retrieved from the sequence object.
masteryii\db\Connection, null – The currently active master connection.
masterConfigarray – The configuration that should be merged with every master configuration listed in masters.
masterPdoPDO – The PDO instance for the currently active master connection.
mastersarray – List of master connection configurations.
passwordstring, null – The password for establishing DB connection.
pdoPDO, null – The PHP PDO instance associated with this DB connection.
pdoClassstring, null – Custom PDO wrapper class.
primariesarray – list of primary connection configurations.
primaryyii\db\Connection, null – The currently active primary connection.
primaryConfigarray – the configuration that should be merged with every primary configuration listed in primaries.
primaryKeyNamestring
primaryPdoPDO – The PDO instance for the currently active primary connection.
queryBuildercraft\db\mysql\QueryBuilder, craft\db\pgsql\QueryBuilder – The query builder for the current DB connection.
queryCacheyii\caching\CacheInterface, string – The cache object or the ID of the cache application component that is used for query caching.
queryCacheDurationinteger – The default number of seconds that query results can remain valid in cache.
replicayii\db\Connection – The currently active replica connection.
replicaConfigarray – the configuration that should be merged with every replica configuration listed in replicas.
replicaPdoPDO – The PDO instance for the currently active replica connection.
replicasarray – list of replica connection configurations.
schemacraft\db\mysql\Schema, craft\db\pgsql\Schema – The schema information for the database opened by this connection.
schemaCacheyii\caching\CacheInterface, string – The cache object or the ID of the cache application component that is used to cache the table metadata.
schemaCacheDurationinteger – Number of seconds that table metadata can remain valid in cache.
schemaCacheExcludearray – List of tables whose metadata should NOT be cached.
schemaMaparray – Mapping between PDO driver names and yii\db\Schema classes.
serverRetryIntervalinteger – The retry interval in seconds for dead servers listed in masters and slaves.
serverStatusCacheyii\caching\CacheInterface, string, false – 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.
serverVersionstring – Server version as a string.
shuffleMastersboolean – Whether to shuffle masters before getting one.
shufflePrimariesboolean – whether to shuffle primaries before getting one.
slaveyii\db\Connection, null – The currently active slave connection.
slaveConfigarray – The configuration that should be merged with every slave configuration listed in slaves.
slavePdoPDO, null – The PDO instance for the currently active slave connection.
slavesarray – List of slave connection configurations.
supportsMb4boolean – Whether the database supports 4+ byte characters.
tablePrefixstring – The common prefix or suffix for table names.
transactionyii\db\Transaction, null – The currently active transaction.
usernamestring, null – The username for establishing DB connection.

backupFilePath ​

Type
string
Default value
null
Access
Read-only
Since
3.0.38

View source

driverLabel ​

Type
string
Default value
null
Access
Read-only
Since
4.4.1

View source

foreignKeyName ​

Type
string
Default value
null
Access
Read-only

View source

ignoredBackupTables ​

Type
string[]
Default value
null
Access
Read-only

View source

indexName ​

Type
string
Default value
null
Access
Read-only

View source

isMaria ​

Type
boolean
Default value
null
Access
Read-only
Since
5.0.0

View source

isMysql ​

Type
boolean
Default value
null
Access
Read-only

View source

isPgsql ​

Type
boolean
Default value
null
Access
Read-only

View source

primaryKeyName ​

Type
string
Default value
null
Access
Read-only

View source

queryBuilder ​

Type
craft\db\mysql\QueryBuilder, craft\db\pgsql\QueryBuilder
Default value
null

The query builder for the current DB connection.

View source

schema ​

Type
craft\db\mysql\Schema, craft\db\pgsql\Schema
Default value
null

The schema information for the database opened by this connection.

View source

supportsMb4 ​

Type
boolean
Default value
null

Whether the database supports 4+ byte characters.

View source

Public Methods ​

MethodDescription
__call()Calls the named method which is not a class method.
__clone()Reset the connection after cloning.
__construct()Constructor.
__get()Returns the value of a component property.
__isset()Checks if a property is set, i.e. defined and not null.
__set()Sets the value of a component property.
__sleep()Close the connection before serializing.
__unset()Sets a component property to be null.
attachBehavior()Attaches a behavior to this component.
attachBehaviors()Attaches a list of behaviors to the component.
backup()Performs a backup operation. If a backupCommand config setting has been set, will execute it. If not, will execute the default database schema specific backup defined in getDefaultBackupCommand(), which uses pg_dump for PostgreSQL and mysqldump for MySQL.
backupTo()Performs a backup operation. If a backupCommand config setting has been set, will execute it. If not, will execute the default database schema specific backup defined in getDefaultBackupCommand(), which uses pg_dump for PostgreSQL and mysqldump for MySQL.
beginTransaction()Starts a transaction.
behaviors()Returns a list of behaviors that this component should behave as.
cache()Uses query cache for the queries performed with the callable.
canGetProperty()Returns a value indicating whether a property can be read.
canSetProperty()Returns a value indicating whether a property can be set.
className()Returns the fully qualified name of this class.
close()Closes the currently active DB connection.
columnExists()Checks if a column exists in a table.
createCommand()Creates a command for execution.
detachBehavior()Detaches a behavior from the component.
detachBehaviors()Detaches all behaviors from the component.
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.
getBackupFilePath()Returns the path for a new backup file.
getBehavior()Returns the named behavior object.
getBehaviors()Returns all behaviors attached to this component.
getDriverLabel()Returns the human-facing driver label (MySQL, MariaDB, or PostgreSQL).
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.
getForeignKeyName()Generates a foreign key name.
getIgnoredBackupTables()Returns the core table names whose data should be excluded from database backups.
getIndexName()Generates an index name.
getIsActive()Returns a value indicating whether the DB connection is established.
getIsMaria()Returns whether this is a MariaDB connection.
getIsMysql()Returns whether this is a MySQL (or MySQL-like) connection.
getIsPgsql()Returns whether this is a PostgreSQL connection.
getLastInsertID()Returns the ID of the last inserted row or sequence value.
getMaster()Returns the currently active master connection.
getMasterPdo()Returns the PDO instance for the currently active master connection.
getPrimary()Returns the currently active primary connection.
getPrimaryKeyName()Generates a primary key name.
getPrimaryPdo()Returns the PDO instance for the currently active primary connection.
getQueryBuilder()Returns the query builder for the current DB connection.
getReplica()Returns the currently active replica connection.
getReplicaPdo()Returns the PDO instance for the currently active replica connection.
getSchema()Returns the schema information for the database opened by this connection.
getServerVersion()Returns a server version as a string comparable by \version_compare().
getSlave()Returns the currently active slave connection.
getSlavePdo()Returns the PDO instance for the currently active slave connection.
getSupportsMb4()Returns whether the database supports 4+ byte characters.
getTableSchema()Obtains the schema information for the named table.
getTransaction()Returns the currently active transaction.
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.
hasMethod()Returns a value indicating whether a method is defined.
hasProperty()Returns a value indicating whether a property is defined for this component.
init()Initializes the object.
noCache()Disables query cache temporarily.
off()Detaches an existing event handler from this component.
on()Attaches an event handler to an event.
onAfterTransaction()Invokes a callback function once the connection is no longer in a transaction.
open()Establishes a DB connection.
quoteColumnName()Quotes a column name for use in a query.
quoteDatabaseName()
quoteSql()Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
quoteTableName()Quotes a table name for use in a query.
quoteValue()Quotes a string value for use in a query.
restore()Restores a database at the given file path.
setDriverName()Changes the current driver name.
setQueryBuilder()Can be used to set yii\db\QueryBuilder configuration via Connection configuration array.
setSupportsMb4()Sets whether the database supports 4+ byte characters.
tableExists()Returns whether a table exists.
transaction()Executes callback provided in a transaction.
trigger()Triggers an event.
useMaster()Executes the provided callback by using the master connection.
usePrimary()Executes the provided callback by using the primary connection.

backup() ​

Performs a backup operation. If a backupCommand config setting has been set, will execute it. If not, will execute the default database schema specific backup defined in getDefaultBackupCommand(), which uses pg_dump for PostgreSQL and mysqldump for MySQL.

View source

Returns ​

string – The file path to the database backup

Throws ​

backupTo() ​

Performs a backup operation. If a backupCommand config setting has been set, will execute it. If not, will execute the default database schema specific backup defined in getDefaultBackupCommand(), which uses pg_dump for PostgreSQL and mysqldump for MySQL.

View source

Arguments ​

  • $filePath (string) – The file path the database backup should be saved at

Throws ​

close() ​

Since
3.4.11

Closes the currently active DB connection.

It does nothing if the connection is already closed.

View source

columnExists() ​

Checks if a column exists in a table.

View source

Arguments ​

Returns ​

boolean

Throws ​

createCommand() ​

Creates a command for execution.

View source

Arguments ​

  • $sql
  • $params

Returns ​

craft\db\Command –

getBackupFilePath() ​

Since
3.0.38

Returns the path for a new backup file.

View source

Returns ​

string

getDriverLabel() ​

Since
4.4.1

Returns the human-facing driver label (MySQL, MariaDB, or PostgreSQL).

View source

Returns ​

string

getForeignKeyName() ​

Generates a foreign key name.

View source

Returns ​

string

getIgnoredBackupTables() ​

Returns the core table names whose data should be excluded from database backups.

View source

Returns ​

string[]

getIndexName() ​

Generates an index name.

View source

Returns ​

string

getIsMaria() ​

Since
5.0.0

Returns whether this is a MariaDB connection.

View source

Returns ​

boolean

getIsMysql() ​

Returns whether this is a MySQL (or MySQL-like) connection.

View source

Returns ​

boolean

getIsPgsql() ​

Returns whether this is a PostgreSQL connection.

View source

Returns ​

boolean

getPrimaryKeyName() ​

Generates a primary key name.

View source

Returns ​

string

getQueryBuilder() ​

Returns the query builder for the current DB connection.

View source

Returns ​

craft\db\mysql\QueryBuilder, craft\db\pgsql\QueryBuilder –

getSchema() ​

Returns the schema information for the database opened by this connection.

View source

Returns ​

craft\db\mysql\Schema, craft\db\pgsql\Schema –

getSupportsMb4() ​

Returns whether the database supports 4+ byte characters.

View source

Returns ​

boolean

getTableSchema() ​

Obtains the schema information for the named table.

View source

Arguments ​

  • $name
  • $refresh

Returns ​

craft\db\TableSchema, null –

onAfterTransaction() ​

Since
4.5.12

Invokes a callback function once the connection is no longer in a transaction.

If no transaction is currently active, the callback will be invoked immediately.

View source

Arguments ​

open() ​

Establishes a DB connection.

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

View source

Throws ​

quoteDatabaseName() ​

View source

Arguments ​

Returns ​

string

restore() ​

Restores a database at the given file path.

View source

Arguments ​

  • $filePath (string) – The path of the database backup to restore.

Throws ​

setSupportsMb4() ​

Sets whether the database supports 4+ byte characters.

View source

Arguments ​

tableExists() ​

Returns whether a table exists.

View source

Arguments ​

Returns ​

boolean

trigger() ​

Triggers an event.

This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.

View source

Arguments ​

Protected Methods ​

MethodDescription
createPdoInstance()Creates the PDO instance.
initConnection()Initializes the DB connection.
openFromPool()Opens the connection to a server in the pool.
openFromPoolSequentially()Opens the connection to a server in the pool.

Constants ​

ConstantDescription
DRIVER_MYSQL
DRIVER_PGSQL

Events ​

EVENT_AFTER_CREATE_BACKUP ​

Type
craft\events\BackupEvent

The event that is triggered after the backup is created.


EVENT_AFTER_RESTORE_BACKUP ​

Type
craft\events\RestoreEvent

The event that is triggered after the restore occurred.


EVENT_BEFORE_CREATE_BACKUP ​

Type
craft\events\BackupEvent

The event that is triggered before the backup is created.


EVENT_BEFORE_RESTORE_BACKUP ​

Type
craft\events\RestoreEvent

The event that is triggered before the restore is started.