Fr3nch13/CakePHP Utilities

Connection
in package
implements ConnectionInterface uses TypeConverterTrait

Represents a connection with a database server.

Table of Contents

Interfaces

ConnectionInterface
This interface defines the methods you can depend on in a connection.

Properties

$_config  : array<string, mixed>
Contains the configuration params for this connection.
$_driver  : DriverInterface
Driver object, responsible for creating the real connection and provide specific SQL dialect.
$_logger  : LoggerInterface|null
Logger object instance.
$_logQueries  : bool
Whether to log queries generated during this connection.
$_schemaCollection  : CollectionInterface|null
The schema collection object
$_transactionLevel  : int
Contains how many nested transactions have been started.
$_transactionStarted  : bool
Whether a transaction is active in this connection.
$_useSavePoints  : bool
Whether this connection can and should use savepoints for nested transactions.
$cacher  : CacheInterface|null
Cacher object instance.
$nestedTransactionRollbackException  : NestedTransactionRollbackException|null
NestedTransactionRollbackException object instance, will be stored if the rollback method is called in some nested transaction.

Methods

__construct()  : mixed
Constructor.
__debugInfo()  : array<string, mixed>
Returns an array that can be used to describe the internal state of this object.
__destruct()  : mixed
Destructor
begin()  : void
Starts a new transaction.
cacheMetadata()  : void
Enables or disables metadata caching for this connection
cast()  : array<string|int, mixed>
Converts a give value to a suitable database value based on type and return relevant internal statement type
commit()  : bool
Commits current transaction.
compileQuery()  : string
Compiles a Query object into a SQL string according to the dialect for this connection's driver
config()  : array<string, mixed>
Get the configuration data used to create the connection.
configName()  : string
Get the configuration name for this connection.
connect()  : bool
Connects to the configured database.
createSavePoint()  : void
Creates a new save point for nested transactions.
delete()  : StatementInterface
Executes a DELETE statement on the specified table.
disableConstraints()  : mixed
Run an operation with constraints disabled.
disableForeignKeys()  : void
Run driver specific SQL to disable foreign key checks.
disableQueryLogging()  : $this
Disable query logging
disableSavePoints()  : $this
Disables the usage of savepoints.
disconnect()  : void
Disconnects from database server.
enableForeignKeys()  : void
Run driver specific SQL to enable foreign key checks.
enableQueryLogging()  : $this
Enable/disable query logging
enableSavePoints()  : $this
Enables/disables the usage of savepoints, enables only if driver the allows it.
execute()  : StatementInterface
Executes a query using $params for interpolating values and $types as a hint for each those params.
getCacher()  : CacheInterface
Get a cacher.
getDisconnectRetry()  : CommandRetry
Get the retry wrapper object that is allows recovery from server disconnects while performing certain database actions, such as executing a query.
getDriver()  : DriverInterface
Gets the driver instance.
getLogger()  : LoggerInterface
Gets the logger object
getSchemaCollection()  : CollectionInterface
Gets a Schema\Collection object for this connection.
insert()  : StatementInterface
Executes an INSERT query on the specified table.
inTransaction()  : bool
Checks if a transaction is running.
isConnected()  : bool
Returns whether connection to database server was already established.
isQueryLoggingEnabled()  : bool
Check if query logging is enabled.
isSavePointsEnabled()  : bool
Returns whether this connection is using savepoints for nested transactions
log()  : void
Logs a Query string using the configured logger object.
matchTypes()  : array<string|int, mixed>
Matches columns to corresponding types
newQuery()  : Query
Create a new Query instance for this connection.
prepare()  : StatementInterface
Prepares a SQL statement to be executed.
query()  : StatementInterface
Executes a SQL statement and returns the Statement object as result.
quote()  : string
Quotes value to be used safely in database query.
quoteIdentifier()  : string
Quotes a database identifier (a column name, table name, etc..) to be used safely in queries without the risk of using reserved words.
releaseSavePoint()  : void
Releases a save point by its name.
rollback()  : bool
Rollback current transaction.
rollbackSavepoint()  : void
Rollback a save point by its name.
run()  : StatementInterface
Executes the provided query after compiling it for the specific driver dialect and returns the executed Statement object.
setCacher()  : $this
Set a cacher.
setDriver()  : $this
Sets the driver instance. If a string is passed it will be treated as a class name and will be instantiated.
setLogger()  : $this
Sets a logger
setSchemaCollection()  : $this
Sets a Schema\Collection object for this connection.
supportsDynamicConstraints()  : bool
Returns whether the driver supports adding or dropping constraints to already created tables.
supportsQuoting()  : bool
Checks if using `quote()` is supported.
transactional()  : 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.
update()  : StatementInterface
Executes an UPDATE statement on the specified table.
_newLogger()  : LoggingStatement
Returns a new statement object that will log the activity for the passed original statement instance.
createDriver()  : DriverInterface
Creates driver from name, class name or instance.
wasNestedTransactionRolledback()  : bool
Returns whether some nested transaction has been already rolled back.

