Test Failed
Pull Request — master (#83)
by Wilmer
16:31 queued 13:03
created

ConnectionPDOSqlite::open()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 34
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
dl 0
loc 34
rs 8.9777
c 1
b 0
f 0
cc 6
nc 9
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Sqlite\PDO;
6
7
use PDO;
8
use PDOException;
9
use Psr\Log\LogLevel;
10
use Yiisoft\Db\Cache\QueryCache;
11
use Yiisoft\Db\Cache\SchemaCache;
12
use Yiisoft\Db\Command\CommandInterface;
13
use Yiisoft\Db\Connection\Connection;
14
use Yiisoft\Db\Connection\ConnectionPDOInterface;
15
use Yiisoft\Db\Driver\PDODriver;
16
use Yiisoft\Db\Exception\Exception;
17
use Yiisoft\Db\Exception\InvalidConfigException;
18
use Yiisoft\Db\Query\QueryBuilderInterface;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Query\QueryBuilderInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
19
use Yiisoft\Db\Schema\Quoter;
20
use Yiisoft\Db\Schema\QuoterInterface;
21
use Yiisoft\Db\Schema\SchemaInterface;
22
use Yiisoft\Db\Transaction\TransactionInterface;
23
24
use function constant;
25
use function strncmp;
26
27
/**
28
 * Database connection class prefilled for MYSQL Server.
29
 */
30
final class ConnectionPDOSqlite extends Connection implements ConnectionPDOInterface
31
{
32
    private ?PDO $pdo = null;
33
    private ?QueryBuilderInterface $queryBuilder = null;
34
    private ?QuoterInterface $quoter = null;
35
    private ?SchemaInterface $schema = null;
36
    private string $serverVersion = '';
37
38
    public function __construct(
39
        private PDODriver $driver,
40
        private QueryCache $queryCache,
41
        private SchemaCache $schemaCache
42
    ) {
43
        parent::__construct($queryCache);
44
    }
45
46
    /**
47
     * Reset the connection after cloning.
48
     */
49
    public function __clone()
50
    {
51
        $this->master = null;
52
        $this->slave = null;
53
        $this->transaction = null;
54
55
        if (strncmp($this->driver->getDsn(), 'sqlite::memory:', 15) !== 0) {
56
            /** reset PDO connection, unless its sqlite in-memory, which can only have one connection */
57
            $this->pdo = null;
58
        }
59
    }
60
61
    /**
62
     * Close the connection before serializing.
63
     *
64
     * @return array
65
     */
66
    public function __sleep(): array
67
    {
68
        $fields = (array) $this;
69
70
        unset(
71
            $fields["\000" . __CLASS__ . "\000" . 'pdo'],
72
            $fields["\000" . __CLASS__ . "\000" . 'master'],
73
            $fields["\000" . __CLASS__ . "\000" . 'slave'],
74
            $fields["\000" . __CLASS__ . "\000" . 'transaction'],
75
            $fields["\000" . __CLASS__ . "\000" . 'schema']
76
        );
77
78
        return array_keys($fields);
79
    }
80
81
    public function createCommand(?string $sql = null, array $params = []): CommandInterface
82
    {
83
        $command = new CommandPDOSqlite($this, $this->queryCache);
84
85
        if ($sql !== null) {
86
            $command->setSql($sql);
87
        }
88
89
        if ($this->logger !== null) {
90
            $command->setLogger($this->logger);
91
        }
92
93
        if ($this->profiler !== null) {
94
            $command->setProfiler($this->profiler);
95
        }
96
97
        return $command->bindValues($params);
98
    }
99
100
    public function createTransaction(): TransactionInterface
101
    {
102
        return new TransactionPDOSqlite($this);
103
    }
104
105
    public function close(): void
106
    {
107
        if (!empty($this->master)) {
108
            /** @var ConnectionPDOSqlite */
109
            $db = $this->master;
110
111
            if ($this->pdo === $db->getPDO()) {
0 ignored issues
show
Bug introduced by
The method getPDO() does not exist on Yiisoft\Db\Connection\ConnectionInterface. It seems like you code against a sub-type of said class. However, the method does not exist in Yiisoft\Db\Connection\Connection. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

111
            if ($this->pdo === $db->/** @scrutinizer ignore-call */ getPDO()) {
Loading history...
112
                $this->pdo = null;
113
            }
114
115
            $db->close();
116
            $this->master = null;
117
        }
118
119
        if ($this->pdo !== null) {
120
            $this->logger?->log(
121
                LogLevel::DEBUG,
122
                'Closing DB connection: ' . $this->driver->getDsn() . ' ' . __METHOD__,
123
            );
124
125
            $this->pdo = null;
126
            $this->transaction = null;
127
        }
128
129
        if (!empty($this->slave)) {
130
            $this->slave->close();
131
            $this->slave = null;
132
        }
133
    }
134
135
    public function getDriver(): PDODriver
136
    {
137
        return $this->driver;
138
    }
139
140
    public function getDriverName(): string
141
    {
142
        return 'sqlite';
143
    }
144
145
    public function getMasterPdo(): PDO|null
146
    {
147
        $this->open();
148
        return $this->pdo;
149
    }
150
151
    public function getPDO(): ?PDO
152
    {
153
        return $this->pdo;
154
    }
155
156
    /**
157
     * @throws Exception|InvalidConfigException
158
     */
159
    public function getQueryBuilder(): QueryBuilderInterface
160
    {
161
        if ($this->queryBuilder === null) {
162
            $this->queryBuilder = new QueryBuilderPDOSqlite(
163
                $this->createCommand(),
164
                $this->getQuoter(),
165
                $this->getSchema(),
166
            );
167
        }
168
169
        return $this->queryBuilder;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->queryBuilder could return the type null which is incompatible with the type-hinted return Yiisoft\Db\Query\QueryBuilderInterface. Consider adding an additional type-check to rule them out.
Loading history...
170
    }
171
172
    public function getQuoter(): QuoterInterface
173
    {
174
        if ($this->quoter === null) {
175
            $this->quoter = new Quoter('`', '`', $this->getTablePrefix());
176
        }
177
178
        return $this->quoter;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->quoter could return the type null which is incompatible with the type-hinted return Yiisoft\Db\Schema\QuoterInterface. Consider adding an additional type-check to rule them out.
Loading history...
179
    }
180
181
    /**
182
     * @throws Exception
183
     */
184
    public function getServerVersion(): string
185
    {
186
        if ($this->serverVersion === '') {
187
            /** @var mixed */
188
            $version = $this->getSlavePDO()?->getAttribute(PDO::ATTR_SERVER_VERSION);
189
            $this->serverVersion = is_string($version) ? $version : 'Version could not be determined.';
190
        }
191
192
        return $this->serverVersion;
193
    }
194
195
    public function getSchema(): SchemaInterface
196
    {
197
        if ($this->schema === null) {
198
            $this->schema = new SchemaPDOSqlite($this, $this->schemaCache);
199
        }
200
201
        return $this->schema;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->schema could return the type null which is incompatible with the type-hinted return Yiisoft\Db\Schema\SchemaInterface. Consider adding an additional type-check to rule them out.
Loading history...
202
    }
203
204
    public function getSlavePdo(bool $fallbackToMaster = true): ?PDO
205
    {
206
        /** @var ConnectionPDOSqlite|null $db */
207
        $db = $this->getSlave(false);
208
209
        if ($db === null) {
210
            return $fallbackToMaster ? $this->getMasterPdo() : null;
211
        }
212
213
        return $db->getPDO();
214
    }
215
216
    public function isActive(): bool
217
    {
218
        return $this->pdo !== null;
219
    }
220
221
    public function open(): void
222
    {
223
        if (!empty($this->pdo)) {
224
            return;
225
        }
226
227
        if (!empty($this->masters)) {
228
            /** @var ConnectionPDOSqlite|null */
229
            $db = $this->getMaster();
230
231
            if ($db !== null) {
232
                $this->pdo = $db->getPDO();
233
                return;
234
            }
235
236
            throw new InvalidConfigException('None of the master DB servers is available.');
237
        }
238
239
        if (empty($this->driver->getDsn())) {
240
            throw new InvalidConfigException('Connection::dsn cannot be empty.');
241
        }
242
243
        $token = 'Opening DB connection: ' . $this->driver->getDsn();
244
245
        try {
246
            $this->logger?->log(LogLevel::INFO, $token);
247
            $this->profiler?->begin($token, [__METHOD__]);
248
            $this->initConnection();
249
            $this->profiler?->end($token, [__METHOD__]);
250
        } catch (PDOException $e) {
251
            $this->profiler?->end($token, [__METHOD__]);
252
            $this->logger?->log(LogLevel::ERROR, $token);
253
254
            throw new Exception($e->getMessage(), (array) $e->errorInfo, $e);
255
        }
256
    }
257
258
    /**
259
     * Initializes the DB connection.
260
     *
261
     * This method is invoked right after the DB connection is established.
262
     *
263
     * The default implementation turns on `PDO::ATTR_EMULATE_PREPARES`.
264
     *
265
     * if {@see emulatePrepare} is true, and sets the database {@see charset} if it is not empty.
266
     *
267
     * It then triggers an {@see EVENT_AFTER_OPEN} event.
268
     */
269
    private function initConnection(): void
270
    {
271
        $this->pdo = $this->driver->createConnection();
272
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
273
274
        if ($this->getEmulatePrepare() !== null && constant('PDO::ATTR_EMULATE_PREPARES')) {
275
            $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->getEmulatePrepare());
276
        }
277
    }
278
}
279