Passed
Pull Request — master (#684)
by Def
02:11
created

AbstractPdoConnection::beginTransaction()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 2
nop 1
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Driver\Pdo;
6
7
use PDO;
8
use PDOException;
9
use Psr\Log\LoggerAwareInterface;
10
use Psr\Log\LoggerAwareTrait;
11
use Psr\Log\LogLevel;
12
use Throwable;
13
use Yiisoft\Db\Cache\SchemaCache;
14
use Yiisoft\Db\Connection\AbstractConnection;
15
use Yiisoft\Db\Exception\Exception;
16
use Yiisoft\Db\Exception\InvalidCallException;
17
use Yiisoft\Db\Exception\InvalidConfigException;
18
use Yiisoft\Db\Profiler\Context\ConnectionContext;
19
use Yiisoft\Db\Profiler\ProfilerAwareInterface;
20
use Yiisoft\Db\Profiler\ProfilerAwareTrait;
21
use Yiisoft\Db\QueryBuilder\QueryBuilderInterface;
22
use Yiisoft\Db\Schema\QuoterInterface;
23
use Yiisoft\Db\Schema\SchemaInterface;
24
use Yiisoft\Db\Transaction\TransactionInterface;
25
26
use function array_keys;
27
use function is_string;
28
29
/**
30
 * Represents a connection to a database using the PDO (PHP Data Objects) extension.
31
 *
32
 * It provides a set of methods for interacting with a database using PDO, such as executing SQL statements, preparing
33
 * and executing statements, and managing transactions.
34
 *
35
 * The ConnectionPDO classes extend from this class, which is a base class for representing a connection to a database.
36
 *
37
 * It implements the ConnectionInterface, which defines the interface for interacting with a database connection.
38
 */
39
abstract class AbstractPdoConnection extends AbstractConnection implements PdoConnectionInterface, LoggerAwareInterface, ProfilerAwareInterface
40
{
41
    use LoggerAwareTrait;
42
    use ProfilerAwareTrait;
43
44
    protected PDO|null $pdo = null;
45
    protected string $serverVersion = '';
46
    protected bool|null $emulatePrepare = null;
47
    protected QueryBuilderInterface|null $queryBuilder = null;
48
    protected QuoterInterface|null $quoter = null;
49
    protected SchemaInterface|null $schema = null;
50
51
    public function __construct(protected PdoDriverInterface $driver, protected SchemaCache $schemaCache)
52
    {
53
    }
54
55
    /**
56
     * Reset the connection after cloning.
57
     */
58
    public function __clone()
59
    {
60
        $this->transaction = null;
61
        $this->pdo = null;
62
    }
63
64
    /**
65
     * Close the connection before serializing.
66
     */
67
    public function __sleep(): array
68
    {
69
        $fields = (array) $this;
70
71
        unset(
72
            $fields["\000*\000" . 'pdo'],
73
            $fields["\000*\000" . 'transaction'],
74
            $fields["\000*\000" . 'schema']
75
        );
76
77
        return array_keys($fields);
78
    }
79
80
    public function beginTransaction(string $isolationLevel = null): TransactionInterface
81
    {
82
        $transaction = parent::beginTransaction($isolationLevel);
83
        if ($this->logger !== null && $transaction instanceof LoggerAwareInterface) {
84
            $transaction->setLogger($this->logger);
85
        }
86
87
        return $transaction;
88
    }
89
90
    public function open(): void
91
    {
92
        if ($this->pdo instanceof PDO) {
93
            return;
94
        }
95
96
        if ($this->driver->getDsn() === '') {
97
            throw new InvalidConfigException('Connection::dsn cannot be empty.');
98
        }
99
100
        $token = 'Opening DB connection: ' . $this->driver->getDsn();
101
        $connectionContext = new ConnectionContext(__METHOD__);
102
103
        try {
104
            $this->logger?->log(LogLevel::INFO, $token);
105
            $this->profiler?->begin($token, $connectionContext);
106
            $this->initConnection();
107
            $this->profiler?->end($token, $connectionContext);
108
        } catch (PDOException $e) {
109
            $this->profiler?->end($token, $connectionContext->setException($e));
110
            $this->logger?->log(LogLevel::ERROR, $token);
111
112
            throw new Exception($e->getMessage(), (array) $e->errorInfo, $e);
113
        }
114
    }
115
116
    public function close(): void
117
    {
118
        if ($this->pdo !== null) {
119
            $this->logger?->log(
120
                LogLevel::DEBUG,
121
                'Closing DB connection: ' . $this->driver->getDsn() . ' ' . __METHOD__,
122
            );
123
124
            $this->pdo = null;
125
            $this->transaction = null;
126
        }
127
    }
128
129
    public function getDriver(): PdoDriverInterface
130
    {
131
        return $this->driver;
132
    }
133
134
    public function getEmulatePrepare(): bool|null
135
    {
136
        return $this->emulatePrepare;
137
    }
138
139
    public function getActivePDO(string|null $sql = '', bool|null $forRead = null): PDO
140
    {
141
        $this->open();
142
        $pdo = $this->getPDO();
143
144
        if ($pdo === null) {
145
            throw new Exception('PDO cannot be initialized.');
146
        }
147
148
        return $pdo;
149
    }
150
151
    public function getPDO(): PDO|null
152
    {
153
        return $this->pdo;
154
    }
155
156
    public function getLastInsertID(string $sequenceName = null): string
157
    {
158
        if ($this->pdo !== null) {
159
            return $this->pdo->lastInsertID($sequenceName ?? null);
160
        }
161
162
        throw new InvalidCallException('DB Connection is not active.');
163
    }
164
165
    public function getDriverName(): string
166
    {
167
        return $this->driver->getDriverName();
168
    }
169
170
    public function getServerVersion(): string
171
    {
172
        if ($this->serverVersion === '') {
173
            /** @psalm-var mixed $version */
174
            $version = $this->getActivePDO()->getAttribute(PDO::ATTR_SERVER_VERSION);
175
            $this->serverVersion = is_string($version) ? $version : 'Version could not be determined.';
176
        }
177
178
        return $this->serverVersion;
179
    }
180
181
    public function isActive(): bool
182
    {
183
        return $this->pdo !== null;
184
    }
185
186
    public function quoteValue(mixed $value): mixed
187
    {
188
        if (is_string($value) === false) {
189
            return $value;
190
        }
191
192
        return $this->getActivePDO()->quote($value);
193
    }
194
195
    public function setEmulatePrepare(bool $value): void
196
    {
197
        $this->emulatePrepare = $value;
198
    }
199
200
    /**
201
     * Initializes the DB connection.
202
     *
203
     * This method is invoked right after the DB connection is established.
204
     *
205
     * The default implementation turns on `PDO::ATTR_EMULATE_PREPARES`, if {@see getEmulatePrepare()} is `true`.
206
     */
207
    protected function initConnection(): void
208
    {
209
        if ($this->getEmulatePrepare() !== null) {
210
            $this->driver->attributes([PDO::ATTR_EMULATE_PREPARES => $this->getEmulatePrepare()]);
211
        }
212
213
        $this->pdo = $this->driver->createConnection();
214
    }
215
216
    /*
217
     * Exceptions thrown from rollback will be caught and just logged with {@see logger->log()}.
218
     */
219
    protected function rollbackTransactionOnLevel(TransactionInterface $transaction, int $level): void
220
    {
221
        if ($transaction->isActive() && $transaction->getLevel() === $level) {
222
            /**
223
             * @link https://github.com/yiisoft/yii2/pull/13347
224
             */
225
            try {
226
                $transaction->rollBack();
227
            } catch (Throwable $e) {
228
                $this->logger?->log(LogLevel::ERROR, (string) $e, [__METHOD__]);
229
                /** hide this exception to be able to continue throwing original exception outside */
230
            }
231
        }
232
    }
233
}
234