class MasterSlaveConnection extends Connection (View source)

Master-Slave Connection

Connection can be used with master-slave setups.

Important for the understanding of this connection should be how and when it picks the slave or master.

  1. Slave if master was never picked before and ONLY if 'getWrappedConnection' or 'executeQuery' is used.
  2. Master picked when 'exec', 'executeUpdate', 'insert', 'delete', 'update', 'createSavepoint', 'releaseSavepoint', 'beginTransaction', 'rollback', 'commit', 'query' or 'prepare' is called.
  3. If master was picked once during the lifetime of the connection it will always get picked afterwards.
  4. One slave connection is randomly picked ONCE during a request.

ATTENTION: You can write to the slave with this connection if you execute a write query without opening up a transaction. For example:

 $conn = DriverManager::getConnection(...);
 $conn->executeQuery("DELETE FROM table");

Be aware that Connection#executeQuery is a method specifically for READ operations only.

This connection is limited to slave operations using the Connection#executeQuery operation only, because it wouldn't be compatible with the ORM or SchemaManager code otherwise. Both use all the other operations in a context where writes could happen to a slave, which makes this restricted approach necessary.

You can manually connect to the master at any time by calling:

 $conn->connect('master');

Instantiation through the DriverManager looks like:

Constants

TRANSACTION_READ_UNCOMMITTED

Constant for transaction isolation level READ UNCOMMITTED.

TRANSACTION_READ_COMMITTED

Constant for transaction isolation level READ COMMITTED.

TRANSACTION_REPEATABLE_READ

Constant for transaction isolation level REPEATABLE READ.

TRANSACTION_SERIALIZABLE

Constant for transaction isolation level SERIALIZABLE.

PARAM_INT_ARRAY

Represents an array of ints to be expanded by Doctrine SQL parsing.

PARAM_STR_ARRAY

Represents an array of strings to be expanded by Doctrine SQL parsing.

ARRAY_PARAM_OFFSET

Offset by which PARAM_* constants are detected as arrays of the param type.

Properties

protected Connection $_conn The wrapped driver connection. from Connection
protected Configuration $_config from Connection
protected EventManager $_eventManager from Connection
protected ExpressionBuilder $_expr from Connection
protected AbstractPlatform $_platform The DatabasePlatform object that provides information about the database platform used by the connection. from Connection
protected AbstractSchemaManager $_schemaManager The schema manager. from Connection
protected Driver $_driver The used DBAL driver. from Connection
protected Connection[] $connections Master and slave connection (one of the randomly picked slaves)
protected bool $keepSlave You can keep the slave connection and then switch back to it during the request if you know what you are doing.

Methods

__construct(array $params, Driver $driver, Configuration $config = null, EventManager $eventManager = null)

Create Master Slave Connection

array
getParams()

Gets the parameters used during instantiation.

string
getDatabase()

Gets the name of the database this Connection is connected to.

string
getHost()

Gets the hostname of the currently connected database.

mixed
getPort()

Gets the port of the currently connected database.

string
getUsername()

Gets the username used by this connection.

string
getPassword()

Gets the password used by this connection.

getDriver()

Gets the DBAL driver instance.

getConfiguration()

Gets the Configuration used by the Connection.

EventManager
getEventManager()

Gets the EventManager used by the Connection.

getDatabasePlatform()

Gets the DatabasePlatform for the connection.

getExpressionBuilder()

Gets the ExpressionBuilder for the connection.

boolean
connect($connectionName = null)

Establishes the connection with the database.

setFetchMode(integer $fetchMode)

setFetchMode

array
fetchAssoc(string $statement, array $params = array())

Prepares and executes an SQL query and returns the first row of the result as an associative array.

array
fetchArray(string $statement, array $params = array())

Prepares and executes an SQL query and returns the first row of the result as a numerically indexed array.

mixed
fetchColumn(string $statement, array $params = array(), int $colnum = 0)

Prepares and executes an SQL query and returns the value of a single column of the first row of the result.

boolean
isConnected()

Whether an actual connection to the database is established.

boolean
isTransactionActive()

Checks whether a transaction is currently active.

integer
delete(string $tableName, array $identifier)

Executes an SQL DELETE statement on a table.

void
close()

Closes the connection.

integer
setTransactionIsolation(integer $level)

Sets the transaction isolation level.

integer
getTransactionIsolation()

