Completed
Pull Request — develop (#3154)
by Sergei
63:15
created

testStatementIsReusableAfterClosingCursor()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 23
rs 9.7998
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\Tests\DBAL\Functional;
6
7
use Doctrine\DBAL\DBALException;
8
use Doctrine\DBAL\Driver\DriverException;
9
use Doctrine\DBAL\Driver\PDOConnection;
10
use Doctrine\DBAL\Driver\PDOOracle\Driver as PDOOracleDriver;
11
use Doctrine\DBAL\Driver\Statement;
12
use Doctrine\DBAL\FetchMode;
13
use Doctrine\DBAL\ParameterType;
14
use Doctrine\DBAL\Schema\Table;
15
use Doctrine\DBAL\Types\Type;
16
use Doctrine\Tests\DbalFunctionalTestCase;
17
use function base64_decode;
18
use function sprintf;
19
use function stream_get_contents;
20
21
class StatementTest extends DbalFunctionalTestCase
22
{
23
    protected function setUp() : void
24
    {
25
        parent::setUp();
26
27
        $table = new Table('stmt_test');
28
        $table->addColumn('id', 'integer');
29
        $table->addColumn('name', 'text', ['notnull' => false]);
30
        $this->connection->getSchemaManager()->dropAndCreateTable($table);
31
    }
32
33
    public function testStatementIsReusableAfterClosingCursor()
34
    {
35
        if ($this->connection->getDriver() instanceof PDOOracleDriver) {
36
            $this->markTestIncomplete('See https://bugs.php.net/bug.php?id=77181');
37
        }
38
39
        $this->connection->insert('stmt_test', ['id' => 1]);
40
        $this->connection->insert('stmt_test', ['id' => 2]);
41
42
        $stmt = $this->connection->prepare('SELECT id FROM stmt_test ORDER BY id');
43
44
        $stmt->execute();
45
46
        $id = $stmt->fetchColumn();
47
        self::assertEquals(1, $id);
48
49
        $stmt->closeCursor();
50
51
        $stmt->execute();
52
        $id = $stmt->fetchColumn();
53
        self::assertEquals(1, $id);
54
        $id = $stmt->fetchColumn();
55
        self::assertEquals(2, $id);
56
    }
57
58
    public function testReuseStatementWithLongerResults()
59
    {
60
        if ($this->connection->getDriver() instanceof PDOOracleDriver) {
61
            $this->markTestIncomplete('PDO_OCI doesn\'t support fetching blobs via PDOStatement::fetchAll()');
62
        }
63
64
        $sm    = $this->connection->getSchemaManager();
65
        $table = new Table('stmt_longer_results');
66
        $table->addColumn('param', 'string');
67
        $table->addColumn('val', 'text');
68
        $sm->createTable($table);
69
70
        $row1 = [
71
            'param' => 'param1',
72
            'val' => 'X',
73
        ];
74
        $this->connection->insert('stmt_longer_results', $row1);
75
76
        $stmt = $this->connection->prepare('SELECT param, val FROM stmt_longer_results ORDER BY param');
77
        $stmt->execute();
78
        self::assertEquals([
79
            ['param1', 'X'],
80
        ], $stmt->fetchAll(FetchMode::NUMERIC));
81
82
        $row2 = [
83
            'param' => 'param2',
84
            'val' => 'A bit longer value',
85
        ];
86
        $this->connection->insert('stmt_longer_results', $row2);
87
88
        $stmt->execute();
89
        self::assertEquals([
90
            ['param1', 'X'],
91
            ['param2', 'A bit longer value'],
92
        ], $stmt->fetchAll(FetchMode::NUMERIC));
93
    }
94
95
    public function testFetchLongBlob()
96
    {
97
        if ($this->connection->getDriver() instanceof PDOOracleDriver) {
98
            // inserting BLOBs as streams on Oracle requires Oracle-specific SQL syntax which is currently not supported
99
            // see http://php.net/manual/en/pdo.lobs.php#example-1035
100
            $this->markTestSkipped('DBAL doesn\'t support storing LOBs represented as streams using PDO_OCI');
101
        }
102
103
        // make sure memory limit is large enough to not cause false positives,
104
        // but is still not enough to store a LONGBLOB of the max possible size
105
        $this->iniSet('memory_limit', '4G');
106
107
        $sm    = $this->connection->getSchemaManager();
108
        $table = new Table('stmt_long_blob');
109
        $table->addColumn('contents', 'blob', ['length' => 0xFFFFFFFF]);
110
        $sm->createTable($table);
111
112
        $contents = base64_decode(<<<EOF
113
H4sICJRACVgCA2RvY3RyaW5lLmljbwDtVNtLFHEU/ia1i9fVzVWxvJSrZmoXS6pd0zK7QhdNc03z
114
lrpppq1pWqJCFERZkUFEDybYBQqJhB6iUOqhh+whgl4qkF6MfGh+s87O7GVmO6OlBfUfdIZvznxn
115
fpzznW9gAI4unQ50XwirH2AAkEygEuIwU58ODnPBzXGv14sEq4BrwzKKL4sY++SGTz6PodcutN5x
116
IPvsFCa+K9CXMfS/cOL5OxesN0Wceygho0WAXVLwcUJBdDVDaqOAij4Rrz640XlXQmAxQ16PHU63
117
iqdvXbg4JOHLpILBUSdM7XZEVDDcfuZEbI2ASaYguUGAroSh97GMngcSeFFFerMdI+/dyGy1o+GW
118
Ax5FxfAbFwoviajuc+DCIwn+RTwGRmRIThXxdQJyu+z4/NUDYz2DKCsILuERWsoQfoQhqpLhyhMZ
119
XfcknBmU0NLvQArpTm0SsI5mqKqKuFoGc8cUcjrtqLohom1AgtujQnapmJJU+BbwCLIwhJXyiKlh
120
MB4TkFgvIK3JjrRmAefJm+77Eiqvi+SvCq/qJahQyWuVuEpcIa7QLh7Kbsourb9b66/pZdAd1voz
121
fCNfwsp46OnZQPojSX9UFcNy+mYJNDeJPHtJfqeR/nSaPTzmwlXar5dQ1adpd+B//I9/hi0xuCPQ
122
Nkvb5um37Wtc+auQXZsVxEVYD5hnCilxTaYYjsuxLlsxXUitzd2hs3GWHLM5UOM7Fy8t3xiat4fb
123
sneNxmNb/POO1pRXc7vnF2nc13Rq0cFWiyXkuHmzxuOtzUYfC7fEmK/3mx4QZd5u4E7XJWz6+dey
124
Za4tXHUiPyB8Vm781oaT+3fN6Y/eUFDfPkcNWetNxb+tlxEZsPqPdZMOzS4rxwJ8CDC+ABj1+Tu0
125
d+N0hqezcjblboJ3Bj8ARJilHX4FAAA=
126
EOF
127
        );
128
129
        $this->connection->insert('stmt_long_blob', ['contents' => $contents], [ParameterType::LARGE_OBJECT]);
130
131
        $stmt = $this->connection->prepare('SELECT contents FROM stmt_long_blob');
132
        $stmt->execute();
133
134
        $stream = Type::getType('blob')
135
            ->convertToPHPValue(
136
                $stmt->fetchColumn(),
137
                $this->connection->getDatabasePlatform()
138
            );
139
140
        self::assertSame($contents, stream_get_contents($stream));
0 ignored issues
show
Bug introduced by
It seems like $stream can also be of type false; however, parameter $handle of stream_get_contents() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

140
        self::assertSame($contents, stream_get_contents(/** @scrutinizer ignore-type */ $stream));
Loading history...
141
    }
142
143
    public function testIncompletelyFetchedStatementDoesNotBlockConnection()
144
    {
145
        $this->connection->insert('stmt_test', ['id' => 1]);
146
        $this->connection->insert('stmt_test', ['id' => 2]);
147
148
        $stmt1 = $this->connection->prepare('SELECT id FROM stmt_test');
149
        $stmt1->execute();
150
        $stmt1->fetch();
151
        $stmt1->execute();
152
        // fetching only one record out of two
153
        $stmt1->fetch();
154
155
        $stmt2 = $this->connection->prepare('SELECT id FROM stmt_test WHERE id = ?');
156
        $stmt2->execute([1]);
157
        self::assertEquals(1, $stmt2->fetchColumn());
158
    }
159
160
    public function testReuseStatementAfterClosingCursor()
161
    {
162
        if ($this->connection->getDriver() instanceof PDOOracleDriver) {
163
            $this->markTestIncomplete('See https://bugs.php.net/bug.php?id=77181');
164
        }
165
166
        $this->connection->insert('stmt_test', ['id' => 1]);
167
        $this->connection->insert('stmt_test', ['id' => 2]);
168
169
        $stmt = $this->connection->prepare('SELECT id FROM stmt_test WHERE id = ?');
170
171
        $stmt->execute([1]);
172
        $id = $stmt->fetchColumn();
173
        self::assertEquals(1, $id);
174
175
        $stmt->closeCursor();
176
177
        $stmt->execute([2]);
178
        $id = $stmt->fetchColumn();
179
        self::assertEquals(2, $id);
180
    }
181
182
    public function testReuseStatementWithParameterBoundByReference()
183
    {
184
        $this->connection->insert('stmt_test', ['id' => 1]);
185
        $this->connection->insert('stmt_test', ['id' => 2]);
186
187
        $stmt = $this->connection->prepare('SELECT id FROM stmt_test WHERE id = ?');
188
        $stmt->bindParam(1, $id);
189
190
        $id = 1;
0 ignored issues
show
Unused Code introduced by
The assignment to $id is dead and can be removed.
Loading history...
191
        $stmt->execute();
192
        self::assertEquals(1, $stmt->fetchColumn());
193
194
        $id = 2;
195
        $stmt->execute();
196
        self::assertEquals(2, $stmt->fetchColumn());
197
    }
198
199
    public function testReuseStatementWithReboundValue()
200
    {
201
        $this->connection->insert('stmt_test', ['id' => 1]);
202
        $this->connection->insert('stmt_test', ['id' => 2]);
203
204
        $stmt = $this->connection->prepare('SELECT id FROM stmt_test WHERE id = ?');
205
206
        $stmt->bindValue(1, 1);
207
        $stmt->execute();
208
        self::assertEquals(1, $stmt->fetchColumn());
209
210
        $stmt->bindValue(1, 2);
211
        $stmt->execute();
212
        self::assertEquals(2, $stmt->fetchColumn());
213
    }
214
215
    public function testReuseStatementWithReboundParam()
216
    {
217
        $this->connection->insert('stmt_test', ['id' => 1]);
218
        $this->connection->insert('stmt_test', ['id' => 2]);
219
220
        $stmt = $this->connection->prepare('SELECT id FROM stmt_test WHERE id = ?');
221
222
        $x = 1;
223
        $stmt->bindParam(1, $x);
224
        $stmt->execute();
225
        self::assertEquals(1, $stmt->fetchColumn());
226
227
        $y = 2;
228
        $stmt->bindParam(1, $y);
229
        $stmt->execute();
230
        self::assertEquals(2, $stmt->fetchColumn());
231
    }
232
233
    /**
234
     * @dataProvider fetchProvider
235
     */
236
    public function testFetchFromNonExecutedStatement(callable $fetch)
237
    {
238
        $stmt = $this->connection->prepare('SELECT id FROM stmt_test');
239
240
        self::expectException(DriverException::class);
0 ignored issues
show
Bug Best Practice introduced by
The method PHPUnit\Framework\TestCase::expectException() is not static, but was called statically. ( Ignorable by Annotation )

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

240
        self::/** @scrutinizer ignore-call */ 
241
              expectException(DriverException::class);
Loading history...
241
        $fetch($stmt);
242
    }
243
244
    /**
245
     * @dataProvider fetchProvider
246
     */
247
    public function testCloseCursorOnNonExecutedStatement(callable $fetch)
0 ignored issues
show
Unused Code introduced by
The parameter $fetch is not used and could be removed. ( Ignorable by Annotation )

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

247
    public function testCloseCursorOnNonExecutedStatement(/** @scrutinizer ignore-unused */ callable $fetch)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
248
    {
249
        $this->expectNotToPerformAssertions();
250
251
        $stmt = $this->connection->prepare('SELECT id FROM stmt_test');
252
253
        $stmt->closeCursor();
254
    }
255
256
    /**
257
     * @group DBAL-2637
258
     */
259
    public function testCloseCursorAfterCursorEnd()
260
    {
261
        $this->expectNotToPerformAssertions();
262
263
        $stmt = $this->connection->prepare('SELECT name FROM stmt_test');
264
265
        $stmt->execute();
266
        self::assertFalse($stmt->fetch());
267
268
        $stmt->closeCursor();
269
270
        self::expectException(DriverException::class);
0 ignored issues
show
Bug Best Practice introduced by
The method PHPUnit\Framework\TestCase::expectException() is not static, but was called statically. ( Ignorable by Annotation )

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

270
        self::/** @scrutinizer ignore-call */ 
271
              expectException(DriverException::class);
Loading history...
271
        $stmt->fetch();
272
273
        $stmt->closeCursor();
274
    }
275
276
    public function testCloseCursorAfterClosingCursor()
277
    {
278
        $this->expectNotToPerformAssertions();
279
280
        $stmt = $this->connection->executeQuery('SELECT name FROM stmt_test');
281
        $stmt->closeCursor();
282
        $stmt->closeCursor();
283
    }
284
285
    /**
286
     * @dataProvider fetchProvider
287
     */
288
    public function testFetchFromNonExecutedStatementWithClosedCursor(callable $fetch)
289
    {
290
        $stmt = $this->connection->prepare('SELECT id FROM stmt_test');
291
        $stmt->closeCursor();
292
293
        self::expectException(DriverException::class);
0 ignored issues
show
Bug Best Practice introduced by
The method PHPUnit\Framework\TestCase::expectException() is not static, but was called statically. ( Ignorable by Annotation )

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

293
        self::/** @scrutinizer ignore-call */ 
294
              expectException(DriverException::class);
Loading history...
294
        $fetch($stmt);
295
    }
296
297
    /**
298
     * @dataProvider fetchProvider
299
     */
300
    public function testFetchFromExecutedStatementWithClosedCursor(callable $fetch)
301
    {
302
        $this->connection->insert('stmt_test', ['id' => 1]);
303
304
        $stmt = $this->connection->prepare('SELECT id FROM stmt_test');
305
        $stmt->execute();
306
        $stmt->closeCursor();
307
308
        self::expectException(DriverException::class);
0 ignored issues
show
Bug Best Practice introduced by
The method PHPUnit\Framework\TestCase::expectException() is not static, but was called statically. ( Ignorable by Annotation )

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

308
        self::/** @scrutinizer ignore-call */ 
309
              expectException(DriverException::class);
Loading history...
309
        $fetch($stmt);
310
    }
311
312
    /**
313
     * @dataProvider fetchProvider
314
     */
315
    public function testFetchBeforeExecute(callable $fetch) : void
316
    {
317
        $platform = $this->connection->getDatabasePlatform();
318
        $query    = $platform->getDummySelectSQL();
319
        $stmt     = $this->connection->prepare($query);
320
321
        self::expectException(DriverException::class);
0 ignored issues
show
Bug Best Practice introduced by
The method PHPUnit\Framework\TestCase::expectException() is not static, but was called statically. ( Ignorable by Annotation )

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

321
        self::/** @scrutinizer ignore-call */ 
322
              expectException(DriverException::class);
Loading history...
322
        $fetch($stmt);
323
    }
324
325
    public static function fetchProvider()
326
    {
327
        return [
328
            'fetch' => [
329
                static function (Statement $stmt) {
330
                    return $stmt->fetch();
331
                },
332
            ],
333
            'fetch-column' => [
334
                static function (Statement $stmt) {
335
                    return $stmt->fetchColumn();
336
                },
337
            ],
338
            'fetch-all' => [
339
                static function (Statement $stmt) {
340
                    return $stmt->fetchAll();
341
                },
342
            ],
343
        ];
344
    }
345
346
    public function testFetchInColumnMode() : void
347
    {
348
        $platform = $this->connection->getDatabasePlatform();
349
        $query    = $platform->getDummySelectSQL();
350
        $result   = $this->connection->executeQuery($query)->fetch(FetchMode::COLUMN);
351
352
        self::assertEquals(1, $result);
353
    }
354
355
    public function testExecWithRedundantParameters() : void
356
    {
357
        $driver = $this->connection->getDriver()->getName();
358
359
        switch ($driver) {
360
            case 'pdo_mysql':
361
            case 'pdo_oracle':
362
            case 'pdo_sqlsrv':
363
                self::markTestSkipped(sprintf(
364
                    'PDOStatement::execute() implemented in the "%s" driver does not report redundant parameters',
365
                    $driver
366
                ));
367
368
                return;
369
            case 'ibm_db2':
370
                self::markTestSkipped('db2_execute() does not report redundant parameters');
371
372
                return;
373
            case 'sqlsrv':
374
                self::markTestSkipped('sqlsrv_prepare() does not report redundant parameters');
375
376
                return;
377
        }
378
379
        $platform = $this->connection->getDatabasePlatform();
380
        $query    = $platform->getDummySelectSQL();
381
        $stmt     = $this->connection->prepare($query);
382
383
        // we want to make sure the exception is thrown by the DBAL code, not by PHPUnit due to a PHP-level error,
384
        // but the wrapper connection wraps everything in a DBAL exception
385
        $this->iniSet('error_reporting', '0');
386
387
        self::expectException(DBALException::class);
0 ignored issues
show
Bug Best Practice introduced by
The method PHPUnit\Framework\TestCase::expectException() is not static, but was called statically. ( Ignorable by Annotation )

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

387
        self::/** @scrutinizer ignore-call */ 
388
              expectException(DBALException::class);
Loading history...
388
        $stmt->execute([null]);
389
    }
390
391
    /**
392
     * @throws DBALException
393
     *
394
     * @dataProvider nonExistingIndexProvider
395
     */
396
    public function testFetchColumnNonExistingIndex(int $index) : void
397
    {
398
        if ($this->connection->getWrappedConnection() instanceof PDOConnection) {
399
            $this->markTestSkipped('PDO supports this behavior natively but throws a different exception');
400
        }
401
402
        $platform = $this->connection->getDatabasePlatform();
403
        $query    = $platform->getDummySelectSQL();
404
        $stmt     = $this->connection->query($query);
405
406
        self::expectException(DBALException::class);
0 ignored issues
show
Bug Best Practice introduced by
The method PHPUnit\Framework\TestCase::expectException() is not static, but was called statically. ( Ignorable by Annotation )

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

406
        self::/** @scrutinizer ignore-call */ 
407
              expectException(DBALException::class);
Loading history...
407
        $stmt->fetchColumn($index);
408
    }
409
410
    /**
411
     * @return mixed[][]
412
     */
413
    public static function nonExistingIndexProvider() : iterable
414
    {
415
        return [
416
            [1],
417
            [-1],
418
        ];
419
    }
420
}
421