Class yii\sphinx\Connection
Inheritance | yii\sphinx\Connection » yii\db\Connection » yii\base\Component » yii\base\BaseObject |
---|---|
Implements | yii\base\Configurable |
Available since version | 2.0 |
Source Code | https://github.com/yiisoft/yii2-sphinx/blob/master/Connection.php |
Connection represents the Sphinx connection via MySQL protocol.
This class uses PDO to maintain such connection. Note: although PDO supports numerous database drivers, this class supports only MySQL.
In order to setup Sphinx "searchd" to support MySQL protocol following configuration should be added:
searchd
{
listen = localhost:9306:mysql41
...
}
The following example shows how to create a Connection instance and establish the Sphinx connection:
$connection = new \yii\db\Connection([
'dsn' => 'mysql:host=127.0.0.1;port=9306;',
'username' => $username,
'password' => $password,
]);
$connection->open();
After the Sphinx connection is established, one can execute SQL statements like the following:
$command = $connection->createCommand("SELECT * FROM idx_article WHERE MATCH('programming')");
$articles = $command->queryAll();
$command = $connection->createCommand('UPDATE idx_article SET status=2 WHERE id=1');
$command->execute();
For more information about how to perform various DB queries, please refer to yii\sphinx\Command.
This class supports transactions exactly as "yii\db\Connection".
Note: while this class extends "yii\db\Connection" some of its methods are not supported.
Public Properties
Property | Type | Description | Defined By |
---|---|---|---|
$attributes | array | PDO attributes (name => value) that should be set when calling open() to establish a DB connection. | yii\db\Connection |
$behaviors | yii\base\Behavior[] | List of behaviors attached to this component. | yii\base\Component |
$charset | string|null | The charset used for database connection. | yii\db\Connection |
$commandClass | string | The class used to create new database yii\db\Command objects. | yii\db\Connection |
$commandMap | array | Mapping between PDO driver names and yii\db\Command classes. | yii\db\Connection |
$driverName | string|null | Name of the DB driver. | yii\db\Connection |
$dsn | string | The Data Source Name, or DSN, contains the information required to connect to the database. | yii\db\Connection |
$emulatePrepare | boolean|null | Whether to turn on prepare emulation. | yii\db\Connection |
$enableFloatConversion | boolean | Whether to enable conversion of the float query params into the direct literal SQL insertion. | yii\sphinx\Connection |
$enableLogging | boolean | Whether to enable logging of database queries. | yii\db\Connection |
$enableProfiling | boolean | Whether to enable profiling of opening database connection and database queries. | yii\db\Connection |
$enableQueryCache | boolean | Whether to enable query caching. | yii\db\Connection |
$enableSavepoint | boolean | Whether to enable savepoint. | yii\db\Connection |
$enableSchemaCache | boolean | Whether to enable schema caching. | yii\db\Connection |
$enableSlaves | boolean | Whether to enable read/write splitting by using $slaves to read data. | yii\db\Connection |
$isActive | boolean | Whether the DB connection is established. | yii\db\Connection |
$isSybase | boolean | If the database connected via pdo_dblib is SyBase. | yii\db\Connection |
$lastInsertID | string | The row ID of the last row inserted, or the last value retrieved from the sequence object. | yii\sphinx\Connection |
$master | yii\db\Connection|null | The currently active master connection. | yii\db\Connection |
$masterConfig | array | The configuration that should be merged with every master configuration listed in $masters. | yii\db\Connection |
$masterPdo | PDO | The PDO instance for the currently active master connection. | yii\db\Connection |
$masters | array | List of master connection configurations. | yii\db\Connection |
$password | string|null | The password for establishing DB connection. | yii\db\Connection |
$pdo | PDO|null | The PHP PDO instance associated with this DB connection. | yii\db\Connection |
$pdoClass | string|null | Custom PDO wrapper class. | yii\db\Connection |
$queryBuilder | yii\db\QueryBuilder | The query builder for the current DB connection. | yii\db\Connection |
$queryCache | yii\caching\CacheInterface|string | The cache object or the ID of the cache application component that is used for query caching. | yii\db\Connection |
$queryCacheDuration | integer | The default number of seconds that query results can remain valid in cache. | yii\db\Connection |
$schema | yii\db\Schema | The schema information for the database opened by this connection. | yii\db\Connection |
$schemaCache | yii\caching\CacheInterface|string | The cache object or the ID of the cache application component that is used to cache the table metadata. | yii\db\Connection |
$schemaCacheDuration | integer | Number of seconds that table metadata can remain valid in cache. | yii\db\Connection |
$schemaCacheExclude | array | List of tables whose metadata should NOT be cached. | yii\db\Connection |
$schemaMap | array | Mapping between PDO driver names and yii\sphinx\Schema classes. | yii\sphinx\Connection |
$serverRetryInterval | integer | The retry interval in seconds for dead servers listed in $masters and $slaves. | yii\db\Connection |
$serverStatusCache | yii\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. | yii\db\Connection |
$serverVersion | string | Server version as a string. | yii\db\Connection |
$shuffleMasters | boolean | Whether to shuffle $masters before getting one. | yii\db\Connection |
$slave | yii\db\Connection|null | The currently active slave connection. | yii\db\Connection |
$slaveConfig | array | The configuration that should be merged with every slave configuration listed in $slaves. | yii\db\Connection |
$slavePdo | PDO|null | The PDO instance for the currently active slave connection. | yii\db\Connection |
$slaves | array | List of slave connection configurations. | yii\db\Connection |
$tablePrefix | string | The common prefix or suffix for table names. | yii\db\Connection |
$transaction | yii\db\Transaction|null | The currently active transaction. | yii\db\Connection |
$username | string|null | The username for establishing DB connection. | yii\db\Connection |
Public Methods
Method | Description | Defined By |
---|---|---|
__call() | Calls the named method which is not a class method. | yii\base\Component |
__clone() | Reset the connection after cloning. | yii\db\Connection |
__construct() | Constructor. | yii\base\BaseObject |
__get() | Returns the value of a component property. | yii\base\Component |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\base\Component |
__set() | Sets the value of a component property. | yii\base\Component |
__sleep() | Close the connection before serializing. | yii\db\Connection |
__unset() | Sets a component property to be null. | yii\base\Component |
attachBehavior() | Attaches a behavior to this component. | yii\base\Component |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\base\Component |
beginTransaction() | Starts a transaction. | yii\db\Connection |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\base\Component |
cache() | Uses query cache for the queries performed with the callable. | yii\db\Connection |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\base\Component |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\base\Component |
className() | Returns the fully qualified name of this class. | yii\base\BaseObject |
close() | Closes the currently active DB connection. | yii\db\Connection |
createCommand() | Creates a command for execution. | yii\sphinx\Connection |
detachBehavior() | Detaches a behavior from the component. | yii\base\Component |
detachBehaviors() | Detaches all behaviors from the component. | yii\base\Component |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\base\Component |
escapeMatchValue() | Escapes all special characters from 'MATCH' statement argument. | yii\sphinx\Connection |
getBehavior() | Returns the named behavior object. | yii\base\Component |
getBehaviors() | Returns all behaviors attached to this component. | yii\base\Component |
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. | yii\db\Connection |
getIndexSchema() | Obtains the schema information for the named index. | yii\sphinx\Connection |
getIsActive() | Returns a value indicating whether the DB connection is established. | yii\db\Connection |
getLastInsertID() | This method is not supported by Sphinx. | yii\sphinx\Connection |
getMaster() | Returns the currently active master connection. | yii\db\Connection |
getMasterPdo() | Returns the PDO instance for the currently active master connection. | yii\db\Connection |
getQueryBuilder() | the query builder for this Sphinx connection | yii\sphinx\Connection |
getSchema() | The schema information for this Sphinx connection | yii\sphinx\Connection |
getServerVersion() | Returns a server version as a string comparable by \version_compare(). | yii\db\Connection |
getSlave() | Returns the currently active slave connection. | yii\db\Connection |
getSlavePdo() | Returns the PDO instance for the currently active slave connection. | yii\db\Connection |
getTableSchema() | Obtains the schema information for the named table. | yii\db\Connection |
getTransaction() | Returns the currently active transaction. | yii\db\Connection |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. | yii\base\Component |
hasMethod() | Returns a value indicating whether a method is defined. | yii\base\Component |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\base\Component |
init() | Initializes the object. | yii\base\BaseObject |
noCache() | Disables query cache temporarily. | yii\db\Connection |
off() | Detaches an existing event handler from this component. | yii\base\Component |
on() | Attaches an event handler to an event. | yii\base\Component |
open() | Establishes a DB connection. | yii\db\Connection |
quoteColumnName() | Quotes a column name for use in a query. | yii\db\Connection |
quoteIndexName() | Quotes a index name for use in a query. | yii\sphinx\Connection |
quoteSql() | Processes a SQL statement by quoting table and column names that are enclosed within double brackets. | yii\db\Connection |
quoteTableName() | Alias of quoteIndexName(). | yii\sphinx\Connection |
quoteValue() | Quotes a string value for use in a query. | yii\db\Connection |
setDriverName() | Changes the current driver name. | yii\db\Connection |
setQueryBuilder() | Can be used to set yii\db\QueryBuilder configuration via Connection configuration array. | yii\db\Connection |
transaction() | Executes callback provided in a transaction. | yii\db\Connection |
trigger() | Triggers an event. | yii\base\Component |
useMaster() | Executes the provided callback by using the master connection. | yii\db\Connection |
Protected Methods
Method | Description | Defined By |
---|---|---|
createPdoInstance() | Creates the PDO instance. | yii\db\Connection |
initConnection() | Initializes the DB connection. | yii\db\Connection |
openFromPool() | Opens the connection to a server in the pool. | yii\db\Connection |
openFromPoolSequentially() | Opens the connection to a server in the pool. | yii\db\Connection |
Events
Event | Type | Description | Defined By |
---|---|---|---|
EVENT_AFTER_OPEN | yii\base\Event | An event that is triggered after a DB connection is established | yii\db\Connection |
EVENT_BEGIN_TRANSACTION | yii\base\Event | An event that is triggered right before a top-level transaction is started | yii\db\Connection |
EVENT_COMMIT_TRANSACTION | yii\base\Event | An event that is triggered right after a top-level transaction is committed | yii\db\Connection |
EVENT_ROLLBACK_TRANSACTION | yii\base\Event | An event that is triggered right after a top-level transaction is rolled back | yii\db\Connection |
Property Details
Whether to enable conversion of the float query params into the direct literal SQL insertion. This allows processing of the float values, since PDO does not provide specific param type for float binding, while Sphinx is unable to process float values passed as quoted strings.
The row ID of the last row inserted, or the last value retrieved from the sequence object.
Mapping between PDO driver names and yii\sphinx\Schema classes. The keys of the array are PDO driver names while the values are either the corresponding schema class names or configurations. Please refer to Yii::createObject() for details on how to specify a configuration.
This property is mainly used by getSchema() when fetching the database schema information. You normally do not need to set this property unless you want to use your own yii\sphinx\Schema class to support DBMS that is not supported by Yii.
Method Details
Defined in: yii\base\Component::__call()
Calls the named method which is not a class method.
This method will check if any attached behavior has the named method and will execute it if available.
Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.
public mixed __call ( $name, $params ) | ||
$name | string |
The method name |
$params | array |
Method parameters |
return | mixed |
The method return value |
---|---|---|
throws | yii\base\UnknownMethodException |
when calling unknown method |
public function __call($name, $params)
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $object) {
if ($object->hasMethod($name)) {
return call_user_func_array([$object, $name], $params);
}
}
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
Defined in: yii\db\Connection::__clone()
Reset the connection after cloning.
public void __clone ( ) |
public function __clone()
{
parent::__clone();
$this->_master = false;
$this->_slave = false;
$this->_schema = null;
$this->_transaction = null;
if (strncmp($this->dsn, 'sqlite::memory:', 15) !== 0) {
// reset PDO connection, unless its sqlite in-memory, which can only have one connection
$this->pdo = null;
}
}
Defined in: yii\base\BaseObject::__construct()
Constructor.
The default implementation does two things:
- Initializes the object with the given configuration
$config
. - Call init().
If this method is overridden in a child class, it is recommended that
- the last parameter of the constructor is a configuration array, like
$config
here. - call the parent implementation at the end of the constructor.
public void __construct ( $config = [] ) | ||
$config | array |
Name-value pairs that will be used to initialize the object properties |
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}
Defined in: yii\base\Component::__get()
Returns the value of a component property.
This method will check in the following order and act accordingly:
- a property defined by a getter: return the getter result
- a property of a behavior: return the behavior property value
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $value = $component->property;
.
See also __set().
public mixed __get ( $name ) | ||
$name | string |
The property name |
return | mixed |
The property value or the value of a behavior's property |
---|---|---|
throws | yii\base\UnknownPropertyException |
if the property is not defined |
throws | yii\base\InvalidCallException |
if the property is write-only. |
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
// read property, e.g. getName()
return $this->$getter();
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name;
}
}
if (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::__isset()
Checks if a property is set, i.e. defined and not null.
This method will check in the following order and act accordingly:
- a property defined by a setter: return whether the property is set
- a property of a behavior: return whether the property is set
- return
false
for non existing properties
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing isset($component->property)
.
public boolean __isset ( $name ) | ||
$name | string |
The property name or the event name |
return | boolean |
Whether the named property is set |
---|
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name !== null;
}
}
return false;
}
Defined in: yii\base\Component::__set()
Sets the value of a component property.
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value
- an event in the format of "on xyz": attach the handler to the event "xyz"
- a behavior in the format of "as xyz": attach the behavior named as "xyz"
- a property of a behavior: set the behavior property value
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $component->property = $value;
.
See also __get().
public void __set ( $name, $value ) | ||
$name | string |
The property name or the event name |
$value | mixed |
The property value |
throws | yii\base\UnknownPropertyException |
if the property is not defined |
---|---|---|
throws | yii\base\InvalidCallException |
if the property is read-only. |
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
// set property
$this->$setter($value);
return;
} elseif (strncmp($name, 'on ', 3) === 0) {
// on event: attach event handler
$this->on(trim(substr($name, 3)), $value);
return;
} elseif (strncmp($name, 'as ', 3) === 0) {
// as behavior: attach behavior
$name = trim(substr($name, 3));
$this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = $value;
return;
}
}
if (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\db\Connection::__sleep()
Close the connection before serializing.
public array __sleep ( ) |
public function __sleep()
{
$fields = (array) $this;
unset($fields['pdo']);
unset($fields["\000" . __CLASS__ . "\000" . '_master']);
unset($fields["\000" . __CLASS__ . "\000" . '_slave']);
unset($fields["\000" . __CLASS__ . "\000" . '_transaction']);
unset($fields["\000" . __CLASS__ . "\000" . '_schema']);
return array_keys($fields);
}
Defined in: yii\base\Component::__unset()
Sets a component property to be null.
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value to be null
- a property of a behavior: set the property value to be null
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing unset($component->property)
.
public void __unset ( $name ) | ||
$name | string |
The property name |
throws | yii\base\InvalidCallException |
if the property is read only. |
---|
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = null;
return;
}
}
throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::attachBehavior()
Attaches a behavior to this component.
This method will create the behavior object based on the given configuration. After that, the behavior object will be attached to this component by calling the yii\base\Behavior::attach() method.
See also detachBehavior().
public yii\base\Behavior attachBehavior ( $name, $behavior ) | ||
$name | string |
The name of the behavior. |
$behavior | string|array|yii\base\Behavior |
The behavior configuration. This can be one of the following:
|
return | yii\base\Behavior |
The behavior object |
---|
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
Defined in: yii\base\Component::attachBehaviors()
Attaches a list of behaviors to the component.
Each behavior is indexed by its name and should be a yii\base\Behavior object, a string specifying the behavior class, or an configuration array for creating the behavior.
See also attachBehavior().
public void attachBehaviors ( $behaviors ) | ||
$behaviors | array |
List of behaviors to be attached to the component |
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
Defined in: yii\db\Connection::beginTransaction()
Starts a transaction.
public yii\db\Transaction beginTransaction ( $isolationLevel = null ) | ||
$isolationLevel | string|null |
The isolation level to use for this transaction. See yii\db\Transaction::begin() for details. |
return | yii\db\Transaction |
The transaction initiated |
---|
public function beginTransaction($isolationLevel = null)
{
$this->open();
if (($transaction = $this->getTransaction()) === null) {
$transaction = $this->_transaction = new Transaction(['db' => $this]);
}
$transaction->begin($isolationLevel);
return $transaction;
}
Defined in: yii\base\Component::behaviors()
Returns a list of behaviors that this component should behave as.
Child classes may override this method to specify the behaviors they want to behave as.
The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
Note that a behavior class must extend from yii\base\Behavior. Behaviors can be attached using a name or anonymously. When a name is used as the array key, using this name, the behavior can later be retrieved using getBehavior() or be detached using detachBehavior(). Anonymous behaviors can not be retrieved or detached.
Behaviors declared in this method will be attached to the component automatically (on demand).
public array behaviors ( ) | ||
return | array |
The behavior configurations. |
---|
public function behaviors()
{
return [];
}
Defined in: yii\db\Connection::cache()
Uses query cache for the queries performed with the callable.
When query caching is enabled ($enableQueryCache is true and $queryCache refers to a valid cache), queries performed within the callable will be cached and their results will be fetched from cache if available. For example,
// The customer will be fetched from cache if available.
// If not, the query will be made against DB and cached for use next time.
$customer = $db->cache(function (Connection $db) {
return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
});
Note that query cache is only meaningful for queries that return results. For queries performed with yii\db\Command::execute(), query cache will not be used.
See also:
public mixed cache ( callable $callable, $duration = null, $dependency = null ) | ||
$callable | callable |
A PHP callable that contains DB queries which will make use of query cache.
The signature of the callable is |
$duration | integer|null |
The number of seconds that query results can remain valid in the cache. If this is not set, the value of $queryCacheDuration will be used instead. Use 0 to indicate that the cached data will never expire. |
$dependency | yii\caching\Dependency|null |
The cache dependency associated with the cached query results. |
return | mixed |
The return result of the callable |
---|---|---|
throws | Throwable |
if there is any exception during query |
public function cache(callable $callable, $duration = null, $dependency = null)
{
$this->_queryCacheInfo[] = [$duration === null ? $this->queryCacheDuration : $duration, $dependency];
try {
$result = call_user_func($callable, $this);
array_pop($this->_queryCacheInfo);
return $result;
} catch (\Exception $e) {
array_pop($this->_queryCacheInfo);
throw $e;
} catch (\Throwable $e) {
array_pop($this->_queryCacheInfo);
throw $e;
}
}
Defined in: yii\base\Component::canGetProperty()
Returns a value indicating whether a property can be read.
A property can be read if:
- the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a readable property of the given name (when
$checkBehaviors
is true).
See also canSetProperty().
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
$checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
return | boolean |
Whether the property can be read |
---|
public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
Defined in: yii\base\Component::canSetProperty()
Returns a value indicating whether a property can be set.
A property can be written if:
- the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a writable property of the given name (when
$checkBehaviors
is true).
See also canGetProperty().
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
$checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
return | boolean |
Whether the property can be written |
---|
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
::class
instead.
Defined in: yii\base\BaseObject::className()
Returns the fully qualified name of this class.
public static string className ( ) | ||
return | string |
The fully qualified name of this class. |
---|
public static function className()
{
return get_called_class();
}
Defined in: yii\db\Connection::close()
Closes the currently active DB connection.
It does nothing if the connection is already closed.
public void close ( ) |
public function close()
{
if ($this->_master) {
if ($this->pdo === $this->_master->pdo) {
$this->pdo = null;
}
$this->_master->close();
$this->_master = false;
}
if ($this->pdo !== null) {
Yii::debug('Closing DB connection: ' . $this->dsn, __METHOD__);
$this->pdo = null;
}
if ($this->_slave) {
$this->_slave->close();
$this->_slave = false;
}
$this->_schema = null;
$this->_transaction = null;
$this->_driverName = null;
$this->_queryCacheInfo = [];
$this->_quotedTableNames = null;
$this->_quotedColumnNames = null;
}
Creates a command for execution.
public yii\sphinx\Command createCommand ( $sql = null, $params = [] ) | ||
$sql | string |
The SQL statement to be executed |
$params | array |
The parameters to be bound to the SQL statement |
return | yii\sphinx\Command |
The Sphinx command |
---|
public function createCommand($sql = null, $params = [])
{
$command = new Command([
'db' => $this,
'sql' => $sql,
]);
return $command->bindValues($params);
}
Defined in: yii\db\Connection::createPdoInstance()
Creates the PDO instance.
This method is called by open() to establish a DB connection. The default implementation will create a PHP PDO instance. You may override this method if the default PDO needs to be adapted for certain DBMS.
protected PDO createPdoInstance ( ) | ||
return | PDO |
The pdo instance |
---|
protected function createPdoInstance()
{
$pdoClass = $this->pdoClass;
if ($pdoClass === null) {
$driver = null;
if ($this->_driverName !== null) {
$driver = $this->_driverName;
} elseif (($pos = strpos($this->dsn, ':')) !== false) {
$driver = strtolower(substr($this->dsn, 0, $pos));
}
switch ($driver) {
case 'mssql':
$pdoClass = 'yii\db\mssql\PDO';
break;
case 'dblib':
$pdoClass = 'yii\db\mssql\DBLibPDO';
break;
case 'sqlsrv':
$pdoClass = 'yii\db\mssql\SqlsrvPDO';
break;
default:
$pdoClass = 'PDO';
}
}
$dsn = $this->dsn;
if (strncmp('sqlite:@', $dsn, 8) === 0) {
$dsn = 'sqlite:' . Yii::getAlias(substr($dsn, 7));
}
return new $pdoClass($dsn, $this->username, $this->password, $this->attributes);
}
Defined in: yii\base\Component::detachBehavior()
Detaches a behavior from the component.
The behavior's yii\base\Behavior::detach() method will be invoked.
public yii\base\Behavior|null detachBehavior ( $name ) | ||
$name | string |
The behavior's name. |
return | yii\base\Behavior|null |
The detached behavior. Null if the behavior does not exist. |
---|
public function detachBehavior($name)
{
$this->ensureBehaviors();
if (isset($this->_behaviors[$name])) {
$behavior = $this->_behaviors[$name];
unset($this->_behaviors[$name]);
$behavior->detach();
return $behavior;
}
return null;
}
Defined in: yii\base\Component::detachBehaviors()
Detaches all behaviors from the component.
public void detachBehaviors ( ) |
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
Defined in: yii\base\Component::ensureBehaviors()
Makes sure that the behaviors declared in behaviors() are attached to this component.
public void ensureBehaviors ( ) |
public function ensureBehaviors()
{
if ($this->_behaviors === null) {
$this->_behaviors = [];
foreach ($this->behaviors() as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
}
Escapes all special characters from 'MATCH' statement argument.
Make sure you are using this method whenever composing 'MATCH' search statement. Note: this method does not perform quoting, you should place the result in the quotes an perform additional escaping for it manually, the best way to do it is using PDO parameter.
public string escapeMatchValue ( $str ) | ||
$str | string |
String to be escaped. |
return | string |
The properly escaped string. |
---|
public function escapeMatchValue($str)
{
return str_replace(
['\\', '/', '"', '(', ')', '|', '-', '!', '@', '~', '&', '^', '$', '=', '>', '<', "\x00", "\n", "\r", "\x1a"],
['\\\\', '\\/', '\\"', '\\(', '\\)', '\\|', '\\-', '\\!', '\\@', '\\~', '\\&', '\\^', '\\$', '\\=', '\\>', '\\<', "\\x00", "\\n", "\\r", "\\x1a"],
$str
);
}
Defined in: yii\base\Component::getBehavior()
Returns the named behavior object.
public yii\base\Behavior|null getBehavior ( $name ) | ||
$name | string |
The behavior name |
return | yii\base\Behavior|null |
The behavior object, or null if the behavior does not exist |
---|
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
Defined in: yii\base\Component::getBehaviors()
Returns all behaviors attached to this component.
public yii\base\Behavior[] getBehaviors ( ) | ||
return | yii\base\Behavior[] |
List of behaviors attached to this component |
---|
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
Defined in: yii\db\Connection::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.
public string|null getDriverName ( ) | ||
return | string|null |
Name of the DB driver |
---|
public function getDriverName()
{
if ($this->_driverName === null) {
if (($pos = strpos((string)$this->dsn, ':')) !== false) {
$this->_driverName = strtolower(substr($this->dsn, 0, $pos));
} else {
$this->_driverName = strtolower($this->getSlavePdo(true)->getAttribute(PDO::ATTR_DRIVER_NAME));
}
}
return $this->_driverName;
}
Obtains the schema information for the named index.
public yii\sphinx\IndexSchema getIndexSchema ( $name, $refresh = false ) | ||
$name | string |
Index name. |
$refresh | boolean |
Whether to reload the table schema even if it is found in the cache. |
return | yii\sphinx\IndexSchema |
Index schema information. Null if the named index does not exist. |
---|
public function getIndexSchema($name, $refresh = false)
{
return $this->getSchema()->getIndexSchema($name, $refresh);
}
Defined in: yii\db\Connection::getIsActive()
Returns a value indicating whether the DB connection is established.
public boolean getIsActive ( ) | ||
return | boolean |
Whether the DB connection is established |
---|
public function getIsActive()
{
return $this->pdo !== null;
}
This method is not supported by Sphinx.
public string getLastInsertID ( $sequenceName = '' ) | ||
$sequenceName | string |
Name of the sequence object |
return | string |
The row ID of the last row inserted, or the last value retrieved from the sequence object |
---|---|---|
throws | yii\base\NotSupportedException |
always. |
public function getLastInsertID($sequenceName = '')
{
throw new NotSupportedException('"' . __METHOD__ . '" is not supported.');
}
Defined in: yii\db\Connection::getMaster()
Returns the currently active master connection.
If this method is called for the first time, it will try to open a master connection.
public yii\db\Connection|null getMaster ( ) | ||
return | yii\db\Connection|null |
The currently active master connection. |
---|
public function getMaster()
{
if ($this->_master === false) {
$this->_master = $this->shuffleMasters
? $this->openFromPool($this->masters, $this->masterConfig)
: $this->openFromPoolSequentially($this->masters, $this->masterConfig);
}
return $this->_master;
}
Defined in: yii\db\Connection::getMasterPdo()
Returns the PDO instance for the currently active master connection.
This method will open the master DB connection and then return $pdo.
public PDO getMasterPdo ( ) | ||
return | PDO |
The PDO instance for the currently active master connection. |
---|
public function getMasterPdo()
{
$this->open();
return $this->pdo;
}
the query builder for this Sphinx connection
public yii\sphinx\QueryBuilder getQueryBuilder ( ) | ||
return | yii\sphinx\QueryBuilder |
---|
The schema information for this Sphinx connection
public yii\sphinx\Schema getSchema ( ) | ||
return | yii\sphinx\Schema |
---|
Defined in: yii\db\Connection::getServerVersion()
Returns a server version as a string comparable by \version_compare().
public string getServerVersion ( ) | ||
return | string |
Server version as a string. |
---|
public function getServerVersion()
{
return $this->getSchema()->getServerVersion();
}
Defined in: yii\db\Connection::getSlave()
Returns the currently active slave connection.
If this method is called for the first time, it will try to open a slave connection when $enableSlaves is true.
public yii\db\Connection|null getSlave ( $fallbackToMaster = true ) | ||
$fallbackToMaster | boolean |
Whether to return a master connection in case there is no slave connection available. |
return | yii\db\Connection|null |
The currently active slave connection. |
---|
public function getSlave($fallbackToMaster = true)
{
if (!$this->enableSlaves) {
return $fallbackToMaster ? $this : null;
}
if ($this->_slave === false) {
$this->_slave = $this->openFromPool($this->slaves, $this->slaveConfig);
}
return $this->_slave === null && $fallbackToMaster ? $this : $this->_slave;
}
Defined in: yii\db\Connection::getSlavePdo()
Returns the PDO instance for the currently active slave connection.
When $enableSlaves is true, one of the slaves will be used for read queries, and its PDO instance will be returned by this method.
public PDO|null getSlavePdo ( $fallbackToMaster = true ) | ||
$fallbackToMaster | boolean |
Whether to return a master PDO in case none of the slave connections is available. |
return | PDO|null |
The PDO instance for the currently active slave connection. |
---|
public function getSlavePdo($fallbackToMaster = true)
{
$db = $this->getSlave(false);
if ($db === null) {
return $fallbackToMaster ? $this->getMasterPdo() : null;
}
return $db->pdo;
}
Defined in: yii\db\Connection::getTableSchema()
Obtains the schema information for the named table.
public yii\db\TableSchema|null getTableSchema ( $name, $refresh = false ) | ||
$name | string |
Table name. |
$refresh | boolean |
Whether to reload the table schema even if it is found in the cache. |
return | yii\db\TableSchema|null |
Table schema information. Null if the named table does not exist. |
---|
public function getTableSchema($name, $refresh = false)
{
return $this->getSchema()->getTableSchema($name, $refresh);
}
Defined in: yii\db\Connection::getTransaction()
Returns the currently active transaction.
public yii\db\Transaction|null getTransaction ( ) | ||
return | yii\db\Transaction|null |
The currently active transaction. Null if no active transaction. |
---|
public function getTransaction()
{
return $this->_transaction && $this->_transaction->getIsActive() ? $this->_transaction : null;
}
Defined in: yii\base\Component::hasEventHandlers()
Returns a value indicating whether there is any handler attached to the named event.
public boolean hasEventHandlers ( $name ) | ||
$name | string |
The event name |
return | boolean |
Whether there is any handler attached to the event. |
---|
public function hasEventHandlers($name)
{
$this->ensureBehaviors();
if (!empty($this->_events[$name])) {
return true;
}
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
return true;
}
}
return Event::hasHandlers($this, $name);
}
Defined in: yii\base\Component::hasMethod()
Returns a value indicating whether a method is defined.
A method is defined if:
- the class has a method with the specified name
- an attached behavior has a method with the given name (when
$checkBehaviors
is true).
public boolean hasMethod ( $name, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkBehaviors | boolean |
Whether to treat behaviors' methods as methods of this component |
return | boolean |
Whether the method is defined |
---|
public function hasMethod($name, $checkBehaviors = true)
{
if (method_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->hasMethod($name)) {
return true;
}
}
}
return false;
}
Defined in: yii\base\Component::hasProperty()
Returns a value indicating whether a property is defined for this component.
A property is defined if:
- the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a property of the given name (when
$checkBehaviors
is true).
See also:
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
$checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
return | boolean |
Whether the property is defined |
---|
public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}
Defined in: yii\base\BaseObject::init()
Initializes the object.
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
public void init ( ) |
public function init()
{
}
Defined in: yii\db\Connection::initConnection()
Initializes the DB connection.
This method is invoked right after the DB connection is established.
The default implementation turns on PDO::ATTR_EMULATE_PREPARES
if $emulatePrepare is true, and sets the database $charset if it is not empty.
It then triggers an EVENT_AFTER_OPEN event.
protected void initConnection ( ) |
protected function initConnection()
{
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($this->emulatePrepare !== null && constant('PDO::ATTR_EMULATE_PREPARES')) {
if ($this->driverName !== 'sqlsrv') {
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare);
}
}
if (PHP_VERSION_ID >= 80100 && $this->getDriverName() === 'sqlite') {
$this->pdo->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, true);
}
if (!$this->isSybase && in_array($this->getDriverName(), ['mssql', 'dblib'], true)) {
$this->pdo->exec('SET ANSI_NULL_DFLT_ON ON');
}
if ($this->charset !== null && in_array($this->getDriverName(), ['pgsql', 'mysql', 'mysqli', 'cubrid'], true)) {
$this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset));
}
$this->trigger(self::EVENT_AFTER_OPEN);
}
Defined in: yii\db\Connection::noCache()
Disables query cache temporarily.
Queries performed within the callable will not use query cache at all. For example,
$db->cache(function (Connection $db) {
// ... queries that use query cache ...
return $db->noCache(function (Connection $db) {
// this query will not use query cache
return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
});
});
See also:
public mixed noCache ( callable $callable ) | ||
$callable | callable |
A PHP callable that contains DB queries which should not use query cache.
The signature of the callable is |
return | mixed |
The return result of the callable |
---|---|---|
throws | Throwable |
if there is any exception during query |
public function noCache(callable $callable)
{
$this->_queryCacheInfo[] = false;
try {
$result = call_user_func($callable, $this);
array_pop($this->_queryCacheInfo);
return $result;
} catch (\Exception $e) {
array_pop($this->_queryCacheInfo);
throw $e;
} catch (\Throwable $e) {
array_pop($this->_queryCacheInfo);
throw $e;
}
}
Defined in: yii\base\Component::off()
Detaches an existing event handler from this component.
This method is the opposite of on().
Note: in case wildcard pattern is passed for event name, only the handlers registered with this wildcard will be removed, while handlers registered with plain names matching this wildcard will remain.
See also on().
public boolean off ( $name, $handler = null ) | ||
$name | string |
Event name |
$handler | callable|null |
The event handler to be removed. If it is null, all handlers attached to the named event will be removed. |
return | boolean |
If a handler is found and detached |
---|
public function off($name, $handler = null)
{
$this->ensureBehaviors();
if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
return false;
}
if ($handler === null) {
unset($this->_events[$name], $this->_eventWildcards[$name]);
return true;
}
$removed = false;
// plain event names
if (isset($this->_events[$name])) {
foreach ($this->_events[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_events[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_events[$name] = array_values($this->_events[$name]);
return true;
}
}
// wildcard event names
if (isset($this->_eventWildcards[$name])) {
foreach ($this->_eventWildcards[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_eventWildcards[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
// remove empty wildcards to save future redundant regex checks:
if (empty($this->_eventWildcards[$name])) {
unset($this->_eventWildcards[$name]);
}
}
}
return $removed;
}
Defined in: yii\base\Component::on()
Attaches an event handler to an event.
The event handler must be a valid PHP callback. The following are some examples:
function ($event) { ... } // anonymous function
[$object, 'handleClick'] // $object->handleClick()
['Page', 'handleClick'] // Page::handleClick()
'handleClick' // global function handleClick()
The event handler must be defined with the following signature,
function ($event)
where $event
is an yii\base\Event object which includes parameters associated with the event.
Since 2.0.14 you can specify event name as a wildcard pattern:
$component->on('event.group.*', function ($event) {
Yii::trace($event->name . ' is triggered.');
});
See also off().
public void on ( $name, $handler, $data = null, $append = true ) | ||
$name | string |
The event name |
$handler | callable |
The event handler |
$data | mixed |
The data to be passed to the event handler when the event is triggered. When the event handler is invoked, this data can be accessed via yii\base\Event::$data. |
$append | boolean |
Whether to append new event handler to the end of the existing handler list. If false, the new handler will be inserted at the beginning of the existing handler list. |
public function on($name, $handler, $data = null, $append = true)
{
$this->ensureBehaviors();
if (strpos($name, '*') !== false) {
if ($append || empty($this->_eventWildcards[$name])) {
$this->_eventWildcards[$name][] = [$handler, $data];
} else {
array_unshift($this->_eventWildcards[$name], [$handler, $data]);
}
return;
}
if ($append || empty($this->_events[$name])) {
$this->_events[$name][] = [$handler, $data];
} else {
array_unshift($this->_events[$name], [$handler, $data]);
}
}
Defined in: yii\db\Connection::open()
Establishes a DB connection.
It does nothing if a DB connection has already been established.
public void open ( ) | ||
throws | yii\db\Exception |
if connection fails |
---|
public function open()
{
if ($this->pdo !== null) {
return;
}
if (!empty($this->masters)) {
$db = $this->getMaster();
if ($db !== null) {
$this->pdo = $db->pdo;
return;
}
throw new InvalidConfigException('None of the master DB servers is available.');
}
if (empty($this->dsn)) {
throw new InvalidConfigException('Connection::dsn cannot be empty.');
}
$token = 'Opening DB connection: ' . $this->dsn;
$enableProfiling = $this->enableProfiling;
try {
if ($this->enableLogging) {
Yii::info($token, __METHOD__);
}
if ($enableProfiling) {
Yii::beginProfile($token, __METHOD__);
}
$this->pdo = $this->createPdoInstance();
$this->initConnection();
if ($enableProfiling) {
Yii::endProfile($token, __METHOD__);
}
} catch (\PDOException $e) {
if ($enableProfiling) {
Yii::endProfile($token, __METHOD__);
}
throw new Exception($e->getMessage(), $e->errorInfo, $e->getCode(), $e);
}
}
Defined in: yii\db\Connection::openFromPool()
Opens the connection to a server in the pool.
This method implements load balancing and failover among the given list of the servers. Connections will be tried in random order. For details about the failover behavior, see openFromPoolSequentially().
See also openFromPoolSequentially().
protected yii\db\Connection|null openFromPool ( array $pool, array $sharedConfig ) | ||
$pool | array |
The list of connection configurations in the server pool |
$sharedConfig | array |
The configuration common to those given in |
return | yii\db\Connection|null |
The opened DB connection, or |
---|---|---|
throws | yii\base\InvalidConfigException |
if a configuration does not specify "dsn" |
protected function openFromPool(array $pool, array $sharedConfig)
{
shuffle($pool);
return $this->openFromPoolSequentially($pool, $sharedConfig);
}
Defined in: yii\db\Connection::openFromPoolSequentially()
Opens the connection to a server in the pool.
This method implements failover among the given list of servers. Connections will be tried in sequential order. The first successful connection will return.
If $serverStatusCache is configured, this method will cache information about unreachable servers and does not try to connect to these for the time configured in $serverRetryInterval. This helps to keep the application stable when some servers are unavailable. Avoiding connection attempts to unavailable servers saves time when the connection attempts fail due to timeout.
If none of the servers are available the status cache is ignored and connection attempts are made to all servers (Since version 2.0.35). This is to avoid downtime when all servers are unavailable for a short time. After a successful connection attempt the server is marked as available again.
See also:
protected yii\db\Connection|null openFromPoolSequentially ( array $pool, array $sharedConfig ) | ||
$pool | array |
The list of connection configurations in the server pool |
$sharedConfig | array |
The configuration common to those given in |
return | yii\db\Connection|null |
The opened DB connection, or |
---|---|---|
throws | yii\base\InvalidConfigException |
if a configuration does not specify "dsn" |
protected function openFromPoolSequentially(array $pool, array $sharedConfig)
{
if (empty($pool)) {
return null;
}
if (!isset($sharedConfig['class'])) {
$sharedConfig['class'] = get_class($this);
}
$cache = is_string($this->serverStatusCache) ? Yii::$app->get($this->serverStatusCache, false) : $this->serverStatusCache;
foreach ($pool as $i => $config) {
$pool[$i] = $config = array_merge($sharedConfig, $config);
if (empty($config['dsn'])) {
throw new InvalidConfigException('The "dsn" option must be specified.');
}
$key = [__METHOD__, $config['dsn']];
if ($cache instanceof CacheInterface && $cache->get($key)) {
// should not try this dead server now
continue;
}
/* @var $db Connection */
$db = Yii::createObject($config);
try {
$db->open();
return $db;
} catch (\Exception $e) {
Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__);
if ($cache instanceof CacheInterface) {
// mark this server as dead and only retry it after the specified interval
$cache->set($key, 1, $this->serverRetryInterval);
}
// exclude server from retry below
unset($pool[$i]);
}
}
if ($cache instanceof CacheInterface) {
// if server status cache is enabled and no server is available
// ignore the cache and try to connect anyway
// $pool now only contains servers we did not already try in the loop above
foreach ($pool as $config) {
/* @var $db Connection */
$db = Yii::createObject($config);
try {
$db->open();
} catch (\Exception $e) {
Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__);
continue;
}
// mark this server as available again after successful connection
$cache->delete([__METHOD__, $config['dsn']]);
return $db;
}
}
return null;
}
Defined in: yii\db\Connection::quoteColumnName()
Quotes a column name for use in a query.
If the column name contains prefix, the prefix will also be properly quoted. If the column name is already quoted or contains special characters including '(', '[[' and '{{', then this method will do nothing.
public string quoteColumnName ( $name ) | ||
$name | string |
Column name |
return | string |
The properly quoted column name |
---|
public function quoteColumnName($name)
{
if (isset($this->_quotedColumnNames[$name])) {
return $this->_quotedColumnNames[$name];
}
return $this->_quotedColumnNames[$name] = $this->getSchema()->quoteColumnName($name);
}
Quotes a index name for use in a query.
If the index name contains schema prefix, the prefix will also be properly quoted. If the index name is already quoted or contains special characters including '(', '[[' and '{{', then this method will do nothing.
public string quoteIndexName ( $name ) | ||
$name | string |
Index name |
return | string |
The properly quoted index name |
---|
public function quoteIndexName($name)
{
return $this->getSchema()->quoteIndexName($name);
}
Defined in: yii\db\Connection::quoteSql()
Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
Tokens enclosed within double curly brackets are treated as table names, while tokens enclosed within double square brackets are column names. They will be quoted accordingly. Also, the percentage character "%" at the beginning or ending of a table name will be replaced with $tablePrefix.
public string quoteSql ( $sql ) | ||
$sql | string |
The SQL to be quoted |
return | string |
The quoted SQL |
---|
public function quoteSql($sql)
{
return preg_replace_callback(
'/(\\{\\{(%?[\w\-\. ]+%?)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/',
function ($matches) {
if (isset($matches[3])) {
return $this->quoteColumnName($matches[3]);
}
return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
},
$sql
);
}
Alias of quoteIndexName().
public string quoteTableName ( $name ) | ||
$name | string |
Table name |
return | string |
The properly quoted table name |
---|
public function quoteTableName($name)
{
return $this->quoteIndexName($name);
}
Defined in: yii\db\Connection::quoteValue()
Quotes a string value for use in a query.
Note that if the parameter is not a string, it will be returned without change.
public string quoteValue ( $value ) | ||
$value | string |
String to be quoted |
return | string |
The properly quoted string |
---|
public function quoteValue($value)
{
return $this->getSchema()->quoteValue($value);
}
Defined in: yii\db\Connection::setDriverName()
Changes the current driver name.
public void setDriverName ( $driverName ) | ||
$driverName | string |
Name of the DB driver |
public function setDriverName($driverName)
{
$this->_driverName = strtolower($driverName);
}
Defined in: yii\db\Connection::setQueryBuilder()
Can be used to set yii\db\QueryBuilder configuration via Connection configuration array.
public void setQueryBuilder ( $value ) | ||
$value | array |
The yii\db\QueryBuilder properties to be configured. |
public function setQueryBuilder($value)
{
Yii::configure($this->getQueryBuilder(), $value);
$this->_queryBuilderConfigurations[] = $value;
}
Defined in: yii\db\Connection::transaction()
Executes callback provided in a transaction.
public mixed transaction ( callable $callback, $isolationLevel = null ) | ||
$callback | callable |
A valid PHP callback that performs the job. Accepts connection instance as parameter. |
$isolationLevel | string|null |
The isolation level to use for this transaction. See yii\db\Transaction::begin() for details. |
return | mixed |
Result of callback function |
---|---|---|
throws | Throwable |
if there is any exception during query. In this case the transaction will be rolled back. |
public function transaction(callable $callback, $isolationLevel = null)
{
$transaction = $this->beginTransaction($isolationLevel);
$level = $transaction->level;
try {
$result = call_user_func($callback, $this);
if ($transaction->isActive && $transaction->level === $level) {
$transaction->commit();
}
} catch (\Exception $e) {
$this->rollbackTransactionOnLevel($transaction, $level);
throw $e;
} catch (\Throwable $e) {
$this->rollbackTransactionOnLevel($transaction, $level);
throw $e;
}
return $result;
}
Defined in: yii\base\Component::trigger()
Triggers an event.
This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.
public void trigger ( $name, yii\base\Event $event = null ) | ||
$name | string |
The event name |
$event | yii\base\Event|null |
The event instance. If not set, a default yii\base\Event object will be created. |
public function trigger($name, Event $event = null)
{
$this->ensureBehaviors();
$eventHandlers = [];
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (StringHelper::matchWildcard($wildcard, $name)) {
$eventHandlers[] = $handlers;
}
}
if (!empty($this->_events[$name])) {
$eventHandlers[] = $this->_events[$name];
}
if (!empty($eventHandlers)) {
$eventHandlers = call_user_func_array('array_merge', $eventHandlers);
if ($event === null) {
$event = new Event();
}
if ($event->sender === null) {
$event->sender = $this;
}
$event->handled = false;
$event->name = $name;
foreach ($eventHandlers as $handler) {
$event->data = $handler[1];
call_user_func($handler[0], $event);
// stop further handling if the event is handled
if ($event->handled) {
return;
}
}
}
// invoke class-level attached handlers
Event::trigger($this, $name, $event);
}
Defined in: yii\db\Connection::useMaster()
Executes the provided callback by using the master connection.
This method is provided so that you can temporarily force using the master connection to perform DB operations even if they are read queries. For example,
$result = $db->useMaster(function ($db) {
return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
});
public mixed useMaster ( callable $callback ) | ||
$callback | callable |
A PHP callable to be executed by this method. Its signature is
|
return | mixed |
The return value of the callback |
---|---|---|
throws | Throwable |
if there is any exception thrown from the callback |
public function useMaster(callable $callback)
{
if ($this->enableSlaves) {
$this->enableSlaves = false;
try {
$result = call_user_func($callback, $this);
} catch (\Exception $e) {
$this->enableSlaves = true;
throw $e;
} catch (\Throwable $e) {
$this->enableSlaves = true;
throw $e;
}
// TODO: use "finally" keyword when miminum required PHP version is >= 5.5
$this->enableSlaves = true;
} else {
$result = call_user_func($callback, $this);
}
return $result;
}