Gets the currently active transaction isolation level.

integer
update(string $tableName, array $data, array $identifier, array $types = array())

Executes an SQL UPDATE statement on a table.

integer
insert(string $tableName, array $data, array $types = array())

Inserts a table row with specified data.

string
quoteIdentifier(string $str)

Quote a string so it can be safely used as a table or column name, even if it is a reserved name.

quote($input, $type = null)

Quotes a given input parameter.

array
fetchAll(string $sql, array $params = array())

Prepares and executes an SQL query and returns the result as an associative array.

prepare(string $statement)

Prepares an SQL statement.

executeQuery(string $query, array $params = array(), array $types = array(), QueryCacheProfile $qcp = null)

Executes an, optionally parameterized, SQL query.

executeCacheQuery(string $query, array $params, array $types, QueryCacheProfile $qcp)

Execute a caching query and

mixed
project($query, array $params, Closure $function)

Executes an, optionally parameterized, SQL query and returns the result, applying a given projection/transformation function on each row of the result.

query()

Executes an SQL statement, returning a result set as a Statement object.

integer
executeUpdate(string $query, array $params = array(), array $types = array())

Executes an SQL INSERT/UPDATE/DELETE query with the given parameters and returns the number of affected rows.

exec($statement)

Execute an SQL statement and return the number of affected rows.

integer
getTransactionNestingLevel()

Returns the current transaction nesting level.

errorCode()

Fetch the SQLSTATE associated with the last database operation.

errorInfo()

Fetch extended error information associated with the last database operation.

lastInsertId(string $seqName = null)

Returns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver.

transactional(Closure $func)

Executes a function in a transaction.

void
setNestTransactionsWithSavepoints(boolean $nestTransactionsWithSavepoints)

Set if nested transactions should use savepoints

boolean
getNestTransactionsWithSavepoints()

Get if nested transactions should use savepoints

mixed
_getNestedTransactionSavePointName()

Returns the savepoint name to use for nested transactions are false if they are not supported "savepointFormat" parameter is not set

beginTransaction()

Starts a transaction by suspending auto-commit mode.

commit()

Commits the current transaction.

rollBack()

Cancel any database changes done during the current transaction.

void
createSavepoint(string $savepoint)

createSavepoint creates a new savepoint

void
releaseSavepoint(string $savepoint)

releaseSavePoint releases given savepoint

void
rollbackSavepoint(string $savepoint)

rollbackSavePoint releases given savepoint

getWrappedConnection()

Gets the wrapped driver connection.

getSchemaManager()

Gets the SchemaManager that can be used to inspect or change the database schema through the connection.

setRollbackOnly()

Marks the current transaction so that the only possible outcome for the transaction to be rolled back.

boolean
isRollbackOnly()

Check whether the current transaction is marked for rollback only.

mixed
convertToDatabaseValue(mixed $value, string $type)

Converts a given value to its database representation according to the conversion rules of a specific DBAL mapping type.

mixed
convertToPHPValue(mixed $value, string $type)

Converts a given value to its PHP representation according to the conversion rules of a specific DBAL mapping type.

array
resolveParams(array $params, array $types)

Resolves the parameters to a format which can be displayed.

createQueryBuilder()

Create a new instance of a SQL query builder.

bool
isConnectedToMaster()

Check if the connection is currently towards the master or not.

connectTo(string $connectionName)

Connect to a specific connection

chooseConnectionConfiguration($connectionName, $params)

No description

Details

__construct(array $params, Driver $driver, Configuration $config = null, EventManager $eventManager = null)

Create Master Slave Connection

Parameters

array $params The connection parameters.
Driver $driver
Configuration $config
EventManager $eventManager

array getParams()

Gets the parameters used during instantiation.

Return Value

array $params

string getDatabase()

Gets the name of the database this Connection is connected to.

Return Value

string $database

string getHost()

Gets the hostname of the currently connected database.

Return Value

string

mixed getPort()

Gets the port of the currently connected database.

Return Value

mixed

string getUsername()

Gets the username used by this connection.

Return Value

string

string getPassword()

Gets the password used by this connection.

Return Value

string

Driver getDriver()

Gets the DBAL driver instance.

Return Value

Driver

Configuration getConfiguration()

Gets the Configuration used by the Connection.

Return Value

Configuration

EventManager getEventManager()

Gets the EventManager used by the Connection.

Return Value

