Class Connection
Represents a connection with a database server.
Properties summary
- $_config protected
array
Contains the configuration params for this connection.
- $_driver protected
\Cake\Database\DriverInterface
Driver object, responsible for creating the real connection and provide specific SQL dialect.
- $_logQueries protected
bool
Whether to log queries generated during this connection.
- $_logger protected
\Psr\Log\LoggerInterface|null
Logger object instance.
- $_schemaCollection protected
\Cake\Database\Schema\CollectionInterface|null
The schema collection object
- $_transactionLevel protected
int
Contains how many nested transactions have been started.
- $_transactionStarted protected
bool
Whether a transaction is active in this connection.
- $_useSavePoints protected
bool
Whether this connection can and should use savepoints for nested transactions.
- $cacher protected
\Psr\SimpleCache\CacheInterface|null
Cacher object instance.
- $nestedTransactionRollbackException protected
\Cake\Database\Exception\NestedTransactionRollbackException|null
NestedTransactionRollbackException object instance, will be stored if the rollback method is called in some nested transaction.
Method Summary
- __debugInfo() public
Returns an array that can be used to describe the internal state of this object.
- _newLogger() protected
Returns a new statement object that will log the activity for the passed original statement instance.
- cast() public
Converts a give value to a suitable database value based on type and return relevant internal statement type
- compileQuery() public
Compiles a Query object into a SQL string according to the dialect for this connection's driver
- enableSavePoints() public
Enables/disables the usage of savepoints, enables only if driver the allows it.
- execute() public
Executes a query using $params for interpolating values and $types as a hint for each those params.
- getDisconnectRetry() public
Get the retry wrapper object that is allows recovery from server disconnects while performing certain database actions, such as executing a query.
- isSavePointsEnabled() public
Returns whether this connection is using savepoints for nested transactions
- quoteIdentifier() public
Quotes a database identifier (a column name, table name, etc..) to be used safely in queries without the risk of using reserved words.
- run() public
Executes the provided query after compiling it for the specific driver dialect and returns the executed Statement object.
- setDriver() public
Sets the driver instance. If a string is passed it will be treated as a class name and will be instantiated.
- supportsDynamicConstraints() public
Returns whether the driver supports adding or dropping constraints to already created tables.
- transactional() public
Executes a callable function inside a transaction, if any exception occurs while executing the passed callable, the transaction will be rolled back If the result of the callable function is
false
, the transaction will also be rolled back. Otherwise the transaction is committed after executing the callback. - wasNestedTransactionRolledback() protected
Returns whether some nested transaction has been already rolled back.
Method Detail
__construct() public
__construct(array $config)
Constructor.
Available options:
-
driver
Sort name or FCQN for driver. -
log
Boolean indicating whether to use query logging. -
name
Connection name. -
cacheMetaData
Boolean indicating whether metadata (datasource schemas) should be cached. If set to a string it will be used as the name of cache config to use. -
cacheKeyPrefix
Custom prefix to use when generation cache keys. Defaults to connection name.
Parameters
-
array
$config Configuration array.
__debugInfo() public
__debugInfo()
Returns an array that can be used to describe the internal state of this object.
Returns
array
__destruct() public
__destruct()
Destructor
Disconnects the driver to release the connection.
_newLogger() protected
_newLogger(\Cake\Database\StatementInterface $statement)
Returns a new statement object that will log the activity for the passed original statement instance.
Parameters
-
\Cake\Database\StatementInterface
$statement the instance to be decorated
Returns
\Cake\Database\Log\LoggingStatement
begin() public
begin()
Starts a new transaction.
cacheMetadata() public
cacheMetadata(mixed $cache)
Enables or disables metadata caching for this connection
Changing this setting will not modify existing schema collections objects.
Parameters
-
bool|string
$cache Either boolean false to disable metadata caching, or true to use
_cake_model_
or the name of the cache config to use.
cast() public
cast(mixed $value, mixed $type)
Converts a give value to a suitable database value based on type and return relevant internal statement type
Parameters
-
mixed
$value The value to cast
-
\Cake\Database\TypeInterface|string|int
$type optional The type name or type instance to use.
Returns
array
list containing converted value and internal type
commit() public
commit()
Commits current transaction.
Returns
bool
true on success, false otherwise
compileQuery() public
compileQuery(\Cake\Database\Query $query, \Cake\Database\ValueBinder $generator)
Compiles a Query object into a SQL string according to the dialect for this connection's driver
Parameters
-
\Cake\Database\Query
$query The query to be compiled
-
\Cake\Database\ValueBinder
$generator The placeholder generator to use
Returns
string
config() public
config()
Get the configuration data used to create the connection.
Returns
array
configName() public
configName()
Get the configuration name for this connection.
Returns
string
connect() public
connect()
Connects to the configured database.
Returns
bool
true, if the connection was already established or the attempt was successful.
Throws
Cake\Database\Exception\MissingConnectionException
If database connection could not be established.
createSavePoint() public
createSavePoint(mixed $name)
Creates a new save point for nested transactions.
Parameters
-
string|int
$name The save point name.
delete() public
delete(string $table, array $conditions, array $types)
Executes a DELETE statement on the specified table.
Parameters
-
string
$table the table to delete rows from
-
array
$conditions optional conditions to be set for delete statement
-
array
$types optional list of associative array containing the types to be used for casting
Returns
\Cake\Database\StatementInterface
disableConstraints() public
disableConstraints(callable $callback)
Run an operation with constraints disabled.
Constraints should be re-enabled after the callback succeeds/fails.
Example:
$connection->disableConstraints(function ($connection) { $connection->newQuery()->delete('users')->execute(); });
Parameters
-
callable
$callback The callback to execute within a transaction.
Returns
mixed
The return value of the callback.
Throws
Exception
Will re-throw any exception raised in $callback after rolling back the transaction.
disableForeignKeys() public
disableForeignKeys()
Run driver specific SQL to disable foreign key checks.
disableQueryLogging() public
disableQueryLogging()
Disable query logging
Returns
$this
disableSavePoints() public
disableSavePoints()
Disables the usage of savepoints.
Returns
$this
disconnect() public
disconnect()
Disconnects from database server.
enableForeignKeys() public
enableForeignKeys()
Run driver specific SQL to enable foreign key checks.
enableQueryLogging() public
enableQueryLogging(bool $enable)
Enable/disable query logging
Parameters
-
bool
$enable optional Enable/disable query logging
Returns
$this
enableSavePoints() public
enableSavePoints(bool $enable)
Enables/disables the usage of savepoints, enables only if driver the allows it.
If you are trying to enable this feature, make sure you check the return value of this function to verify it was enabled successfully.
Example:
$connection->enableSavePoints(true)
Returns true if drivers supports save points, false otherwise $connection->enableSavePoints(false)
Disables usage of savepoints and returns false
Parameters
-
bool
$enable optional Whether or not save points should be used.
Returns
$this
execute() public
execute(string $sql, array $params, array $types)
Executes a query using $params for interpolating values and $types as a hint for each those params.
Parameters
-
string
$sql SQL to be executed and interpolated with $params
-
array
$params optional list or associative array of params to be interpolated in $sql as values
-
array
$types optional list or associative array of types to be used for casting values in query
Returns
\Cake\Database\StatementInterface
executed statement
getCacher() public
getCacher()
Get a cacher.
Returns
\Psr\SimpleCache\CacheInterface
$cacher Cacher object
getDisconnectRetry() public
getDisconnectRetry()
Get the retry wrapper object that is allows recovery from server disconnects while performing certain database actions, such as executing a query.
Returns
\Cake\Core\Retry\CommandRetry
The retry wrapper
getDriver() public
getDriver()
Gets the driver instance.
Returns
\Cake\Database\DriverInterface
getLogger() public
getLogger()
Gets the logger object
Returns
\Psr\Log\LoggerInterface
logger instance
getSchemaCollection() public
getSchemaCollection()
Gets a Schema\Collection object for this connection.
Returns
\Cake\Database\Schema\CollectionInterface
inTransaction() public
inTransaction()
Checks if a transaction is running.
Returns
bool
True if a transaction is running else false.
insert() public
insert(string $table, array $values, array $types)
Executes an INSERT query on the specified table.
Parameters
-
string
$table the table to insert values in
-
array
$values values to be inserted
-
array
$types optional list of associative array containing the types to be used for casting
Returns
\Cake\Database\StatementInterface
isConnected() public
isConnected()
Returns whether connection to database server was already established.
Returns
bool
isQueryLoggingEnabled() public
isQueryLoggingEnabled()
Check if query logging is enabled.
Returns
bool
isSavePointsEnabled() public
isSavePointsEnabled()
Returns whether this connection is using savepoints for nested transactions
Returns
bool
true if enabled, false otherwise
log() public
log(string $sql)
Logs a Query string using the configured logger object.
Parameters
-
string
$sql string to be logged
matchTypes() public
matchTypes(array $columns, array $types)
Matches columns to corresponding types
Both $columns and $types should either be numeric based or string key based at the same time.
Parameters
-
array
$columns list or associative array of columns and parameters to be bound with types
-
array
$types list or associative array of types
Returns
array
newQuery() public
newQuery()
Create a new Query instance for this connection.
Returns
\Cake\Database\Query
prepare() public
prepare(mixed $query)
Prepares a SQL statement to be executed.
Parameters
-
string|\Cake\Database\Query
$query The SQL to convert into a prepared statement.
Returns
\Cake\Database\StatementInterface
query() public
query(string $sql)
Executes a SQL statement and returns the Statement object as result.
Parameters
-
string
$sql The SQL query to execute.
Returns
\Cake\Database\StatementInterface
quote() public
quote(mixed $value, mixed $type)
Quotes value to be used safely in database query.
Parameters
-
mixed
$value The value to quote.
-
string|int|\Cake\Database\TypeInterface
$type optional Type to be used for determining kind of quoting to perform
Returns
string
Quoted value
quoteIdentifier() public
quoteIdentifier(string $identifier)
Quotes a database identifier (a column name, table name, etc..) to be used safely in queries without the risk of using reserved words.
Parameters
-
string
$identifier The identifier to quote.
Returns
string
releaseSavePoint() public
releaseSavePoint(mixed $name)
Releases a save point by its name.
Parameters
-
string|int
$name The save point name.
rollback() public
rollback(?bool $toBeginning)
Rollback current transaction.
Parameters
-
bool|null
$toBeginning optional Whether or not the transaction should be rolled back to the beginning of it. Defaults to false if using savepoints, or true if not.
Returns
bool
rollbackSavepoint() public
rollbackSavepoint(mixed $name)
Rollback a save point by its name.
Parameters
-
string|int
$name The save point name.
run() public
run(\Cake\Database\Query $query)
Executes the provided query after compiling it for the specific driver dialect and returns the executed Statement object.
Parameters
-
\Cake\Database\Query
$query The query to be executed
Returns
\Cake\Database\StatementInterface
executed statement
setCacher() public
setCacher(\Psr\SimpleCache\CacheInterface $cacher)
Set a cacher.
Parameters
-
\Psr\SimpleCache\CacheInterface
$cacher Cacher object
Returns
$this
setDriver() public
setDriver(mixed $driver, mixed $config)
Sets the driver instance. If a string is passed it will be treated as a class name and will be instantiated.
Parameters
-
\Cake\Database\DriverInterface|string
$driver The driver instance to use.
-
array
$config optional Config for a new driver.
Returns
$this
Throws
Cake\Database\Exception\MissingDriverException
When a driver class is missing.
Cake\Database\Exception\MissingExtensionException
When a driver's PHP extension is missing.
setLogger() public
setLogger(\Psr\Log\LoggerInterface $logger)
Sets a logger
Parameters
-
\Psr\Log\LoggerInterface
$logger Logger object
Returns
$this
setSchemaCollection() public
setSchemaCollection(\Cake\Database\Schema\CollectionInterface $collection)
Sets a Schema\Collection object for this connection.
Parameters
-
\Cake\Database\Schema\CollectionInterface
$collection The schema collection object
Returns
$this
supportsDynamicConstraints() public
supportsDynamicConstraints()
Returns whether the driver supports adding or dropping constraints to already created tables.
Returns
bool
true if driver supports dynamic constraints
supportsQuoting() public
supportsQuoting()
Checks if the driver supports quoting.
Returns
bool
transactional() public
transactional(callable $callback)
Executes a callable function inside a transaction, if any exception occurs while executing the passed callable, the transaction will be rolled back If the result of the callable function is false
, the transaction will also be rolled back. Otherwise the transaction is committed after executing the callback.
The callback will receive the connection instance as its first argument.
Example:
$connection->transactional(function ($connection) { $connection->newQuery()->delete('users')->execute(); });
Parameters
-
callable
$callback The callback to execute within a transaction.
Returns
mixed
The return value of the callback.
Throws
Exception
Will re-throw any exception raised in $callback after rolling back the transaction.
update() public
update(string $table, array $values, array $conditions, array $types)
Executes an UPDATE statement on the specified table.
Parameters
-
string
$table the table to update rows from
-
array
$values values to be updated
-
array
$conditions optional conditions to be set for update statement
-
array
$types optional list of associative array containing the types to be used for casting
Returns
\Cake\Database\StatementInterface
wasNestedTransactionRolledback() protected
wasNestedTransactionRolledback()
Returns whether some nested transaction has been already rolled back.
Returns
bool
Property Detail
$_config protected
Contains the configuration params for this connection.
Type
array
$_driver protected
Driver object, responsible for creating the real connection and provide specific SQL dialect.
Type
\Cake\Database\DriverInterface
$_logQueries protected
Whether to log queries generated during this connection.
Type
bool
$_logger protected
Logger object instance.
Type
\Psr\Log\LoggerInterface|null
$_schemaCollection protected
The schema collection object
Type
\Cake\Database\Schema\CollectionInterface|null
$_transactionLevel protected
Contains how many nested transactions have been started.
Type
int
$_transactionStarted protected
Whether a transaction is active in this connection.
Type
bool
$_useSavePoints protected
Whether this connection can and should use savepoints for nested transactions.
Type
bool
$cacher protected
Cacher object instance.
Type
\Psr\SimpleCache\CacheInterface|null
$nestedTransactionRollbackException protected
NestedTransactionRollbackException object instance, will be stored if the rollback method is called in some nested transaction.
Type
\Cake\Database\Exception\NestedTransactionRollbackException|null
© 2005–present The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
https://api.cakephp.org/4.1/class-Cake.Database.Connection.html