Properties

$_config

Contains the configuration params for this connection.

protected array<string, mixed> $_config

$_driver

Driver object, responsible for creating the real connection and provide specific SQL dialect.

protected DriverInterface $_driver

$_logQueries

Whether to log queries generated during this connection.

protected bool $_logQueries = false

$_transactionLevel

Contains how many nested transactions have been started.

protected int $_transactionLevel = 0

$_transactionStarted

Whether a transaction is active in this connection.

protected bool $_transactionStarted = false

$_useSavePoints

Whether this connection can and should use savepoints for nested transactions.

protected bool $_useSavePoints = false

$nestedTransactionRollbackException

NestedTransactionRollbackException object instance, will be stored if the rollback method is called in some nested transaction.

protected NestedTransactionRollbackException|null $nestedTransactionRollbackException

Methods

__construct()

Constructor.

public __construct(array<string, mixed> $config) : mixed

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
$config : array<string, mixed>

Configuration array.

__debugInfo()

Returns an array that can be used to describe the internal state of this object.

public __debugInfo() : array<string, mixed>
Return values
array<string, mixed>

__destruct()

Destructor

public __destruct() : mixed

Disconnects the driver to release the connection.

begin()

Starts a new transaction.

public begin() : void

cacheMetadata()

Enables or disables metadata caching for this connection

public cacheMetadata(string|bool $cache) : void

Changing this setting will not modify existing schema collections objects.

Parameters
$cache : string|bool

Either boolean false to disable metadata caching, or true to use _cake_model_ or the name of the cache config to use.

cast()

Converts a give value to a suitable database value based on type and return relevant internal statement type

public cast(mixed $value[, TypeInterface|string|int $type = 'string' ]) : array<string|int, mixed>
Parameters
$value : mixed

The value to cast

$type : TypeInterface|string|int = 'string'

The type name or type instance to use.

Tags
pslam-return

array{mixed, int}

Return values
array<string|int, mixed> —

list containing converted value and internal type

commit()

Commits current transaction.

public commit() : bool
Return values
bool —

true on success, false otherwise

compileQuery()

Compiles a Query object into a SQL string according to the dialect for this connection's driver

public compileQuery(Query $query, ValueBinder $binder) : string
Parameters
$query : Query

The query to be compiled

$binder : ValueBinder

Value binder

Return values
string

config()

Get the configuration data used to create the connection.

public config() : array<string, mixed>
Tags
inheritDoc
Return values
array<string, mixed>

configName()

Get the configuration name for this connection.

public configName() : string
Tags
inheritDoc
Return values
string

connect()

Connects to the configured database.

public connect() : bool
Tags
throws
MissingConnectionException

If database connection could not be established.

Return values
bool —

true, if the connection was already established or the attempt was successful.

createSavePoint()

Creates a new save point for nested transactions.

public createSavePoint(string|int $name) : void
Parameters
$name : string|int

Save point name or id

delete()

Executes a DELETE statement on the specified table.

public delete(string $table[, array<string|int, mixed> $conditions = [] ][, array<string|int, string> $types = [] ]) : StatementInterface
Parameters
$table : string

