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() Creates Yiisoft\Db\Transaction\TransactionInterface 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() Returns 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 __clone( ): mixed

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

            
__construct() public method

public __construct( Yiisoft\Db\Driver\Pdo\PdoDriverInterface $driver, Yiisoft\Db\Cache\SchemaCache $schemaCache, Yiisoft\Db\Schema\Column\ColumnFactoryInterface|null $columnFactory null ): mixed
$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 __sleep( ): array

                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 beginTransaction( string|null $isolationLevel null ): Yiisoft\Db\Transaction\TransactionInterface
$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 close( ): void

                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 createBatchQueryResult( Yiisoft\Db\Query\QueryInterface $query ): Yiisoft\Db\Query\BatchQueryResultInterface
$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 createCommand( string|null $sql null, array $params = [] ): Yiisoft\Db\Command\CommandInterface
$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.

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

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

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

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

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

The transaction.

                public function createTransaction(): TransactionInterface;

            
getActivePdo() public method

public getActivePdo( ): PDO

                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 getColumnBuilderClass( ): string

                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 getColumnFactory( ): Yiisoft\Db\Schema\Column\ColumnFactoryInterface

                public function getColumnFactory(): ColumnFactoryInterface;

            
getDriver() public method

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

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

            
getDriverName() public method

public getDriverName( ): string

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

            
getEmulatePrepare() public method

public getEmulatePrepare( ): boolean|null

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

            
getLastInsertId() public method

public getLastInsertId( string|null $sequenceName null ): string
$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 getPdo( ): PDO|null

                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 getQueryBuilder( ): Yiisoft\Db\QueryBuilder\QueryBuilderInterface
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()

Returns quoter helper for current DB connection.

public abstract getQuoter( ): Yiisoft\Db\Schema\QuoterInterface
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 getSchema( ): Yiisoft\Db\Schema\SchemaInterface
return Yiisoft\Db\Schema\SchemaInterface

The schema information for the database opened by this connection.

                public function getSchema(): SchemaInterface;

            
getServerInfo() public method

public getServerInfo( ): Yiisoft\Db\Connection\ServerInfoInterface

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

            
getTablePrefix() public method
public getTablePrefix( ): string

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

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

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

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

                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 getEmulatePrepare() is true.

protected initConnection( ): void

                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 isActive( ): boolean

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

            
isSavepointEnabled() public method
public isSavepointEnabled( ): boolean

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

            
open() public method

public open( ): void

                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 quoteValue( mixed $value ): mixed
$value mixed

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

            
rollbackTransactionOnLevel() protected method

protected rollbackTransactionOnLevel( Yiisoft\Db\Transaction\TransactionInterface $transaction, integer $level ): void
$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 select( array|boolean|float|integer|string|Yiisoft\Db\Expression\ExpressionInterface $columns = [], string|null $option null ): Yiisoft\Db\Query\QueryInterface
$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 setEmulatePrepare( boolean $value ): void
$value boolean

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

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

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

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

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

            
setTablePrefix() public method

public setTablePrefix( string $value ): void
$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 transaction( Closure $closure, string|null $isolationLevel null ): mixed
$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;
}