0 follower

Abstract Class Yiisoft\Db\Driver\Pdo\AbstractPdoConnection

InheritanceYiisoft\Db\Driver\Pdo\AbstractPdoConnection » Yiisoft\Db\Connection\AbstractConnection
ImplementsPsr\Log\LoggerAwareInterface, Yiisoft\Db\Connection\ConnectionInterface, Yiisoft\Db\Driver\Pdo\PdoConnectionInterface, Yiisoft\Db\Profiler\ProfilerAwareInterface
Uses TraitsPsr\Log\LoggerAwareTrait, Yiisoft\Db\Profiler\ProfilerAwareTrait

Represents a connection to a database using the PDO (PHP Data Objects) extension.

It provides a set of methods for interacting with a database using PDO, such as executing SQL statements, preparing and executing statements, and managing transactions.

The ConnectionPDO classes extend from this class, which is a base class for representing a connection to a database.

It implements the ConnectionInterface, which defines the interface for interacting with a database connection.

Public Methods

Hide inherited methods

Method Description Defined By
__clone() Reset the connection after cloning. Yiisoft\Db\Driver\Pdo\AbstractPdoConnection
__construct() Yiisoft\Db\Driver\Pdo\AbstractPdoConnection
__sleep() Close the connection before serializing. Yiisoft\Db\Driver\Pdo\AbstractPdoConnection
beginTransaction() Yiisoft\Db\Driver\Pdo\AbstractPdoConnection
close() Yiisoft\Db\Driver\Pdo\AbstractPdoConnection
createBatchQueryResult() Yiisoft\Db\Connection\AbstractConnection
createCommand() Creates a command for execution. Yiisoft\Db\Connection\ConnectionInterface
createQuery() Yiisoft\Db\Connection\AbstractConnection
createTransaction() Create a transaction instance. Yiisoft\Db\Connection\ConnectionInterface
getActivePdo() Yiisoft\Db\Driver\Pdo\AbstractPdoConnection
getColumnBuilderClass() Yiisoft\Db\Connection\AbstractConnection
getColumnFactory() Returns the column factory for creating column instances. Yiisoft\Db\Connection\ConnectionInterface
getDriver() Yiisoft\Db\Driver\Pdo\AbstractPdoConnection
getDriverName() Yiisoft\Db\Driver\Pdo\AbstractPdoConnection
getEmulatePrepare() Yiisoft\Db\Driver\Pdo\AbstractPdoConnection
getLastInsertId() Yiisoft\Db\Driver\Pdo\AbstractPdoConnection
getPdo() Yiisoft\Db\Driver\Pdo\AbstractPdoConnection
getQueryBuilder() Returns the query builder for the current DB connection. Yiisoft\Db\Connection\ConnectionInterface
getQuoter() Return quoter helper for current DB connection. Yiisoft\Db\Connection\ConnectionInterface
getSchema() Returns the schema information for the database opened by this connection. Yiisoft\Db\Connection\ConnectionInterface
getServerInfo() Yiisoft\Db\Driver\Pdo\AbstractPdoConnection
getTablePrefix() Yiisoft\Db\Connection\AbstractConnection
getTableSchema() Yiisoft\Db\Connection\AbstractConnection
getTransaction() Yiisoft\Db\Connection\AbstractConnection
isActive() Yiisoft\Db\Driver\Pdo\AbstractPdoConnection
isSavepointEnabled() Yiisoft\Db\Connection\AbstractConnection
open() Yiisoft\Db\Driver\Pdo\AbstractPdoConnection
quoteValue() Yiisoft\Db\Driver\Pdo\AbstractPdoConnection
select() Yiisoft\Db\Connection\AbstractConnection
setEmulatePrepare() Yiisoft\Db\Driver\Pdo\AbstractPdoConnection
setEnableSavepoint() Yiisoft\Db\Connection\AbstractConnection
setProfiler() Yiisoft\Db\Profiler\ProfilerAwareTrait
setTablePrefix() Yiisoft\Db\Driver\Pdo\AbstractPdoConnection
transaction() Yiisoft\Db\Connection\AbstractConnection

Property Details

Hide inherited properties