the table to delete rows from

$conditions : array<string|int, mixed> = []

conditions to be set for delete statement

$types : array<string|int, string> = []

list of associative array containing the types to be used for casting

Return values
StatementInterface

disableConstraints()

Run an operation with constraints disabled.

public disableConstraints(callable $callback) : mixed
Parameters
$callback : callable

The callback to execute within a transaction.

Tags
inheritDoc
Return values
mixed —

The return value of the callback.

disableForeignKeys()

Run driver specific SQL to disable foreign key checks.

public disableForeignKeys() : void

disableQueryLogging()

Disable query logging

public disableQueryLogging() : $this
Return values
$this

disableSavePoints()

Disables the usage of savepoints.

public disableSavePoints() : $this
Return values
$this

disconnect()

Disconnects from database server.

public disconnect() : void

enableForeignKeys()

Run driver specific SQL to enable foreign key checks.

public enableForeignKeys() : void

enableQueryLogging()

Enable/disable query logging

public enableQueryLogging([bool $enable = true ]) : $this
Parameters
$enable : bool = true

Enable/disable query logging

Return values
$this

enableSavePoints()

Enables/disables the usage of savepoints, enables only if driver the allows it.

public enableSavePoints([bool $enable = true ]) : $this

If you are trying to enable this feature, make sure you check isSavePointsEnabled() to verify that savepoints were enabled successfully.

Parameters
$enable : bool = true

Whether save points should be used.

Return values
$this

execute()

Executes a query using $params for interpolating values and $types as a hint for each those params.

public execute(string $sql[, array<string|int, mixed> $params = [] ][, array<string|int, mixed> $types = [] ]) : StatementInterface
Parameters
$sql : string

SQL to be executed and interpolated with $params

$params : array<string|int, mixed> = []

list or associative array of params to be interpolated in $sql as values

$types : array<string|int, mixed> = []

list or associative array of types to be used for casting values in query

Return values
StatementInterface —

executed statement

getDisconnectRetry()

Get the retry wrapper object that is allows recovery from server disconnects while performing certain database actions, such as executing a query.

public getDisconnectRetry() : CommandRetry
Return values
CommandRetry —

The retry wrapper

insert()

Executes an INSERT query on the specified table.

public insert(string $table, array<string|int, mixed> $values[, array<int|string, string> $types = [] ]) : StatementInterface
Parameters
$table : string

the table to insert values in

$values : array<string|int, mixed>

values to be inserted

$types : array<int|string, string> = []

Array containing the types to be used for casting

Return values
StatementInterface

inTransaction()

Checks if a transaction is running.

public inTransaction() : bool
Return values
bool —

True if a transaction is running else false.

isConnected()

Returns whether connection to database server was already established.

public isConnected() : bool
Return values
bool

isQueryLoggingEnabled()

Check if query logging is enabled.

public isQueryLoggingEnabled() : bool
Return values
bool

isSavePointsEnabled()

Returns whether this connection is using savepoints for nested transactions

public isSavePointsEnabled() : bool
Return values
bool —

true if enabled, false otherwise

log()

Logs a Query string using the configured logger object.

public log(string $sql) : void
Parameters
$sql : string

string to be logged

matchTypes()

Matches columns to corresponding types

public matchTypes(array<string|int, mixed> $columns, array<string|int, mixed> $types) : array<string|int, mixed>

Both $columns and $types should either be numeric based or string key based at the same time.

Parameters
$columns : array<string|int, mixed>

list or associative array of columns and parameters to be bound with types

$types : array<string|int, mixed>

list or associative array of types

Return values
array<string|int, mixed>

newQuery()

Create a new Query instance for this connection.

public newQuery() : Query
Return values
Query

quote()

Quotes value to be used safely in database query.

public quote(mixed $value[, TypeInterface|string|int $type = 'string' ]) : string

This uses PDO::quote() and requires supportsQuoting() to work.

Parameters
$value : mixed

The value to quote.

$type : TypeInterface|string|int = 'string'

Type to be used for determining kind of quoting to perform

