Class Connection
Represents a connection with a database server.
Property Summary
-
$_config protected
array<string, mixed>Contains the configuration params for this connection.
-
$_logQueries protected
boolWhether to log queries generated during this connection.
-
$_logger protected
Psr\Log\LoggerInterface|nullLogger object instance.
-
$_schemaCollection protected
Cake\Database\Schema\CollectionInterface|nullThe schema collection object
-
$_transactionLevel protected
intContains how many nested transactions have been started.
-
$_transactionStarted protected
boolWhether a transaction is active in this connection.
-
$_useSavePoints protected
boolWhether this connection can and should use savepoints for nested transactions.
-
$cacher protected
Psr\SimpleCache\CacheInterface|nullCacher object instance.
-
$nestedTransactionRollbackException protected
Cake\Database\Exception\NestedTransactionRollbackException|nullNestedTransactionRollbackException object instance, will be stored if the rollback method is called in some nested transaction.
-
$readDriver protected
Cake\Database\DriverInterface -
$writeDriver protected
Cake\Database\DriverInterface
Method Summary
-
__construct() public
Constructor.
-
__debugInfo() public
Returns an array that can be used to describe the internal state of this object.
-
__destruct() public
Destructor
-
_newLogger() protected
Returns a new statement object that will log the activity for the passed original statement instance.
-
begin() public
Starts a new transaction.
-
cacheMetadata() public
Enables or disables metadata caching for this connection
-
cast() public
Converts a give value to a suitable database value based on type and return relevant internal statement type
-
commit() public
Commits current transaction.
-
compileQuery() public deprecated
Compiles a Query object into a SQL string according to the dialect for this connection's driver
-
config() public
Get the configuration data used to create the connection.
-
configName() public
Get the configuration name for this connection.
-
connect() public deprecated
Connects to the configured database.
-
createDriver() protected
Creates driver from name, class name or instance.
-
createDrivers() protected
Creates read and write drivers.
-
createSavePoint() public
Creates a new save point for nested transactions.
-
delete() public
Executes a DELETE statement on the specified table.
-
deleteQuery() public
Create a new DeleteQuery instance for this connection.
-
disableConstraints() public
Run an operation with constraints disabled.
-
disableForeignKeys() public
Run driver specific SQL to disable foreign key checks.
-
disableQueryLogging() public deprecated
Disable query logging
-
disableSavePoints() public
Disables the usage of savepoints.
-
disconnect() public deprecated
Disconnects from database server.
-
enableForeignKeys() public
Run driver specific SQL to enable foreign key checks.
-
enableQueryLogging() public deprecated
Enable/disable query logging
-
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.
-
getCacher() public
Get a cacher.
-
getDisconnectRetry() public
Get the retry wrapper object that is allows recovery from server disconnects while performing certain database actions, such as executing a query.
-
getDriver() public
Gets the driver instance.
-
getLogger() public
Gets the logger object
-
getSchemaCollection() public
Gets a Schema\Collection object for this connection.
-
inTransaction() public
Checks if a transaction is running.
-
insert() public
Executes an INSERT query on the specified table.
-
insertQuery() public
Create a new InsertQuery instance for this connection.
-
isConnected() public deprecated
Returns whether connection to database server was already established.
-
isQueryLoggingEnabled() public deprecated
Check if query logging is enabled.
-
isSavePointsEnabled() public
Returns whether this connection is using savepoints for nested transactions
-
log() public
Logs a Query string using the configured logger object.
-
matchTypes() public
Matches columns to corresponding types
-
newQuery() public deprecated
Create a new Query instance for this connection.
-
prepare() public deprecated
Prepares a SQL statement to be executed.
-
query() public deprecated
Executes a SQL statement and returns the Statement object as result.
-
quote() public deprecated
Quotes value to be used safely in database query.
-
quoteIdentifier() public deprecated
Quotes a database identifier (a column name, table name, etc..) to be used safely in queries without the risk of using reserved words.
-
releaseSavePoint() public
Releases a save point by its name.
-
role() public
Returns the connection role: read or write.
-
rollback() public
Rollback current transaction.
-
rollbackSavepoint() public
Rollback a save point by its name.
-
run() public
Executes the provided query after compiling it for the specific driver dialect and returns the executed Statement object.
-
selectQuery() public
Create a new SelectQuery instance for this connection.
-
setCacher() public
Set a cacher.
-
setDriver() public deprecated
Sets the driver instance. If a string is passed it will be treated as a class name and will be instantiated.
-
setLogger() public
Sets a logger
-
setSchemaCollection() public
Sets a Schema\Collection object for this connection.
-
supportsDynamicConstraints() public deprecated
Returns whether the driver supports adding or dropping constraints to already created tables.
-
supportsQuoting() public deprecated
Checks if using
quote()is supported. -
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. -
update() public
Executes an UPDATE statement on the specified table.
-
updateQuery() public
Create a new UpdateQuery instance for this connection.
-
wasNestedTransactionRolledback() protected
Returns whether some nested transaction has been already rolled back.
Method Detail
__construct() ¶ public
__construct(array<string, mixed> $config)
Constructor.
Available options:
driverSort name or FCQN for driver.logBoolean indicating whether to use query logging.nameConnection name.cacheMetaDataBoolean 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.cacheKeyPrefixCustom prefix to use when generation cache keys. Defaults to connection name.
Parameters
-
array<string, mixed>$config Configuration array.
__debugInfo() ¶ public
__debugInfo(): array<string, mixed>
Returns an array that can be used to describe the internal state of this object.
Returns
array<string, mixed>_newLogger() ¶ protected
_newLogger(Cake\Database\StatementInterface $statement): Cake\Database\Log\LoggingStatement
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\LoggingStatementcacheMetadata() ¶ public
cacheMetadata(string|bool $cache): void
Enables or disables metadata caching for this connection
Changing this setting will not modify existing schema collections objects.
Parameters
-
string|bool$cache Either boolean false to disable metadata caching, or true to use
_cake_model_or the name of the cache config to use.
Returns
voidcast() ¶ public
cast(mixed $value, Cake\Database\TypeInterface|string|int $type = 'string'): array
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
arraycompileQuery() ¶ public
compileQuery(Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
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$binder Value binder
Returns
stringconfig() ¶ public
config(): array<string, mixed>
Get the configuration data used to create the connection.
Returns
array<string, mixed>configName() ¶ public
configName(): string
Get the configuration name for this connection.
Returns
stringconnect() ¶ public
connect(): bool
Connects to the configured database.
Returns
boolThrows
Cake\Database\Exception\MissingConnectionExceptionIf database connection could not be established.
createDriver() ¶ protected
createDriver(Cake\Database\DriverInterface|string $name, array $config): Cake\Database\DriverInterface
Creates driver from name, class name or instance.
Parameters
-
Cake\Database\DriverInterface|string$name Driver name, class name or instance.
-
array$config Driver config if $name is not an instance.
Returns
Cake\Database\DriverInterfaceThrows
Cake\Database\Exception\MissingDriverExceptionWhen a driver class is missing.
Cake\Database\Exception\MissingExtensionExceptionWhen a driver's PHP extension is missing.
createDrivers() ¶ protected
createDrivers(array $config): array<string, \Cake\Database\DriverInterface>
Creates read and write drivers.
Parameters
-
array$config Connection config
Returns
array<string, \Cake\Database\DriverInterface>createSavePoint() ¶ public
createSavePoint(string|int $name): void
Creates a new save point for nested transactions.
Parameters
-
string|int$name Save point name or id
Returns
voiddelete() ¶ public
delete(string $table, array $conditions = [], array<string> $types = []): Cake\Database\StatementInterface
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<string>$types optional list of associative array containing the types to be used for casting
Returns
Cake\Database\StatementInterfacedeleteQuery() ¶ public
deleteQuery(string|null $table = null, array $conditions = [], array<string, string> $types = []): Cake\Database\Query\DeleteQuery
Create a new DeleteQuery instance for this connection.
Parameters
-
string|null$table optional The table to delete rows from.
-
array$conditions optional Conditions to be set for the delete statement.
-
array<string, string>$types optional Associative array containing the types to be used for casting.
Returns
Cake\Database\Query\DeleteQuerydisableConstraints() ¶ public
disableConstraints(callable $callback): mixed
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
Returns
mixeddisableForeignKeys() ¶ public
disableForeignKeys(): void
Run driver specific SQL to disable foreign key checks.
Returns
voiddisableSavePoints() ¶ public
disableSavePoints(): $this
Disables the usage of savepoints.
Returns
$thisenableForeignKeys() ¶ public
enableForeignKeys(): void
Run driver specific SQL to enable foreign key checks.
Returns
voidenableQueryLogging() ¶ public
enableQueryLogging(bool $enable = true): $this
Enable/disable query logging
Parameters
-
bool$enable optional Enable/disable query logging
Returns
$thisenableSavePoints() ¶ public
enableSavePoints(bool $enable = true): $this
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
isSavePointsEnabled() to verify that savepoints were enabled successfully.
Parameters
-
bool$enable optional Whether save points should be used.
Returns
$thisexecute() ¶ public
execute(string $sql, array $params = [], array $types = []): Cake\Database\StatementInterface
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\StatementInterfacegetCacher() ¶ public
getCacher(): Psr\SimpleCache\CacheInterface
Get a cacher.
Returns
Psr\SimpleCache\CacheInterfacegetDisconnectRetry() ¶ public
getDisconnectRetry(): Cake\Core\Retry\CommandRetry
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\CommandRetrygetDriver() ¶ public
getDriver(string $role = self::ROLE_WRITE): Cake\Database\DriverInterface
Gets the driver instance.
Parameters
-
string$role optional Connection role ('read' or 'write')
Returns
Cake\Database\DriverInterfacegetLogger() ¶ public
getLogger(): Psr\Log\LoggerInterface
Gets the logger object
Returns
Psr\Log\LoggerInterfacegetSchemaCollection() ¶ public
getSchemaCollection(): Cake\Database\Schema\CollectionInterface
Gets a Schema\Collection object for this connection.
Returns
Cake\Database\Schema\CollectionInterfaceinsert() ¶ public
insert(string $table, array $values, array<int|string, string> $types = []): Cake\Database\StatementInterface
Executes an INSERT query on the specified table.
Parameters
-
string$table the table to insert values in
-
array$values values to be inserted
-
array<int|string, string>$types optional Array containing the types to be used for casting
Returns
Cake\Database\StatementInterfaceinsertQuery() ¶ public
insertQuery(string|null $table = null, array $values = [], array<int|string, string> $types = []): Cake\Database\Query\InsertQuery
Create a new InsertQuery instance for this connection.
Parameters
-
string|null$table optional The table to insert rows into.
-
array$values optional Associative array of column => value to be inserted.
-
array<int|string, string>$types optional Associative array containing the types to be used for casting.
Returns
Cake\Database\Query\InsertQueryisConnected() ¶ public
isConnected(): bool
Returns whether connection to database server was already established.
Returns
boolisQueryLoggingEnabled() ¶ public
isQueryLoggingEnabled(): bool
Check if query logging is enabled.
Returns
boolisSavePointsEnabled() ¶ public
isSavePointsEnabled(): bool
Returns whether this connection is using savepoints for nested transactions
Returns
boollog() ¶ public
log(string $sql): void
Logs a Query string using the configured logger object.
Parameters
-
string$sql string to be logged
Returns
voidmatchTypes() ¶ public
matchTypes(array $columns, array $types): array
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
arraynewQuery() ¶ public
newQuery(): Cake\Database\Query
Create a new Query instance for this connection.
Returns
Cake\Database\Queryprepare() ¶ public
prepare(Cake\Database\Query|string $query): Cake\Database\StatementInterface
Prepares a SQL statement to be executed.
Parameters
-
Cake\Database\Query|string$query The SQL to convert into a prepared statement.
Returns
Cake\Database\StatementInterfacequery() ¶ public
query(string $sql): Cake\Database\StatementInterface
Executes a SQL statement and returns the Statement object as result.
Parameters
-
string$sql The SQL query to execute.
Returns
Cake\Database\StatementInterfacequote() ¶ public
quote(mixed $value, Cake\Database\TypeInterface|string|int $type = 'string'): string
Quotes value to be used safely in database query.
This uses PDO::quote() and requires supportsQuoting() to work.
Parameters
-
mixed$value The value to quote.
-
Cake\Database\TypeInterface|string|int$type optional Type to be used for determining kind of quoting to perform
Returns
stringquoteIdentifier() ¶ public
quoteIdentifier(string $identifier): string
Quotes a database identifier (a column name, table name, etc..) to be used safely in queries without the risk of using reserved words.
This does not require supportsQuoting() to work.
Parameters
-
string$identifier The identifier to quote.
Returns
stringreleaseSavePoint() ¶ public
releaseSavePoint(string|int $name): void
Releases a save point by its name.
Parameters
-
string|int$name Save point name or id
Returns
voidrollback() ¶ public
rollback(bool|null $toBeginning = null): bool
Rollback current transaction.
Parameters
-
bool|null$toBeginning optional Whether the transaction should be rolled back to the beginning of it. Defaults to false if using savepoints, or true if not.
Returns
boolrollbackSavepoint() ¶ public
rollbackSavepoint(string|int $name): void
Rollback a save point by its name.
Parameters
-
string|int$name Save point name or id
Returns
voidrun() ¶ public
run(Cake\Database\Query $query): Cake\Database\StatementInterface
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\StatementInterfaceselectQuery() ¶ public
selectQuery(Cake\Database\ExpressionInterface|callable|array|string $fields = [], array|string $table = [], array<string, string> $types = []): Cake\Database\Query\SelectQuery
Create a new SelectQuery instance for this connection.
Parameters
-
Cake\Database\ExpressionInterface|callable|array|string$fields optional fields to be added to the list.
-
array|string$table optional The table or list of tables to query.
-
array<string, string>$types optional Associative array containing the types to be used for casting.
Returns
Cake\Database\Query\SelectQuerysetCacher() ¶ public
setCacher(Psr\SimpleCache\CacheInterface $cacher): $this
Set a cacher.
Parameters
-
Psr\SimpleCache\CacheInterface$cacher
Returns
$thissetDriver() ¶ public
setDriver(Cake\Database\DriverInterface|string $driver, array<string, mixed> $config = []): $this
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<string, mixed>$config optional Config for a new driver.
Returns
$thisThrows
Cake\Database\Exception\MissingDriverExceptionWhen a driver class is missing.
Cake\Database\Exception\MissingExtensionExceptionWhen a driver's PHP extension is missing.
setLogger() ¶ public
setLogger(Psr\Log\LoggerInterface $logger): $this
Sets a logger
Parameters
-
Psr\Log\LoggerInterface$logger Logger object
Returns
$thissetSchemaCollection() ¶ public
setSchemaCollection(Cake\Database\Schema\CollectionInterface $collection): $this
Sets a Schema\Collection object for this connection.
Parameters
-
Cake\Database\Schema\CollectionInterface$collection The schema collection object
Returns
$thissupportsDynamicConstraints() ¶ public
supportsDynamicConstraints(): bool
Returns whether the driver supports adding or dropping constraints to already created tables.
Returns
boolsupportsQuoting() ¶ public
supportsQuoting(): bool
Checks if using quote() is supported.
This is not required to use quoteIdentifier().
Returns
booltransactional() ¶ public
transactional(callable $callback): mixed
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
Returns
mixedupdate() ¶ public
update(string $table, array $values, array $conditions = [], array<string> $types = []): Cake\Database\StatementInterface
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<string>$types optional list of associative array containing the types to be used for casting
Returns
Cake\Database\StatementInterfaceupdateQuery() ¶ public
updateQuery(Cake\Database\ExpressionInterface|string|null $table = null, array $values = [], array $conditions = [], array<string, string> $types = []): Cake\Database\Query\UpdateQuery
Create a new UpdateQuery instance for this connection.
Parameters
-
Cake\Database\ExpressionInterface|string|null$table optional The table to update rows of.
-
array$values optional Values to be updated.
-
array$conditions optional Conditions to be set for the update statement.
-
array<string, string>$types optional Associative array containing the types to be used for casting.
Returns
Cake\Database\Query\UpdateQuerywasNestedTransactionRolledback() ¶ protected
wasNestedTransactionRolledback(): bool
Returns whether some nested transaction has been already rolled back.
Returns
boolProperty Detail
$_config ¶ protected
Contains the configuration params for this connection.
Type
array<string, mixed>$_schemaCollection ¶ protected
The schema collection object
Type
Cake\Database\Schema\CollectionInterface|null$_useSavePoints ¶ protected
Whether this connection can and should use savepoints for nested transactions.
Type
bool$nestedTransactionRollbackException ¶ protected
NestedTransactionRollbackException object instance, will be stored if the rollback method is called in some nested transaction.
Type
Cake\Database\Exception\NestedTransactionRollbackException|null