$columnFactory protected property
$driver protected property
$emulatePrepare protected property
protected boolean|null $emulatePrepare null
$pdo protected property
protected PDO|null $pdo null
$queryBuilder protected property
$quoter protected property
$schema protected property
$schemaCache protected property
$serverInfo protected property

Method Details

Hide inherited methods

__clone() public method

Reset the connection after cloning.

public mixed __clone ( )

                public function __clone()
{
    $this->transaction = null;
    $this->pdo = null;
}

            
__construct() public method

public mixed __construct ( Yiisoft\Db\Driver\Pdo\PdoDriverInterface $driver, Yiisoft\Db\Cache\SchemaCache $schemaCache, Yiisoft\Db\Schema\Column\ColumnFactoryInterface|null $columnFactory null )
$driver Yiisoft\Db\Driver\Pdo\PdoDriverInterface
$schemaCache Yiisoft\Db\Cache\SchemaCache
$columnFactory Yiisoft\Db\Schema\Column\ColumnFactoryInterface|null

                public function __construct(
    protected PdoDriverInterface $driver,
    protected SchemaCache $schemaCache,
    protected ?ColumnFactoryInterface $columnFactory = null,
) {}

            
__sleep() public method

Close the connection before serializing.

public array __sleep ( )

                public function __sleep(): array
{
    $fields = (array) $this;
    unset(
        $fields["\000*\000" . 'pdo'],
        $fields["\000*\000" . 'transaction'],
        $fields["\000*\000" . 'schema'],
    );
    return array_keys($fields);
}

            
beginTransaction() public method

public Yiisoft\Db\Transaction\TransactionInterface beginTransaction ( string|null $isolationLevel null )
$isolationLevel string|null

                public function beginTransaction(?string $isolationLevel = null): TransactionInterface
{
    $transaction = parent::beginTransaction($isolationLevel);
    if ($this->logger !== null && $transaction instanceof LoggerAwareInterface) {
        $transaction->setLogger($this->logger);
    }
    return $transaction;
}

            
close() public method

public void close ( )

                public function close(): void
{
    if ($this->pdo !== null) {
        $this->logger?->log(
            LogLevel::DEBUG,
            'Closing DB connection: ' . $this->driver->getDsn() . ' ' . __METHOD__,
            ['type' => LogType::CONNECTION],
        );
        $this->pdo = null;
        $this->transaction = null;
    }
}

            
createBatchQueryResult() public method
public Yiisoft\Db\Query\BatchQueryResultInterface createBatchQueryResult ( Yiisoft\Db\Query\QueryInterface $query )
$query Yiisoft\Db\Query\QueryInterface

                public function createBatchQueryResult(QueryInterface $query): BatchQueryResultInterface
{
    return (new BatchQueryResult($query))
        ->indexBy($query->getIndexBy())
        ->resultCallback($query->getResultCallback());
}

            
createCommand() public abstract method

Defined in: Yiisoft\Db\Connection\ConnectionInterface::createCommand()

Creates a command for execution.

public abstract Yiisoft\Db\Command\CommandInterface createCommand ( string|null $sql null, array $params = [] )
$sql string|null

The SQL statement to execute.

$params array

The parameters to bind to the SQL statement.

return Yiisoft\Db\Command\CommandInterface

The database command instance.

throws Yiisoft\Db\Exception\Exception
throws Yiisoft\Db\Exception\InvalidConfigException

                public function createCommand(?string $sql = null, array $params = []): CommandInterface;

            
createQuery() public method
public Yiisoft\Db\Query\QueryInterface createQuery ( )

                public function createQuery(): QueryInterface
{
    return new Query($this);
}

            
createTransaction() public abstract method

Defined in: Yiisoft\Db\Connection\ConnectionInterface::createTransaction()

Create a transaction instance.

public abstract Yiisoft\Db\Transaction\TransactionInterface createTransaction ( )
return Yiisoft\Db\Transaction\TransactionInterface

The transaction instance.

                public function createTransaction(): TransactionInterface;

            
getActivePdo() public method

public PDO getActivePdo ( )

                public function getActivePdo(): PDO
{
    $this->open();
    $pdo = $this->getPdo();
    if ($pdo === null) {
        throw new Exception('PDO cannot be initialized.');
    }
    return $pdo;
}

            
getColumnBuilderClass() public method
public string getColumnBuilderClass ( )

                public function getColumnBuilderClass(): string
{
    return ColumnBuilder::class;
}

            
getColumnFactory() public abstract method

