-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathAbstractPdoConnection.php
242 lines (204 loc) · 7.16 KB
/
AbstractPdoConnection.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
<?php
declare(strict_types=1);
namespace Yiisoft\Db\Driver\Pdo;
use PDO;
use PDOException;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LogLevel;
use Throwable;
use Yiisoft\Db\Cache\SchemaCache;
use Yiisoft\Db\Connection\AbstractConnection;
use Yiisoft\Db\Connection\ServerInfoInterface;
use Yiisoft\Db\Exception\Exception;
use Yiisoft\Db\Exception\InvalidCallException;
use Yiisoft\Db\Exception\InvalidConfigException;
use Yiisoft\Db\Profiler\Context\ConnectionContext;
use Yiisoft\Db\Profiler\ProfilerAwareInterface;
use Yiisoft\Db\Profiler\ProfilerAwareTrait;
use Yiisoft\Db\QueryBuilder\QueryBuilderInterface;
use Yiisoft\Db\Schema\Column\ColumnFactoryInterface;
use Yiisoft\Db\Schema\QuoterInterface;
use Yiisoft\Db\Schema\SchemaInterface;
use Yiisoft\Db\Transaction\TransactionInterface;
use function array_keys;
use function is_string;
use function method_exists;
/**
* 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.
*/
abstract class AbstractPdoConnection extends AbstractConnection implements PdoConnectionInterface, LoggerAwareInterface, ProfilerAwareInterface
{
use LoggerAwareTrait;
use ProfilerAwareTrait;
protected PDO|null $pdo = null;
protected ServerInfoInterface|null $serverInfo = null;
protected bool|null $emulatePrepare = null;
protected QueryBuilderInterface|null $queryBuilder = null;
protected QuoterInterface|null $quoter = null;
protected SchemaInterface|null $schema = null;
public function __construct(
protected PdoDriverInterface $driver,
protected SchemaCache $schemaCache,
protected ColumnFactoryInterface|null $columnFactory = null,
) {
}
/**
* Reset the connection after cloning.
*/
public function __clone()
{
$this->transaction = null;
$this->pdo = null;
}
/**
* Close the connection before serializing.
*/
public function __sleep(): array
{
$fields = (array) $this;
unset(
$fields["\000*\000" . 'pdo'],
$fields["\000*\000" . 'transaction'],
$fields["\000*\000" . 'schema']
);
return array_keys($fields);
}
public function beginTransaction(?string $isolationLevel = null): TransactionInterface
{
$transaction = parent::beginTransaction($isolationLevel);
if ($this->logger !== null && $transaction instanceof LoggerAwareInterface) {
$transaction->setLogger($this->logger);
}
return $transaction;
}
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);
}
}
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;
}
}
public function getDriver(): PdoDriverInterface
{
return $this->driver;
}
public function getEmulatePrepare(): bool|null
{
return $this->emulatePrepare;
}
public function getActivePDO(string|null $sql = '', bool|null $forRead = null): PDO
{
$this->open();
$pdo = $this->getPDO();
if ($pdo === null) {
throw new Exception('PDO cannot be initialized.');
}
return $pdo;
}
public function getPDO(): PDO|null
{
return $this->pdo;
}
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.');
}
public function getDriverName(): string
{
return $this->driver->getDriverName();
}
public function getServerInfo(): ServerInfoInterface
{
return $this->serverInfo ??= new PdoServerInfo($this);
}
public function isActive(): bool
{
return $this->pdo !== null;
}
public function quoteValue(mixed $value): mixed
{
if (is_string($value) === false) {
return $value;
}
return $this->getActivePDO()->quote($value);
}
public function setEmulatePrepare(bool $value): void
{
$this->emulatePrepare = $value;
}
public function setTablePrefix(string $value): void
{
parent::setTablePrefix($value);
if ($this->quoter !== null && method_exists($this->quoter, 'setTablePrefix')) {
$this->quoter->setTablePrefix($value);
}
}
/**
* 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 getEmulatePrepare()} is `true`.
*/
protected function initConnection(): void
{
if ($this->getEmulatePrepare() !== null) {
$this->driver->attributes([PDO::ATTR_EMULATE_PREPARES => $this->getEmulatePrepare()]);
}
$this->pdo = $this->driver->createConnection();
}
/*
* Exceptions thrown from rollback will be caught and just logged with {@see logger->log()}.
*/
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 */
}
}
}
}