EventManager

AbstractPlatform getDatabasePlatform()

Gets the DatabasePlatform for the connection.

Return Value

AbstractPlatform

ExpressionBuilder getExpressionBuilder()

Gets the ExpressionBuilder for the connection.

Return Value

ExpressionBuilder

boolean connect($connectionName = null)

Establishes the connection with the database.

Parameters

$connectionName

Return Value

boolean TRUE if the connection was successfully established, FALSE if the connection is already open.

setFetchMode(integer $fetchMode)

setFetchMode

Parameters

integer $fetchMode

array fetchAssoc(string $statement, array $params = array())

Prepares and executes an SQL query and returns the first row of the result as an associative array.

Parameters

string $statement The SQL query.
array $params The query parameters.

Return Value

array

array fetchArray(string $statement, array $params = array())

Prepares and executes an SQL query and returns the first row of the result as a numerically indexed array.

Parameters

string $statement sql query to be executed
array $params prepared statement params

Return Value

array

mixed fetchColumn(string $statement, array $params = array(), int $colnum = 0)

Prepares and executes an SQL query and returns the value of a single column of the first row of the result.

Parameters

string $statement sql query to be executed
array $params prepared statement params
int $colnum 0-indexed column number to retrieve

Return Value

mixed

boolean isConnected()

Whether an actual connection to the database is established.

Return Value

boolean

boolean isTransactionActive()

Checks whether a transaction is currently active.

Return Value

boolean TRUE if a transaction is currently active, FALSE otherwise.

integer delete(string $tableName, array $identifier)

Executes an SQL DELETE statement on a table.

Parameters

string $tableName The name of the table on which to delete.
array $identifier The deletion criteria. An associative array containing column-value pairs.

Return Value

integer The number of affected rows.

void close()

Closes the connection.

Return Value

void

integer setTransactionIsolation(integer $level)

Sets the transaction isolation level.

Parameters

integer $level The level to set.

Return Value

integer

integer getTransactionIsolation()

Gets the currently active transaction isolation level.

Return Value

integer The current transaction isolation level.

integer update(string $tableName, array $data, array $identifier, array $types = array())

Executes an SQL UPDATE statement on a table.

Parameters

string $tableName The name of the table to update.
array $data
array $identifier The update criteria. An associative array containing column-value pairs.
array $types Types of the merged $data and $identifier arrays in that order.

Return Value

integer The number of affected rows.

integer insert(string $tableName, array $data, array $types = array())

Inserts a table row with specified data.

Parameters

string $tableName The name of the table to insert data into.
array $data An associative array containing column-value pairs.
array $types Types of the inserted data.

Return Value

integer The number of affected rows.

string quoteIdentifier(string $str)

Quote a string so it can be safely used as a table or column name, even if it is a reserved name.

Delimiting style depends on the underlying database platform that is being used.

NOTE: Just because you CAN use quoted identifiers does not mean you SHOULD use them. In general, they end up causing way more problems than they solve.

Parameters

string $str The name to be quoted.

Return Value

string The quoted name.

quote($input, $type = null)

Quotes a given input parameter.

Parameters

$input
$type

array fetchAll(string $sql, array $params = array())

Prepares and executes an SQL query and returns the result as an associative array.

Parameters

string $sql The SQL query.
array $params The query parameters.

Return Value

array

prepare(string $statement)

Prepares an SQL statement.

Parameters

string $statement The SQL statement to prepare.

Statement executeQuery(string $query, array $params = array(), array $types = array(), QueryCacheProfile $qcp = null)

Executes an, optionally parameterized, SQL query.

If the query is parameterized, a prepared statement is used. If an SQLLogger is configured, the execution is logged.

Parameters

string $query The SQL query to execute.
array $params The parameters to bind to the query, if any.
array $types The types the previous parameters are in.
QueryCacheProfile $qcp

Return Value

Statement The executed statement.

ResultStatement executeCacheQuery(string $query, array $params, array $types, QueryCacheProfile $qcp)

Execute a caching query and

Parameters

string $query
array $params
array $types
QueryCacheProfile $qcp

Return Value

ResultStatement

mixed project($query, array $params, Closure $function)

Executes an, optionally parameterized, SQL query and returns the result, applying a given projection/transformation function on each row of the result.

Parameters

$query
array $params
Closure $function

Return Value

mixed The projected result of the query.

query()