Defined in: Yiisoft\Db\Connection\ConnectionInterface::getColumnFactory()

Returns the column factory for creating column instances.

public abstract Yiisoft\Db\Schema\Column\ColumnFactoryInterface getColumnFactory ( )

                public function getColumnFactory(): ColumnFactoryInterface;

            
getDriver() public method

public Yiisoft\Db\Driver\Pdo\PdoDriverInterface getDriver ( )

                public function getDriver(): PdoDriverInterface
{
    return $this->driver;
}

            
getDriverName() public method

public string getDriverName ( )

                public function getDriverName(): string
{
    return $this->driver->getDriverName();
}

            
getEmulatePrepare() public method

public boolean|null getEmulatePrepare ( )

                public function getEmulatePrepare(): ?bool
{
    return $this->emulatePrepare;
}

            
getLastInsertId() public method

public string getLastInsertId ( string|null $sequenceName null )
$sequenceName string|null

                public function getLastInsertId(?string $sequenceName = null): string
{
    if ($this->pdo !== null) {
        return $this->pdo->lastInsertID($sequenceName ?? null);
    }
    throw new InvalidCallException('DB Connection is not active.');
}

            
getPdo() public method

public PDO|null getPdo ( )

                public function getPdo(): ?PDO
{
    return $this->pdo;
}

            
getQueryBuilder() public abstract method

Defined in: Yiisoft\Db\Connection\ConnectionInterface::getQueryBuilder()

Returns the query builder for the current DB connection.

public abstract Yiisoft\Db\QueryBuilder\QueryBuilderInterface getQueryBuilder ( )
return Yiisoft\Db\QueryBuilder\QueryBuilderInterface

The query builder for the current DB connection.

                public function getQueryBuilder(): QueryBuilderInterface;

            
getQuoter() public abstract method

Defined in: Yiisoft\Db\Connection\ConnectionInterface::getQuoter()

Return quoter helper for current DB connection.

public abstract Yiisoft\Db\Schema\QuoterInterface getQuoter ( )
return Yiisoft\Db\Schema\QuoterInterface

The quoter helper for the current DB connection.

                public function getQuoter(): QuoterInterface;

            
getSchema() public abstract method

Defined in: Yiisoft\Db\Connection\ConnectionInterface::getSchema()

Returns the schema information for the database opened by this connection.

public abstract Yiisoft\Db\Schema\SchemaInterface getSchema ( )
return Yiisoft\Db\Schema\SchemaInterface

The schema information for the database opened by this connection.

                public function getSchema(): SchemaInterface;

            
getServerInfo() public method

public Yiisoft\Db\Connection\ServerInfoInterface getServerInfo ( )

                public function getServerInfo(): ServerInfoInterface
{
    return $this->serverInfo ??= new PdoServerInfo($this);
}

            
getTablePrefix() public method
public string getTablePrefix ( )

                public function getTablePrefix(): string
{
    return $this->tablePrefix;
}

            
getTableSchema() public method
public Yiisoft\Db\Schema\TableSchemaInterface|null getTableSchema ( string $name, boolean $refresh false )
$name string
$refresh boolean

                public function getTableSchema(string $name, bool $refresh = false): ?TableSchemaInterface
{
    return $this->getSchema()->getTableSchema($name, $refresh);
}

            
getTransaction() public method
public Yiisoft\Db\Transaction\TransactionInterface|null getTransaction ( )

                public function getTransaction(): ?TransactionInterface
{
    return $this->transaction && $this->transaction->isActive() ? $this->transaction : null;
}

            
initConnection() protected method

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 {@see \Yiisoft\Db\Driver\Pdo\getEmulatePrepare()} is true.

protected void initConnection ( )

                protected function initConnection(): void
{
    if ($this->getEmulatePrepare() !== null) {
        $this->driver->attributes([PDO::ATTR_EMULATE_PREPARES => $this->getEmulatePrepare()]);
    }
    $this->pdo = $this->driver->createConnection();
}

            
isActive() public method

public boolean isActive ( )

                public function isActive(): bool
{
    return $this->pdo !== null;
}

            
isSavepointEnabled() public method
public boolean isSavepointEnabled ( )

                public function isSavepointEnabled(): bool
{
    return $this->enableSavepoint;
}

            
open() public method