Return values
string —

Quoted value

quoteIdentifier()

Quotes a database identifier (a column name, table name, etc..) to be used safely in queries without the risk of using reserved words.

public quoteIdentifier(string $identifier) : string

This does not require supportsQuoting() to work.

Parameters
$identifier : string

The identifier to quote.

Return values
string

releaseSavePoint()

Releases a save point by its name.

public releaseSavePoint(string|int $name) : void
Parameters
$name : string|int

Save point name or id

rollback()

Rollback current transaction.

public rollback([bool|null $toBeginning = null ]) : bool
Parameters
$toBeginning : bool|null = null

Whether the transaction should be rolled back to the beginning of it. Defaults to false if using savepoints, or true if not.

Return values
bool

rollbackSavepoint()

Rollback a save point by its name.

public rollbackSavepoint(string|int $name) : void
Parameters
$name : string|int

Save point name or id

run()

Executes the provided query after compiling it for the specific driver dialect and returns the executed Statement object.

public run(Query $query) : StatementInterface
Parameters
$query : Query

The query to be executed

Return values
StatementInterface —

executed statement

setDriver()

Sets the driver instance. If a string is passed it will be treated as a class name and will be instantiated.

public setDriver(DriverInterface|string $driver[, array<string, mixed> $config = [] ]) : $this

Setting the driver is deprecated. Use the connection config instead.

Parameters
$driver : DriverInterface|string

The driver instance to use.

$config : array<string, mixed> = []

Config for a new driver.

Tags
throws
MissingDriverException

When a driver class is missing.

throws
MissingExtensionException

When a driver's PHP extension is missing.

Return values
$this

setLogger()

Sets a logger

public setLogger(LoggerInterface $logger) : $this
Parameters
$logger : LoggerInterface

Logger object

Tags
psalm-suppress

ImplementedReturnTypeMismatch

Return values
$this

setSchemaCollection()

Sets a Schema\Collection object for this connection.

public setSchemaCollection(CollectionInterface $collection) : $this
Parameters
$collection : CollectionInterface

The schema collection object

Return values
$this

supportsDynamicConstraints()

Returns whether the driver supports adding or dropping constraints to already created tables.

public supportsDynamicConstraints() : bool

Fixtures no longer dynamically drop and create constraints.

Return values
bool —

true if driver supports dynamic constraints

supportsQuoting()

Checks if using `quote()` is supported.

public supportsQuoting() : bool

This is not required to use quoteIdentifier().

Return values
bool

transactional()

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.

public transactional(callable $callback) : mixed
Parameters
$callback : callable

The callback to execute within a transaction.

Tags
inheritDoc
Return values
mixed —

The return value of the callback.

update()

Executes an UPDATE statement on the specified table.

public update(string $table, array<string|int, mixed> $values[, array<string|int, mixed> $conditions = [] ][, array<string|int, string> $types = [] ]) : StatementInterface
Parameters
$table : string

the table to update rows from

$values : array<string|int, mixed>

values to be updated

$conditions : array<string|int, mixed> = []

conditions to be set for update statement

$types : array<string|int, string> = []

list of associative array containing the types to be used for casting

Return values
StatementInterface

_newLogger()

Returns a new statement object that will log the activity for the passed original statement instance.

protected _newLogger(StatementInterface $statement) : LoggingStatement
Parameters
$statement : StatementInterface

the instance to be decorated

Return values
LoggingStatement

createDriver()

Creates driver from name, class name or instance.

protected createDriver(DriverInterface|string $name, array<string|int, mixed> $config) : DriverInterface
Parameters
$name : DriverInterface|string

Driver name, class name or instance.

$config : array<string|int, mixed>

Driver config if $name is not an instance.

Tags
throws
MissingDriverException

When a driver class is missing.

throws
MissingExtensionException

When a driver's PHP extension is missing.

Return values
DriverInterface

wasNestedTransactionRolledback()

Returns whether some nested transaction has been already rolled back.

protected wasNestedTransactionRolledback() : bool
Return values
bool

        
On this page

Search results