Executes an SQL statement, returning a result set as a Statement object.

integer executeUpdate(string $query, array $params = array(), array $types = array())

Executes an SQL INSERT/UPDATE/DELETE query with the given parameters and returns the number of affected rows.

This method supports PDO binding types as well as DBAL mapping types.

Parameters

string $query The SQL query.
array $params The query parameters.
array $types The parameter types.

Return Value

integer The number of affected rows.

exec($statement)

Execute an SQL statement and return the number of affected rows.

Parameters

$statement

integer getTransactionNestingLevel()

Returns the current transaction nesting level.

Return Value

integer The nesting level. A value of 0 means there's no active transaction.

errorCode()

Fetch the SQLSTATE associated with the last database operation.

errorInfo()

Fetch extended error information associated with the last database operation.

lastInsertId(string $seqName = null)

Returns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver.

Note: This method may not return a meaningful or consistent result across different drivers, because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY columns or sequences.

Parameters

string $seqName Name of the sequence object from which the ID should be returned.

transactional(Closure $func)

Executes a function in a transaction.

The function gets passed this Connection instance as an (optional) parameter.

If an exception occurs during execution of the function or transaction commit, the transaction is rolled back and the exception re-thrown.

Parameters

Closure $func The function to execute transactionally.

void setNestTransactionsWithSavepoints(boolean $nestTransactionsWithSavepoints)

Set if nested transactions should use savepoints

Parameters

boolean $nestTransactionsWithSavepoints

Return Value

void

boolean getNestTransactionsWithSavepoints()

Get if nested transactions should use savepoints

Return Value

boolean

protected mixed _getNestedTransactionSavePointName()

Returns the savepoint name to use for nested transactions are false if they are not supported "savepointFormat" parameter is not set

Return Value

mixed a string with the savepoint name or false

beginTransaction()

Starts a transaction by suspending auto-commit mode.

commit()

Commits the current transaction.

Exceptions

ConnectionException If the commit failed due to no active transaction or because the transaction was marked for rollback only.

rollBack()

Cancel any database changes done during the current transaction.

this method can be listened with onPreTransactionRollback and onTransactionRollback eventlistener methods

Exceptions

ConnectionException If the rollback operation failed.

void createSavepoint(string $savepoint)

createSavepoint creates a new savepoint

Parameters

string $savepoint name of a savepoint to set

Return Value

void

void releaseSavepoint(string $savepoint)

releaseSavePoint releases given savepoint

Parameters

string $savepoint name of a savepoint to release

Return Value

void

void rollbackSavepoint(string $savepoint)

rollbackSavePoint releases given savepoint

Parameters

string $savepoint name of a savepoint to rollback to

Return Value

void

Connection getWrappedConnection()

Gets the wrapped driver connection.

Return Value

Connection

AbstractSchemaManager getSchemaManager()

Gets the SchemaManager that can be used to inspect or change the database schema through the connection.

Return Value

AbstractSchemaManager

setRollbackOnly()

Marks the current transaction so that the only possible outcome for the transaction to be rolled back.

Exceptions

ConnectionException If no transaction is active.

boolean isRollbackOnly()

Check whether the current transaction is marked for rollback only.

Return Value

boolean

Exceptions

ConnectionException If no transaction is active.

mixed convertToDatabaseValue(mixed $value, string $type)

Converts a given value to its database representation according to the conversion rules of a specific DBAL mapping type.

Parameters

mixed $value The value to convert.
string $type The name of the DBAL mapping type.

Return Value

mixed The converted value.

mixed convertToPHPValue(mixed $value, string $type)

Converts a given value to its PHP representation according to the conversion rules of a specific DBAL mapping type.

Parameters

mixed $value The value to convert.
string $type The name of the DBAL mapping type.

Return Value

mixed The converted type.

array resolveParams(array $params, array $types)

Resolves the parameters to a format which can be displayed.

Parameters

array $params
array $types

Return Value

array

QueryBuilder createQueryBuilder()

Create a new instance of a SQL query builder.

Return Value

QueryBuilder

bool isConnectedToMaster()

Check if the connection is currently towards the master or not.

Return Value

bool

protected Driver connectTo(string $connectionName)

Connect to a specific connection

Parameters

string $connectionName

Return Value

Driver

protected chooseConnectionConfiguration($connectionName, $params)

Parameters

$connectionName
$params