Completed
Pull Request — 2.10.x (#3997)
by
unknown
62:08
created

ResultCacheTest::testGetIterator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 1 Features 0
Metric Value
eloc 12
c 5
b 1
f 0
dl 0
loc 20
rs 9.8666
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Doctrine\Tests\DBAL\Functional;
4
5
use ArrayIterator;
6
use Doctrine\Common\Cache\ArrayCache;
7
use Doctrine\DBAL\Cache\QueryCacheProfile;
8
use Doctrine\DBAL\Driver\ResultStatement;
9
use Doctrine\DBAL\FetchMode;
10
use Doctrine\DBAL\Logging\DebugStack;
11
use Doctrine\DBAL\Schema\Table;
12
use Doctrine\Tests\DbalFunctionalTestCase;
13
use function array_change_key_case;
14
use function array_merge;
15
use function array_shift;
16
use function array_values;
17
use function is_array;
18
use const CASE_LOWER;
19
20
/**
21
 * @group DDC-217
22
 */
23
class ResultCacheTest extends DbalFunctionalTestCase
24
{
25
    /** @var array<int, array<int, int|string>> */
26
    private $expectedResult = [['test_int' => 100, 'test_string' => 'foo'], ['test_int' => 200, 'test_string' => 'bar'], ['test_int' => 300, 'test_string' => 'baz']];
27
28
    /** @var DebugStack */
29
    private $sqlLogger;
30
31
    protected function setUp() : void
32
    {
33
        parent::setUp();
34
35
        $table = new Table('caching');
36
        $table->addColumn('test_int', 'integer');
37
        $table->addColumn('test_string', 'string', ['notnull' => false]);
38
        $table->setPrimaryKey(['test_int']);
39
40
        $sm = $this->connection->getSchemaManager();
41
        $sm->createTable($table);
42
43
        foreach ($this->expectedResult as $row) {
44
            $this->connection->insert('caching', $row);
45
        }
46
47
        $config = $this->connection->getConfiguration();
48
        $config->setSQLLogger($this->sqlLogger = new DebugStack());
49
50
        $cache = new ArrayCache();
51
        $config->setResultCacheImpl($cache);
52
    }
53
54
    protected function tearDown() : void
55
    {
56
        $this->connection->getSchemaManager()->dropTable('caching');
57
58
        parent::tearDown();
59
    }
60
61
    public function testCacheFetchAssoc() : void
62
    {
63
        $this->assertCacheNonCacheSelectSameFetchModeAreEqual(
64
            $this->expectedResult,
65
            FetchMode::ASSOCIATIVE
66
        );
67
    }
68
69
    public function testFetchNum() : void
70
    {
71
        $expectedResult = [];
72
        foreach ($this->expectedResult as $v) {
73
            $expectedResult[] = array_values($v);
74
        }
75
76
        $this->assertCacheNonCacheSelectSameFetchModeAreEqual($expectedResult, FetchMode::NUMERIC);
77
    }
78
79
    public function testFetchBoth() : void
80
    {
81
        $expectedResult = [];
82
        foreach ($this->expectedResult as $v) {
83
            $expectedResult[] = array_merge($v, array_values($v));
84
        }
85
86
        $this->assertCacheNonCacheSelectSameFetchModeAreEqual($expectedResult, FetchMode::MIXED);
87
    }
88
89
    public function testFetchColumn() : void
90
    {
91
        $expectedResult = [];
92
        foreach ($this->expectedResult as $v) {
93
            $expectedResult[] = array_shift($v);
94
        }
95
96
        $this->assertCacheNonCacheSelectSameFetchModeAreEqual($expectedResult, FetchMode::COLUMN);
97
    }
98
99
    public function testMixingFetch() : void
100
    {
101
        $numExpectedResult = [];
102
        foreach ($this->expectedResult as $v) {
103
            $numExpectedResult[] = array_values($v);
104
        }
105
106
        $stmt = $this->connection->executeQuery('SELECT * FROM caching ORDER BY test_int ASC', [], [], new QueryCacheProfile(10, 'testcachekey'));
107
108
        $data = $this->hydrateStmt($stmt, FetchMode::ASSOCIATIVE);
109
110
        self::assertEquals($this->expectedResult, $data);
111
112
        $stmt = $this->connection->executeQuery('SELECT * FROM caching ORDER BY test_int ASC', [], [], new QueryCacheProfile(10, 'testcachekey'));
113
114
        $data = $this->hydrateStmt($stmt, FetchMode::NUMERIC);
115
116
        self::assertEquals($numExpectedResult, $data);
117
    }
118
119
    public function testIteratorFetch() : void
120
    {
121
        self::assertStandardAndIteratorFetchAreEqual(FetchMode::MIXED);
0 ignored issues
show
Bug Best Practice introduced by
The method Doctrine\Tests\DBAL\Func...IteratorFetchAreEqual() 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

121
        self::/** @scrutinizer ignore-call */ 
122
              assertStandardAndIteratorFetchAreEqual(FetchMode::MIXED);
Loading history...
122
        self::assertStandardAndIteratorFetchAreEqual(FetchMode::ASSOCIATIVE);
123
        self::assertStandardAndIteratorFetchAreEqual(FetchMode::NUMERIC);
124
    }
125
126
    private function assertStandardAndIteratorFetchAreEqual(int $fetchMode) : void
127
    {
128
        $stmt = $this->connection->executeQuery('SELECT * FROM caching ORDER BY test_int ASC', [], [], new QueryCacheProfile(10, 'testcachekey'));
129
        $data = $this->hydrateStmt($stmt, $fetchMode);
130
131
        $stmt         = $this->connection->executeQuery('SELECT * FROM caching ORDER BY test_int ASC', [], [], new QueryCacheProfile(10, 'testcachekey'));
132
        $dataIterator = $this->hydrateStmtIterator($stmt, $fetchMode);
133
134
        self::assertEquals($data, $dataIterator);
135
    }
136
137
    public function testDontCloseNoCache() : void
138
    {
139
        $stmt = $this->connection->executeQuery('SELECT * FROM caching ORDER BY test_int ASC', [], [], new QueryCacheProfile(10, 'testcachekey'));
140
141
        $data = [];
142
143
        while ($row = $stmt->fetch(FetchMode::ASSOCIATIVE)) {
144
            $data[] = $row;
145
        }
146
147
        $stmt = $this->connection->executeQuery('SELECT * FROM caching ORDER BY test_int ASC', [], [], new QueryCacheProfile(10, 'testcachekey'));
148
149
        $data = [];
150
151
        while ($row = $stmt->fetch(FetchMode::NUMERIC)) {
152
            $data[] = $row;
153
        }
154
155
        self::assertCount(2, $this->sqlLogger->queries);
156
    }
157
158
    public function testDontFinishNoCache() : void
159
    {
160
        $stmt = $this->connection->executeQuery('SELECT * FROM caching ORDER BY test_int ASC', [], [], new QueryCacheProfile(10, 'testcachekey'));
161
162
        $stmt->fetch(FetchMode::ASSOCIATIVE);
163
        $stmt->closeCursor();
164
165
        $stmt = $this->connection->executeQuery('SELECT * FROM caching ORDER BY test_int ASC', [], [], new QueryCacheProfile(10, 'testcachekey'));
166
167
        $this->hydrateStmt($stmt, FetchMode::NUMERIC);
168
169
        self::assertCount(1, $this->sqlLogger->queries);
170
    }
171
172
    public function testFetchAllAndFinishSavesCache() : void
173
    {
174
        $layerCache = new ArrayCache();
175
        $stmt       = $this->connection->executeQuery('SELECT * FROM caching WHERE test_int > 500', [], [], new QueryCacheProfile(10, 'testcachekey', $layerCache));
176
        $stmt->fetchAll();
177
        $stmt->closeCursor();
178
179
        self::assertCount(1, $layerCache->fetch('testcachekey'));
0 ignored issues
show
Bug introduced by
It seems like $layerCache->fetch('testcachekey') can also be of type false; however, parameter $haystack of PHPUnit\Framework\Assert::assertCount() does only seem to accept Countable|iterable, 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

179
        self::assertCount(1, /** @scrutinizer ignore-type */ $layerCache->fetch('testcachekey'));
Loading history...
180
    }
181
182
    public function testFetchAllColumn() : void
183
    {
184
        $query = $this->connection->getDatabasePlatform()
185
            ->getDummySelectSQL('1');
186
187
        $qcp = new QueryCacheProfile(0, 0, new ArrayCache());
188
189
        $stmt = $this->connection->executeCacheQuery($query, [], [], $qcp);
190
        $stmt->fetchAll(FetchMode::COLUMN);
191
        $stmt->closeCursor();
192
193
        $stmt = $this->connection->executeCacheQuery($query, [], [], $qcp);
194
195
        self::assertEquals([1], $stmt->fetchAll(FetchMode::COLUMN));
196
    }
197
198
    public function testGetIterator() : void
199
    {
200
        $query = $this->connection->getDatabasePlatform()
201
            ->getDummySelectSQL('1');
202
203
        $qcp = new QueryCacheProfile(0, 0, new ArrayCache());
204
205
        $stmt = $this->connection->executeCacheQuery($query, [], [], $qcp);
206
        $stmt->/** @scrutinizer ignore-call */
207
                getIterator();
208
        $stmt->closeCursor();
209
210
        $stmt = $this->connection->executeCacheQuery($query, [], [], $qcp);
211
212
        $iterator = $stmt->/** @scrutinizer ignore-call */
213
                            getIterator();
214
215
        self::assertTrue($iterator instanceof ArrayIterator);
216
217
        self::assertEquals(1, $iterator->count());
218
    }
219
220
    /**
221
     * @param array<int, array<int, int|string>> $expectedResult
222
     */
223
    private function assertCacheNonCacheSelectSameFetchModeAreEqual(array $expectedResult, int $fetchMode) : void
224
    {
225
        $stmt = $this->connection->executeQuery('SELECT * FROM caching ORDER BY test_int ASC', [], [], new QueryCacheProfile(10, 'testcachekey'));
226
227
        self::assertEquals(2, $stmt->columnCount());
228
        $data = $this->hydrateStmt($stmt, $fetchMode);
229
        self::assertEquals($expectedResult, $data);
230
231
        $stmt = $this->connection->executeQuery('SELECT * FROM caching ORDER BY test_int ASC', [], [], new QueryCacheProfile(10, 'testcachekey'));
232
233
        self::assertEquals(2, $stmt->columnCount());
234
        $data = $this->hydrateStmt($stmt, $fetchMode);
235
        self::assertEquals($expectedResult, $data);
236
        self::assertCount(1, $this->sqlLogger->queries, 'just one dbal hit');
237
    }
238
239
    public function testEmptyResultCache() : void
240
    {
241
        $stmt = $this->connection->executeQuery('SELECT * FROM caching WHERE test_int > 500', [], [], new QueryCacheProfile(10, 'emptycachekey'));
242
        $data = $this->hydrateStmt($stmt);
0 ignored issues
show
Unused Code introduced by
The assignment to $data is dead and can be removed.
Loading history...
243
244
        $stmt = $this->connection->executeQuery('SELECT * FROM caching WHERE test_int > 500', [], [], new QueryCacheProfile(10, 'emptycachekey'));
245
        $data = $this->hydrateStmt($stmt);
246
247
        self::assertCount(1, $this->sqlLogger->queries, 'just one dbal hit');
248
    }
249
250
    public function testChangeCacheImpl() : void
251
    {
252
        $stmt = $this->connection->executeQuery('SELECT * FROM caching WHERE test_int > 500', [], [], new QueryCacheProfile(10, 'emptycachekey'));
253
        $data = $this->hydrateStmt($stmt);
0 ignored issues
show
Unused Code introduced by
The assignment to $data is dead and can be removed.
Loading history...
254
255
        $secondCache = new ArrayCache();
256
        $stmt        = $this->connection->executeQuery('SELECT * FROM caching WHERE test_int > 500', [], [], new QueryCacheProfile(10, 'emptycachekey', $secondCache));
257
        $data        = $this->hydrateStmt($stmt);
258
259
        self::assertCount(2, $this->sqlLogger->queries, 'two hits');
260
        self::assertCount(1, $secondCache->fetch('emptycachekey'));
0 ignored issues
show
Bug introduced by
It seems like $secondCache->fetch('emptycachekey') can also be of type false; however, parameter $haystack of PHPUnit\Framework\Assert::assertCount() does only seem to accept Countable|iterable, 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

260
        self::assertCount(1, /** @scrutinizer ignore-type */ $secondCache->fetch('emptycachekey'));
Loading history...
261
    }
262
263
    /**
264
     * @return array<int, mixed>
265
     */
266
    private function hydrateStmt(ResultStatement $stmt, int $fetchMode = FetchMode::ASSOCIATIVE) : array
267
    {
268
        $data = [];
269
        while ($row = $stmt->fetch($fetchMode)) {
270
            $data[] = is_array($row) ? array_change_key_case($row, CASE_LOWER) : $row;
271
        }
272
273
        $stmt->closeCursor();
274
275
        return $data;
276
    }
277
278
    /**
279
     * @return array<int, mixed>
280
     */
281
    private function hydrateStmtIterator(ResultStatement $stmt, int $fetchMode = FetchMode::ASSOCIATIVE) : array
282
    {
283
        $data = [];
284
        $stmt->setFetchMode($fetchMode);
285
        foreach ($stmt as $row) {
286
            $data[] = is_array($row) ? array_change_key_case($row, CASE_LOWER) : $row;
287
        }
288
289
        $stmt->closeCursor();
290
291
        return $data;
292
    }
293
}
294