public void open ( )

                public function open(): void
{
    if ($this->pdo instanceof PDO) {
        return;
    }
    if ($this->driver->getDsn() === '') {
        throw new InvalidConfigException('Connection::dsn cannot be empty.');
    }
    $token = 'Opening DB connection: ' . $this->driver->getDsn();
    $connectionContext = new ConnectionContext(__METHOD__);
    try {
        $this->logger?->log(LogLevel::INFO, $token, ['type' => LogType::CONNECTION]);
        $this->profiler?->begin($token, $connectionContext);
        $this->initConnection();
        $this->profiler?->end($token, $connectionContext);
    } catch (PDOException $e) {
        $this->profiler?->end($token, $connectionContext->setException($e));
        $this->logger?->log(LogLevel::ERROR, $token, ['type' => LogType::CONNECTION]);
        throw new Exception($e->getMessage(), (array) $e->errorInfo, $e);
    }
}

            
quoteValue() public method

public mixed quoteValue ( mixed $value )
$value mixed

                public function quoteValue(mixed $value): mixed
{
    if (is_string($value) === false) {
        return $value;
    }
    return $this->getActivePdo()->quote($value);
}

            
rollbackTransactionOnLevel() protected method

protected void rollbackTransactionOnLevel ( Yiisoft\Db\Transaction\TransactionInterface $transaction, integer $level )
$transaction Yiisoft\Db\Transaction\TransactionInterface
$level integer

                protected function rollbackTransactionOnLevel(TransactionInterface $transaction, int $level): void
{
    if ($transaction->isActive() && $transaction->getLevel() === $level) {
        /**
         * @link https://github.com/yiisoft/yii2/pull/13347
         */
        try {
            $transaction->rollBack();
        } catch (Throwable $e) {
            $this->logger?->log(LogLevel::ERROR, (string) $e, [__METHOD__, 'type' => LogType::TRANSACTION]);
            /** hide this exception to be able to continue throwing original exception outside */
        }
    }
}

            
select() public method
public Yiisoft\Db\Query\QueryInterface select ( array|boolean|float|integer|string|Yiisoft\Db\Expression\ExpressionInterface $columns = [], string|null $option null )
$columns array|boolean|float|integer|string|Yiisoft\Db\Expression\ExpressionInterface
$option string|null

                public function select(
    array|bool|float|int|string|ExpressionInterface $columns = [],
    ?string $option = null,
): QueryInterface {
    return $this->createQuery()->select($columns, $option);
}

            
setEmulatePrepare() public method

public void setEmulatePrepare ( boolean $value )
$value boolean

                public function setEmulatePrepare(bool $value): void
{
    $this->emulatePrepare = $value;
}

            
setEnableSavepoint() public method
public void setEnableSavepoint ( boolean $value )
$value boolean

                public function setEnableSavepoint(bool $value): void
{
    $this->enableSavepoint = $value;
}

            
setProfiler() public method
public void setProfiler ( Yiisoft\Db\Profiler\ProfilerInterface|null $profiler )
$profiler Yiisoft\Db\Profiler\ProfilerInterface|null

                public function setProfiler(?ProfilerInterface $profiler): void
{
    $this->profiler = $profiler;
}

            
setTablePrefix() public method

public void setTablePrefix ( string $value )
$value string

                public function setTablePrefix(string $value): void
{
    parent::setTablePrefix($value);
    if ($this->quoter !== null && method_exists($this->quoter, 'setTablePrefix')) {
        $this->quoter->setTablePrefix($value);
    }
}

            
transaction() public method
public mixed transaction ( Closure $closure, string|null $isolationLevel null )
$closure Closure
$isolationLevel string|null

                public function transaction(Closure $closure, ?string $isolationLevel = null): mixed
{
    $transaction = $this->beginTransaction($isolationLevel);
    $level = $transaction->getLevel();
    try {
        $result = $closure($this);
        if ($transaction->isActive() && $transaction->getLevel() === $level) {
            $transaction->commit();
        }
    } catch (Throwable $e) {
        $this->rollbackTransactionOnLevel($transaction, $level);
        throw $e;
    }
    return $result;
}