Passed
Push — master ( be06f7...c027e3 )
by Wilmer
08:58 queued 06:59
created

TestQueryTrait::countLikeQuery()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 22
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 4
nop 5
dl 0
loc 22
ccs 9
cts 9
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\TestUtility;
6
7
use Yiisoft\Db\Connection\Connection;
8
use Yiisoft\Db\Exception\Exception;
9
use Yiisoft\Db\Exception\InvalidArgumentException;
10
use Yiisoft\Db\Exception\InvalidConfigException;
11
use Yiisoft\Db\Exception\NotSupportedException;
12
use Yiisoft\Db\Expression\Expression;
13
use Yiisoft\Db\Query\Query;
14
use Yiisoft\Db\Schema\Schema;
15
16
trait TestQueryTrait
17
{
18
    use GetTablesAliasTestTrait;
19
20 4
    public function testSelect(): void
21
    {
22 4
        $db = $this->getConnection();
0 ignored issues
show
Bug introduced by
It seems like getConnection() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

22
        /** @scrutinizer ignore-call */ 
23
        $db = $this->getConnection();
Loading history...
23
24
        /* default */
25 4
        $query = new Query($db);
26
27 4
        $query->select('*');
28
29 4
        $this->assertEquals(['*' => '*'], $query->getSelect());
0 ignored issues
show
Bug introduced by
It seems like assertEquals() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

29
        $this->/** @scrutinizer ignore-call */ 
30
               assertEquals(['*' => '*'], $query->getSelect());
Loading history...
30 4
        $this->assertNull($query->getDistinct());
0 ignored issues
show
Bug introduced by
It seems like assertNull() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

30
        $this->/** @scrutinizer ignore-call */ 
31
               assertNull($query->getDistinct());
Loading history...
31 4
        $this->assertNull($query->getSelectOption());
0 ignored issues
show
Bug introduced by
Are you sure the usage of $query->getSelectOption() targeting Yiisoft\Db\Query\Query::getSelectOption() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
32
33 4
        $query = new Query($db);
34
35 4
        $query->select('id, name', 'something')->distinct(true);
36
37 4
        $this->assertEquals(['id' => 'id', 'name' => 'name'], $query->getSelect());
38 4
        $this->assertTrue($query->getDistinct());
0 ignored issues
show
Bug introduced by
It seems like assertTrue() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

38
        $this->/** @scrutinizer ignore-call */ 
39
               assertTrue($query->getDistinct());
Loading history...
39 4
        $this->assertEquals('something', $query->getSelectOption());
40
41 4
        $query = new Query($db);
42
43 4
        $query->addSelect('email');
44
45 4
        $this->assertEquals(['email' => 'email'], $query->getSelect());
46
47 4
        $query = new Query($db);
48
49 4
        $query->select('id, name');
50 4
        $query->addSelect('email');
51
52 4
        $this->assertEquals(['id' => 'id', 'name' => 'name', 'email' => 'email'], $query->getSelect());
53
54 4
        $query = new Query($db);
55
56 4
        $query->select('name, lastname');
57 4
        $query->addSelect('name');
58
59 4
        $this->assertEquals(['name' => 'name', 'lastname' => 'lastname'], $query->getSelect());
60
61 4
        $query = new Query($db);
62
63 4
        $query->addSelect(['*', 'abc']);
64 4
        $query->addSelect(['*', 'bca']);
65
66 4
        $this->assertEquals(['*' => '*', 'abc' => 'abc', 'bca' => 'bca'], $query->getSelect());
67
68 4
        $query = new Query($db);
69
70 4
        $query->addSelect(['field1 as a', 'field 1 as b']);
71
72 4
        $this->assertEquals(['a' => 'field1', 'b' => 'field 1'], $query->getSelect());
73
74 4
        $query = new Query($db);
75
76 4
        $query->addSelect(['field1 a', 'field 1 b']);
77
78 4
        $this->assertEquals(['a' => 'field1', 'b' => 'field 1'], $query->getSelect());
79
80 4
        $query = new Query($db);
81
82 4
        $query->select(['name' => 'firstname', 'lastname']);
83 4
        $query->addSelect(['firstname', 'surname' => 'lastname']);
84 4
        $query->addSelect(['firstname', 'lastname']);
85
86 4
        $this->assertEquals(
87 4
            ['name' => 'firstname', 'lastname' => 'lastname', 'firstname' => 'firstname', 'surname' => 'lastname'],
88 4
            $query->getSelect()
89
        );
90
91 4
        $query = new Query($db);
92
93 4
        $query->select('name, name, name as X, name as X');
94
95 4
        $this->assertEquals(['name' => 'name', 'X' => 'name'], $query->getSelect());
96
97
        /**
98
         * {@see https://github.com/yiisoft/yii2/issues/15676}
99
         */
100 4
        $query = (new Query($db))->select('id');
101
102 4
        $this->assertSame(['id' => 'id'], $query->getSelect());
0 ignored issues
show
Bug introduced by
It seems like assertSame() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

102
        $this->/** @scrutinizer ignore-call */ 
103
               assertSame(['id' => 'id'], $query->getSelect());
Loading history...
103
104 4
        $query->select(['id', 'brand_id']);
105
106 4
        $this->assertSame(['id' => 'id', 'brand_id' => 'brand_id'], $query->getSelect());
107
108
        /**
109
         * {@see https://github.com/yiisoft/yii2/issues/15676}
110
         */
111 4
        $query = (new Query($db))
112 4
            ->select(['prefix' => 'LEFT(name, 7)', 'prefix_key' => 'LEFT(name, 7)']);
113
114 4
        $this->assertSame(['prefix' => 'LEFT(name, 7)', 'prefix_key' => 'LEFT(name, 7)'], $query->getSelect());
115
116 4
        $query->addSelect(['LEFT(name,7) as test']);
117
118 4
        $this->assertSame(
119 4
            ['prefix' => 'LEFT(name, 7)', 'prefix_key' => 'LEFT(name, 7)', 'test' => 'LEFT(name,7)'],
120 4
            $query->getSelect()
121
        );
122
123 4
        $query->addSelect(['LEFT(name,7) as test']);
124
125 4
        $this->assertSame(
126 4
            ['prefix' => 'LEFT(name, 7)', 'prefix_key' => 'LEFT(name, 7)', 'test' => 'LEFT(name,7)'],
127 4
            $query->getSelect()
128
        );
129
130 4
        $query->addSelect(['test' => 'LEFT(name,7)']);
131
132 4
        $this->assertSame(
133 4
            ['prefix' => 'LEFT(name, 7)', 'prefix_key' => 'LEFT(name, 7)', 'test' => 'LEFT(name,7)'],
134 4
            $query->getSelect()
135
        );
136
137
        /**
138
         * {@see https://github.com/yiisoft/yii2/issues/15731}
139
         */
140
        $selectedCols = [
141 4
            'total_sum' => 'SUM(f.amount)',
142
            'in_sum'    => 'SUM(IF(f.type = :type_in, f.amount, 0))',
143
            'out_sum'   => 'SUM(IF(f.type = :type_out, f.amount, 0))',
144
        ];
145
146 4
        $query = (new Query($db))->select($selectedCols)->addParams([
147 4
            ':type_in'      => 'in',
148
            ':type_out'     => 'out',
149
            ':type_partner' => 'partner',
150
        ]);
151
152 4
        $this->assertSame($selectedCols, $query->getSelect());
153
154 4
        $query->select($selectedCols);
155
156 4
        $this->assertSame($selectedCols, $query->getSelect());
157
158
        /**
159
         * {@see https://github.com/yiisoft/yii2/issues/17384}
160
         */
161 4
        $query = new Query($db);
162
163 4
        $query->select('DISTINCT ON(tour_dates.date_from) tour_dates.date_from, tour_dates.id');
164
165 4
        $this->assertEquals(
166 4
            ['DISTINCT ON(tour_dates.date_from) tour_dates.date_from', 'tour_dates.id' => 'tour_dates.id'],
167 4
            $query->getSelect()
168
        );
169 4
    }
170
171 4
    public function testFrom(): void
172
    {
173 4
        $db = $this->getConnection();
174
175 4
        $query = new Query($db);
176
177 4
        $query->from('user');
178
179 4
        $this->assertEquals(['user'], $query->getFrom());
180 4
    }
181
182 4
    public function testFromTableIsArrayWithExpression(): void
183
    {
184 4
        $db = $this->getConnection();
185
186 4
        $query = new Query($db);
187
188 4
        $tables = new Expression('(SELECT id,name FROM user) u');
189
190 4
        $query->from($tables);
191
192 4
        $this->assertInstanceOf(Expression::class, $query->getFrom()[0]);
0 ignored issues
show
Bug introduced by
It seems like assertInstanceOf() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

192
        $this->/** @scrutinizer ignore-call */ 
193
               assertInstanceOf(Expression::class, $query->getFrom()[0]);
Loading history...
193 4
    }
194
195 40
    protected function createQuery(): Query
196
    {
197 40
        return new Query($this->getConnection());
198
    }
199
200 4
    public function testWhere(): void
201
    {
202 4
        $db = $this->getConnection();
203
204 4
        $query = new Query($db);
205
206 4
        $query->where('id = :id', [':id' => 1]);
207
208 4
        $this->assertEquals('id = :id', $query->getWhere());
209 4
        $this->assertEquals([':id' => 1], $query->getParams());
210
211 4
        $query->andWhere('name = :name', [':name' => 'something']);
212
213 4
        $this->assertEquals(['and', 'id = :id', 'name = :name'], $query->getWhere());
214 4
        $this->assertEquals([':id' => 1, ':name' => 'something'], $query->getParams());
215
216 4
        $query->orWhere('age = :age', [':age' => '30']);
217
218 4
        $this->assertEquals(['or', ['and', 'id = :id', 'name = :name'], 'age = :age'], $query->getWhere());
219 4
        $this->assertEquals([':id' => 1, ':name' => 'something', ':age' => '30'], $query->getParams());
220 4
    }
221
222 4
    public function testFilterWhereWithHashFormat(): void
223
    {
224 4
        $db = $this->getConnection();
225
226 4
        $query = new Query($db);
227
228 4
        $query->filterWhere([
229 4
            'id'         => 0,
230
            'title'      => '   ',
231
            'author_ids' => [],
232
        ]);
233
234 4
        $this->assertEquals(['id' => 0], $query->getWhere());
235
236 4
        $query->andFilterWhere(['status' => null]);
237
238 4
        $this->assertEquals(['id' => 0], $query->getWhere());
239
240 4
        $query->orFilterWhere(['name' => '']);
241
242 4
        $this->assertEquals(['id' => 0], $query->getWhere());
243 4
    }
244
245 4
    public function testFilterWhereWithOperatorFormat(): void
246
    {
247 4
        $db = $this->getConnection();
248
249 4
        $query = new Query($db);
250
251 4
        $condition = ['like', 'name', 'Alex'];
252
253 4
        $query->filterWhere($condition);
254
255 4
        $this->assertEquals($condition, $query->getWhere());
256
257 4
        $query->andFilterWhere(['between', 'id', null, null]);
258
259 4
        $this->assertEquals($condition, $query->getWhere());
260
261 4
        $query->orFilterWhere(['not between', 'id', null, null]);
262
263 4
        $this->assertEquals($condition, $query->getWhere());
264
265 4
        $query->andFilterWhere(['in', 'id', []]);
266
267 4
        $this->assertEquals($condition, $query->getWhere());
268
269 4
        $query->andFilterWhere(['not in', 'id', []]);
270
271 4
        $this->assertEquals($condition, $query->getWhere());
272
273 4
        $query->andFilterWhere(['like', 'id', '']);
274
275 4
        $this->assertEquals($condition, $query->getWhere());
276
277 4
        $query->andFilterWhere(['or like', 'id', '']);
278
279 4
        $this->assertEquals($condition, $query->getWhere());
280
281 4
        $query->andFilterWhere(['not like', 'id', '   ']);
282
283 4
        $this->assertEquals($condition, $query->getWhere());
284
285 4
        $query->andFilterWhere(['or not like', 'id', null]);
286
287 4
        $this->assertEquals($condition, $query->getWhere());
288
289 4
        $query->andFilterWhere(['or', ['eq', 'id', null], ['eq', 'id', []]]);
290
291 4
        $this->assertEquals($condition, $query->getWhere());
292 4
    }
293
294 4
    public function testFilterHavingWithHashFormat(): void
295
    {
296 4
        $db = $this->getConnection();
297
298 4
        $query = new Query($db);
299
300 4
        $query->filterHaving([
301 4
            'id'         => 0,
302
            'title'      => '   ',
303
            'author_ids' => [],
304
        ]);
305
306 4
        $this->assertEquals(['id' => 0], $query->getHaving());
307
308 4
        $query->andFilterHaving(['status' => null]);
309
310 4
        $this->assertEquals(['id' => 0], $query->getHaving());
311
312 4
        $query->orFilterHaving(['name' => '']);
313
314 4
        $this->assertEquals(['id' => 0], $query->getHaving());
315 4
    }
316
317 4
    public function testFilterHavingWithOperatorFormat(): void
318
    {
319 4
        $db = $this->getConnection();
320
321 4
        $query = new Query($db);
322
323 4
        $condition = ['like', 'name', 'Alex'];
324
325 4
        $query->filterHaving($condition);
326
327 4
        $this->assertEquals($condition, $query->getHaving());
328
329 4
        $query->andFilterHaving(['between', 'id', null, null]);
330
331 4
        $this->assertEquals($condition, $query->getHaving());
332
333 4
        $query->orFilterHaving(['not between', 'id', null, null]);
334
335 4
        $this->assertEquals($condition, $query->getHaving());
336
337 4
        $query->andFilterHaving(['in', 'id', []]);
338
339 4
        $this->assertEquals($condition, $query->getHaving());
340
341 4
        $query->andFilterHaving(['not in', 'id', []]);
342
343 4
        $this->assertEquals($condition, $query->getHaving());
344
345 4
        $query->andFilterHaving(['like', 'id', '']);
346
347 4
        $this->assertEquals($condition, $query->getHaving());
348
349 4
        $query->andFilterHaving(['or like', 'id', '']);
350
351 4
        $this->assertEquals($condition, $query->getHaving());
352
353 4
        $query->andFilterHaving(['not like', 'id', '   ']);
354
355 4
        $this->assertEquals($condition, $query->getHaving());
356
357 4
        $query->andFilterHaving(['or not like', 'id', null]);
358
359 4
        $this->assertEquals($condition, $query->getHaving());
360
361 4
        $query->andFilterHaving(['or', ['eq', 'id', null], ['eq', 'id', []]]);
362
363 4
        $this->assertEquals($condition, $query->getHaving());
364 4
    }
365
366 4
    public function testFilterRecursively(): void
367
    {
368 4
        $db = $this->getConnection();
369
370 4
        $query = new Query($db);
371
372 4
        $query->filterWhere(
373 4
            ['and', ['like', 'name', ''],
374
            ['like', 'title', ''],
375
            ['id' => 1],
376
            ['not',
377
            ['like', 'name', '']]]
378
        );
379
380 4
        $this->assertEquals(['and', ['id' => 1]], $query->getWhere());
381 4
    }
382
383 4
    public function testGroup(): void
384
    {
385 4
        $db = $this->getConnection();
386
387 4
        $query = new Query($db);
388
389 4
        $query->groupBy('team');
390
391 4
        $this->assertEquals(['team'], $query->getGroupBy());
392
393 4
        $query->addGroupBy('company');
394
395 4
        $this->assertEquals(['team', 'company'], $query->getGroupBy());
396
397 4
        $query->addGroupBy('age');
398
399 4
        $this->assertEquals(['team', 'company', 'age'], $query->getGroupBy());
400 4
    }
401
402 4
    public function testHaving(): void
403
    {
404 4
        $db = $this->getConnection();
405
406 4
        $query = new Query($db);
407
408 4
        $query->having('id = :id', [':id' => 1]);
409
410 4
        $this->assertEquals('id = :id', $query->getHaving());
411 4
        $this->assertEquals([':id' => 1], $query->getParams());
412
413 4
        $query->andHaving('name = :name', [':name' => 'something']);
414 4
        $this->assertEquals(['and', 'id = :id', 'name = :name'], $query->getHaving());
415 4
        $this->assertEquals([':id' => 1, ':name' => 'something'], $query->getParams());
416
417 4
        $query->orHaving('age = :age', [':age' => '30']);
418 4
        $this->assertEquals(['or', ['and', 'id = :id', 'name = :name'], 'age = :age'], $query->getHaving());
419 4
        $this->assertEquals([':id' => 1, ':name' => 'something', ':age' => '30'], $query->getParams());
420 4
    }
421
422 4
    public function testOrder(): void
423
    {
424 4
        $db = $this->getConnection();
425
426 4
        $query = new Query($db);
427
428 4
        $query->orderBy('team');
429
430 4
        $this->assertEquals(['team' => SORT_ASC], $query->getOrderBy());
431
432 4
        $query->addOrderBy('company');
433
434 4
        $this->assertEquals(['team' => SORT_ASC, 'company' => SORT_ASC], $query->getOrderBy());
435
436 4
        $query->addOrderBy('age');
437
438 4
        $this->assertEquals(['team' => SORT_ASC, 'company' => SORT_ASC, 'age' => SORT_ASC], $query->getOrderBy());
439
440 4
        $query->addOrderBy(['age' => SORT_DESC]);
441
442 4
        $this->assertEquals(['team' => SORT_ASC, 'company' => SORT_ASC, 'age' => SORT_DESC], $query->getOrderBy());
443
444 4
        $query->addOrderBy('age ASC, company DESC');
445
446 4
        $this->assertEquals(['team' => SORT_ASC, 'company' => SORT_DESC, 'age' => SORT_ASC], $query->getOrderBy());
447
448 4
        $expression = new Expression('SUBSTR(name, 3, 4) DESC, x ASC');
449
450 4
        $query->orderBy($expression);
451
452 4
        $this->assertEquals([$expression], $query->getOrderBy());
453
454 4
        $expression = new Expression('SUBSTR(name, 3, 4) DESC, x ASC');
455
456 4
        $query->addOrderBy($expression);
457
458 4
        $this->assertEquals([$expression, $expression], $query->getOrderBy());
459 4
    }
460
461 4
    public function testLimitOffset(): void
462
    {
463 4
        $db = $this->getConnection();
464
465 4
        $query = new Query($db);
466
467 4
        $query->limit(10)->offset(5);
468
469 4
        $this->assertEquals(10, $query->getLimit());
470 4
        $this->assertEquals(5, $query->getOffset());
471 4
    }
472
473 2
    public function testLimitOffsetWithExpression(): void
474
    {
475 2
        $db = $this->getConnection();
476
477 2
        $query = (new Query($db))->from('customer')->select('id')->orderBy('id');
478
479
        $query
480 2
            ->limit(new Expression('1 + 1'))
481 2
            ->offset(new Expression('1 + 0'));
482
483 2
        $result = $query->column();
484
485 2
        $this->assertCount(2, $result);
0 ignored issues
show
Bug introduced by
It seems like assertCount() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

485
        $this->/** @scrutinizer ignore-call */ 
486
               assertCount(2, $result);
Loading history...
486 2
        if ($db->getDriverName() !== 'sqlsrv') {
487 1
            $this->assertContains(2, $result);
0 ignored issues
show
Bug introduced by
It seems like assertContains() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

487
            $this->/** @scrutinizer ignore-call */ 
488
                   assertContains(2, $result);
Loading history...
488 1
            $this->assertContains(3, $result);
489
        } else {
490 1
            $this->assertContains("2", $result);
491 1
            $this->assertContains("3", $result);
492
        }
493 2
        $this->assertNotContains(1, $result);
0 ignored issues
show
Bug introduced by
It seems like assertNotContains() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

493
        $this->/** @scrutinizer ignore-call */ 
494
               assertNotContains(1, $result);
Loading history...
494 2
    }
495
496 4
    public function testOne(): void
497
    {
498 4
        $db = $this->getConnection();
499
500 4
        $result = (new Query($db))->from('customer')->where(['status' => 2])->one();
501
502 4
        $this->assertEquals('user3', $result['name']);
503
504 4
        $result = (new Query($db))->from('customer')->where(['status' => 3])->one();
505
506 4
        $this->assertFalse($result);
0 ignored issues
show
Bug introduced by
It seems like assertFalse() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

506
        $this->/** @scrutinizer ignore-call */ 
507
               assertFalse($result);
Loading history...
507 4
    }
508
509 4
    public function testExists(): void
510
    {
511 4
        $db = $this->getConnection();
512
513 4
        $result = (new Query($db))->from('customer')->where(['status' => 2])->exists();
514
515 4
        $this->assertTrue($result);
516
517 4
        $result = (new Query($db))->from('customer')->where(['status' => 3])->exists();
518
519 4
        $this->assertFalse($result);
520 4
    }
521
522 4
    public function testColumn(): void
523
    {
524 4
        $db = $this->getConnection();
525
526 4
        $result = (new Query($db))
527 4
            ->select('name')
528 4
            ->from('customer')
529 4
            ->orderBy(['id' => SORT_DESC])
530 4
            ->column();
531
532 4
        $this->assertEquals(['user3', 'user2', 'user1'], $result);
533
534
        /**
535
         * {@see https://github.com/yiisoft/yii2/issues/7515}
536
         */
537 4
        $result = (new Query($db))->from('customer')
538 4
            ->select('name')
539 4
            ->orderBy(['id' => SORT_DESC])
540 4
            ->indexBy('id')
541 4
            ->column();
542
543 4
        $this->assertEquals([3 => 'user3', 2 => 'user2', 1 => 'user1'], $result);
544
545
        /**
546
         * {@see https://github.com/yiisoft/yii2/issues/12649}
547
         */
548 4
        $result = (new Query($db))->from('customer')
549 4
            ->select(['name', 'id'])
550 4
            ->orderBy(['id' => SORT_DESC])
551 4
            ->indexBy(function ($row) {
552 4
                return $row['id'] * 2;
553 4
            })
554 4
            ->column();
555
556 4
        $this->assertEquals([6 => 'user3', 4 => 'user2', 2 => 'user1'], $result);
557
558 4
        $result = (new Query($db))->from('customer')
559 4
            ->select(['name'])
560 4
            ->indexBy('name')
561 4
            ->orderBy(['id' => SORT_DESC])
562 4
            ->column($db);
0 ignored issues
show
Unused Code introduced by
The call to Yiisoft\Db\Query\Query::column() has too many arguments starting with $db. ( Ignorable by Annotation )

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

562
            ->/** @scrutinizer ignore-call */ column($db);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
563
564 4
        $this->assertEquals(['user3' => 'user3', 'user2' => 'user2', 'user1' => 'user1'], $result);
565 4
    }
566
567 4
    public function testCount(): void
568
    {
569 4
        $db = $this->getConnection();
570
571 4
        $count = (new Query($db))->from('customer')->count('*');
572
573 4
        $this->assertEquals(3, $count);
574
575 4
        $count = (new Query($db))->from('customer')->where(['status' => 2])->count('*');
576
577 4
        $this->assertEquals(1, $count);
578
579 4
        $count = (new Query($db))
580 4
            ->select('[[status]], COUNT([[id]]) cnt')
581 4
            ->from('customer')
582 4
            ->groupBy('status')
583 4
            ->count('*');
584
585 4
        $this->assertEquals(2, $count);
586
587
        /* testing that orderBy() should be ignored here as it does not affect the count anyway. */
588 4
        $count = (new Query($db))->from('customer')->orderBy('status')->count('*');
589
590 4
        $this->assertEquals(3, $count);
591
592 4
        $count = (new Query($db))->from('customer')->orderBy('id')->limit(1)->count('*');
593
594 4
        $this->assertEquals(3, $count);
595 4
    }
596
597
    /**
598
     * @depends testFilterWhereWithHashFormat
599
     * @depends testFilterWhereWithOperatorFormat
600
     */
601 4
    public function testAndFilterCompare(): void
602
    {
603 4
        $db = $this->getConnection();
604
605 4
        $query = new Query($db);
606
607 4
        $result = $query->andFilterCompare('name', null);
608
609 4
        $this->assertInstanceOf(Query::class, $result);
610 4
        $this->assertNull($query->getWhere());
611
612 4
        $query->andFilterCompare('name', '');
613
614 4
        $this->assertNull($query->getWhere());
615
616 4
        $query->andFilterCompare('name', 'John Doe');
617 4
        $condition = ['=', 'name', 'John Doe'];
618
619 4
        $this->assertEquals($condition, $query->getWhere());
620
621 4
        $condition = ['and', $condition, ['like', 'name', 'Doe']];
622 4
        $query->andFilterCompare('name', 'Doe', 'like');
623
624 4
        $this->assertEquals($condition, $query->getWhere());
625
626 4
        $condition[] = ['>', 'rating', '9'];
627 4
        $query->andFilterCompare('rating', '>9');
628
629 4
        $this->assertEquals($condition, $query->getWhere());
630
631 4
        $condition[] = ['<=', 'value', '100'];
632 4
        $query->andFilterCompare('value', '<=100');
633
634 4
        $this->assertEquals($condition, $query->getWhere());
635 4
    }
636
637 4
    public function testEmulateExecution(): void
638
    {
639 4
        $db = $this->getConnection();
640
641 4
        $this->assertGreaterThan(0, (new Query($db))->from('customer')->count('*'));
0 ignored issues
show
Bug introduced by
It seems like assertGreaterThan() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

641
        $this->/** @scrutinizer ignore-call */ 
642
               assertGreaterThan(0, (new Query($db))->from('customer')->count('*'));
Loading history...
642
643 4
        $rows = (new Query($db))->from('customer')->emulateExecution()->all();
644
645 4
        $this->assertSame([], $rows);
646
647 4
        $row = (new Query($db))->from('customer')->emulateExecution()->one();
648
649 4
        $this->assertFalse($row);
650
651 4
        $exists = (new Query($db))->from('customer')->emulateExecution()->exists($db);
0 ignored issues
show
Unused Code introduced by
The call to Yiisoft\Db\Query\Query::exists() has too many arguments starting with $db. ( Ignorable by Annotation )

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

651
        $exists = (new Query($db))->from('customer')->emulateExecution()->/** @scrutinizer ignore-call */ exists($db);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
652
653 4
        $this->assertFalse($exists);
654
655 4
        $count = (new Query($db))->from('customer')->emulateExecution()->count('*');
656
657 4
        $this->assertSame(0, $count);
658
659 4
        $sum = (new Query($db))->from('customer')->emulateExecution()->sum('id');
660
661 4
        $this->assertSame(0, $sum);
662
663 4
        $sum = (new Query($db))->from('customer')->emulateExecution()->average('id');
664
665 4
        $this->assertSame(0, $sum);
666
667 4
        $max = (new Query($db))->from('customer')->emulateExecution()->max('id');
668
669 4
        $this->assertNull($max);
670
671 4
        $min = (new Query($db))->from('customer')->emulateExecution()->min('id');
672
673 4
        $this->assertNull($min);
674
675 4
        $scalar = (new Query($db))->select(['id'])->from('customer')->emulateExecution()->scalar();
676
677 4
        $this->assertNull($scalar);
678
679 4
        $column = (new Query($db))->select(['id'])->from('customer')->emulateExecution()->column();
680
681 4
        $this->assertSame([], $column);
682 4
    }
683
684
    /**
685
     * @param Connection $db
686
     * @param string $tableName
687
     * @param string $columnName
688
     * @param array $condition
689
     * @param string $operator
690
     *
691
     * @throws Exception
692
     * @throws InvalidArgumentException
693
     * @throws InvalidConfigException
694
     * @throws NotSupportedException
695
     *
696
     * @return int
697
     */
698 4
    protected function countLikeQuery(
699
        Connection $db,
0 ignored issues
show
Unused Code introduced by
The parameter $db 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

699
        /** @scrutinizer ignore-unused */ Connection $db,

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...
700
        string $tableName,
701
        string $columnName,
702
        array $condition,
703
        string $operator = 'or'
704
    ): int {
705 4
        $db = $this->getConnection();
706
707 4
        $whereCondition = [$operator];
708
709 4
        foreach ($condition as $value) {
710 4
            $whereCondition[] = ['like', $columnName, $value];
711
        }
712
713 4
        $result = (new Query($db))->from($tableName)->where($whereCondition)->count('*');
714
715 4
        if (is_numeric($result)) {
716 4
            $result = (int) $result;
717
        }
718
719 4
        return $result;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $result could return the type string which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
720
    }
721
722
    /**
723
     * {@see https://github.com/yiisoft/yii2/issues/13745}
724
     */
725 4
    public function testMultipleLikeConditions(): void
726
    {
727 4
        $db = $this->getConnection();
728
729 4
        $tableName = 'like_test';
730 4
        $columnName = 'col';
731
732 4
        if ($db->getSchema()->getTableSchema($tableName) !== null) {
733
            $db->createCommand()->dropTable($tableName)->execute();
734
        }
735
736 4
        $db->createCommand()->createTable($tableName, [
737 4
            $columnName => $db->getSchema()->createColumnSchemaBuilder(Schema::TYPE_STRING, 64),
738 4
        ])->execute();
739
740 4
        $db->createCommand()->batchInsert($tableName, ['col'], [
741 4
            ['test0'],
742
            ['test\1'],
743
            ['test\2'],
744
            ['foo%'],
745
            ['%bar'],
746
            ['%baz%'],
747 4
        ])->execute();
748
749
        /* Basic tests */
750 4
        $this->assertSame(1, $this->countLikeQuery($db, $tableName, $columnName, ['test0']));
751 4
        $this->assertSame(2, $this->countLikeQuery($db, $tableName, $columnName, ['test\\']));
752 4
        $this->assertSame(0, $this->countLikeQuery($db, $tableName, $columnName, ['test%']));
753 4
        $this->assertSame(3, $this->countLikeQuery($db, $tableName, $columnName, ['%']));
754
755
        /* Multiple condition tests */
756 4
        $this->assertSame(2, $this->countLikeQuery($db, $tableName, $columnName, [
757 4
            'test0',
758
            'test\1',
759
        ]));
760 4
        $this->assertSame(3, $this->countLikeQuery($db, $tableName, $columnName, [
761 4
            'test0',
762
            'test\1',
763
            'test\2',
764
        ]));
765 4
        $this->assertSame(3, $this->countLikeQuery($db, $tableName, $columnName, [
766 4
            'foo',
767
            '%ba',
768
        ]));
769 4
    }
770
771
    /**
772
     * {@see https://github.com/yiisoft/yii2/issues/15355}
773
     */
774 4
    public function testExpressionInFrom(): void
775
    {
776 4
        $db = $this->getConnection();
777
778 4
        $query = (new Query($db))
779 4
            ->from(new Expression('(SELECT id, name, email, address, status FROM customer) c'))
780 4
            ->where(['status' => 2]);
781
782 4
        $result = $query->one();
783
784 4
        $this->assertEquals('user3', $result['name']);
785 4
    }
786
787 4
    public function testQueryCache()
788
    {
789 4
        $db = $this->getConnection();
790
791 4
        $db->setEnableQueryCache(true);
792 4
        $db->setQueryCache($this->cache);
793
794 4
        $query = (new Query($db))
795 4
            ->select(['name'])
796 4
            ->from('customer');
797
798 4
        $update = $db->createCommand('UPDATE {{customer}} SET [[name]] = :name WHERE [[id]] = :id');
799
800 4
        $this->assertEquals('user1', $query->where(['id' => 1])->scalar(), 'Asserting initial value');
801
802
        /* No cache */
803 4
        $update->bindValues([':id' => 1, ':name' => 'user11'])->execute();
804
805 4
        $this->assertEquals(
806 4
            'user11',
807 4
            $query->where(['id' => 1])->scalar(),
808 4
            'Query reflects DB changes when caching is disabled'
809
        );
810
811
        /* Connection cache */
812 4
        $db->cache(function (Connection $db) use ($query, $update) {
813 4
            $this->assertEquals(
814 4
                'user2',
815 4
                $query->where(['id' => 2])->scalar(),
816 4
                'Asserting initial value for user #2'
817
            );
818
819 4
            $update->bindValues([':id' => 2, ':name' => 'user22'])->execute();
820
821 4
            $this->assertEquals(
822 4
                'user2',
823 4
                $query->where(['id' => 2])->scalar(),
824 4
                'Query does NOT reflect DB changes when wrapped in connection caching'
825
            );
826
827 4
            $db->noCache(function () use ($query) {
828 4
                $this->assertEquals(
829 4
                    'user22',
830 4
                    $query->where(['id' => 2])->scalar(),
831 4
                    'Query reflects DB changes when wrapped in connection caching and noCache simultaneously'
832
                );
833 4
            });
834
835 4
            $this->assertEquals(
836 4
                'user2',
837 4
                $query->where(['id' => 2])->scalar(),
838 4
                'Cache does not get changes after getting newer data from DB in noCache block.'
839
            );
840 4
        }, 10);
841
842 4
        $db->setEnableQueryCache(false);
843
844 4
        $db->cache(function () use ($query, $update) {
845 4
            $this->assertEquals(
846 4
                'user22',
847 4
                $query->where(['id' => 2])->scalar(),
848 4
                'When cache is disabled for the whole connection, Query inside cache block does not get cached'
849
            );
850
851 4
            $update->bindValues([':id' => 2, ':name' => 'user2'])->execute();
852
853 4
            $this->assertEquals('user2', $query->where(['id' => 2])->scalar());
854 4
        }, 10);
855
856 4
        $db->setEnableQueryCache(true);
857 4
        $query->cache();
858
859 4
        $this->assertEquals('user11', $query->where(['id' => 1])->scalar());
860
861 4
        $update->bindValues([':id' => 1, ':name' => 'user1'])->execute();
862
863 4
        $this->assertEquals(
864 4
            'user11',
865 4
            $query->where(['id' => 1])->scalar(),
866 4
            'When both Connection and Query have cache enabled, we get cached value'
867
        );
868 4
        $this->assertEquals(
869 4
            'user1',
870 4
            $query->noCache()->where(['id' => 1])->scalar(),
871 4
            'When Query has disabled cache, we get actual data'
872
        );
873
874 4
        $db->cache(function () use ($query, $update) {
0 ignored issues
show
Unused Code introduced by
The import $update is not used and could be removed.

This check looks for imports that have been defined, but are not used in the scope.

Loading history...
875 4
            $this->assertEquals('user1', $query->noCache()->where(['id' => 1])->scalar());
876 4
            $this->assertEquals('user11', $query->cache()->where(['id' => 1])->scalar());
877 4
        }, 10);
878 4
    }
879
880
    /**
881
     * checks that all needed properties copied from source to new query
882
     */
883 4
    public function testQueryCreation(): void
884
    {
885 4
        $db = $this->getConnection();
886
887 4
        $where = 'id > :min_user_id';
888 4
        $limit = 50;
889 4
        $offset = 2;
890 4
        $orderBy = ['name' => SORT_ASC];
891 4
        $indexBy = 'id';
892 4
        $select = ['id' => 'id', 'name' => 'name', 'articles_count' => 'count(*)'];
893 4
        $selectOption = 'SQL_NO_CACHE';
894 4
        $from = 'recent_users';
895 4
        $groupBy = 'id';
896 4
        $having = ['>', 'articles_count', 0];
897 4
        $params = [':min_user_id' => 100];
898
899 4
        [$joinType, $joinTable, $joinOn] = $join = ['INNER', 'articles', 'articles.author_id=users.id'];
900
901 4
        $unionQuery = (new Query($db))
902 4
            ->select('id, name, 1000 as articles_count')
903 4
            ->from('admins');
904
905 4
        $withQuery = (new Query($db))
906 4
            ->select('id, name')
907 4
            ->from('users')
908 4
            ->where('DATE(registered_at) > "2020-01-01"');
909
910
        /** build target query */
911 4
        $sourceQuery = (new Query($db))
912 4
            ->where($where)
913 4
            ->limit($limit)
914 4
            ->offset($offset)
915 4
            ->orderBy($orderBy)
916 4
            ->indexBy($indexBy)
917 4
            ->select($select, $selectOption)
918 4
            ->distinct()
919 4
            ->from($from)
920 4
            ->groupBy($groupBy)
921 4
            ->having($having)
922 4
            ->addParams($params)
923 4
            ->join($joinType, $joinTable, $joinOn)
924 4
            ->union($unionQuery)
925 4
            ->withQuery($withQuery, $from);
926
927 4
        $newQuery = Query::create($db, $sourceQuery);
928
929 4
        $this->assertEquals($where, $newQuery->getWhere());
930 4
        $this->assertEquals($limit, $newQuery->getLimit());
931 4
        $this->assertEquals($offset, $newQuery->getOffset());
932 4
        $this->assertEquals($orderBy, $newQuery->getOrderBy());
933 4
        $this->assertEquals($indexBy, $newQuery->getIndexBy());
934 4
        $this->assertEquals($select, $newQuery->getSelect());
935 4
        $this->assertEquals($selectOption, $newQuery->getSelectOption());
936 4
        $this->assertTrue($newQuery->getDistinct());
937 4
        $this->assertEquals([$from], $newQuery->getFrom());
938 4
        $this->assertEquals([$groupBy], $newQuery->getGroupBy());
939 4
        $this->assertEquals($having, $newQuery->getHaving());
940 4
        $this->assertEquals($params, $newQuery->getParams());
941 4
        $this->assertEquals([$join], $newQuery->getJoin());
942 4
        $this->assertEquals([['query' => $unionQuery, 'all' => false]], $newQuery->getUnion());
943 4
        $this->assertEquals(
944 4
            [['query' => $withQuery, 'alias' => $from, 'recursive' => false]],
945 4
            $newQuery->getWithQueries()
946
        );
947 4
    }
948
}
949