Failed Conditions
Pull Request — master (#7885)
by Šimon
11:22
created

testQueryBuilderWithStringWhereClauseContainingOrAndConditionalPrimary()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 8
nc 1
nop 0
dl 0
loc 12
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\Tests\ORM\Functional;
6
7
use Doctrine\Common\Collections\ArrayCollection;
8
use Doctrine\ORM\Mapping\FetchMode;
9
use Doctrine\ORM\NonUniqueResultException;
10
use Doctrine\ORM\Query;
11
use Doctrine\ORM\Query\Parameter;
12
use Doctrine\ORM\Query\QueryException;
13
use Doctrine\ORM\UnexpectedResultException;
14
use Doctrine\Tests\Models\CMS\CmsArticle;
15
use Doctrine\Tests\Models\CMS\CmsPhonenumber;
16
use Doctrine\Tests\Models\CMS\CmsUser;
17
use Doctrine\Tests\OrmFunctionalTestCase;
18
use ProxyManager\Proxy\GhostObjectInterface;
19
use function array_values;
20
use function count;
21
22
/**
23
 * Functional Query tests.
24
 */
25
class QueryTest extends OrmFunctionalTestCase
26
{
27
    protected function setUp() : void
28
    {
29
        $this->useModelSet('cms');
30
31
        parent::setUp();
32
    }
33
34
    public function testSimpleQueries() : void
35
    {
36
        $user           = new CmsUser();
37
        $user->name     = 'Guilherme';
38
        $user->username = 'gblanco';
39
        $user->status   = 'developer';
40
        $this->em->persist($user);
41
        $this->em->flush();
42
        $this->em->clear();
43
44
        $query = $this->em->createQuery("select u, upper(u.name) from Doctrine\Tests\Models\CMS\CmsUser u where u.username = 'gblanco'");
45
46
        $result = $query->getResult();
47
48
        self::assertCount(1, $result);
49
        self::assertInstanceOf(CmsUser::class, $result[0][0]);
50
        self::assertEquals('Guilherme', $result[0][0]->name);
51
        self::assertEquals('gblanco', $result[0][0]->username);
52
        self::assertEquals('developer', $result[0][0]->status);
53
        self::assertEquals('GUILHERME', $result[0][1]);
54
55
        $resultArray = $query->getArrayResult();
56
        self::assertCount(1, $resultArray);
57
        self::assertInternalType('array', $resultArray[0][0]);
0 ignored issues
show
Deprecated Code introduced by
The function PHPUnit\Framework\Assert::assertInternalType() has been deprecated: https://github.com/sebastianbergmann/phpunit/issues/3369 ( Ignorable by Annotation )

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

57
        /** @scrutinizer ignore-deprecated */ self::assertInternalType('array', $resultArray[0][0]);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
58
        self::assertEquals('Guilherme', $resultArray[0][0]['name']);
59
        self::assertEquals('gblanco', $resultArray[0][0]['username']);
60
        self::assertEquals('developer', $resultArray[0][0]['status']);
61
        self::assertEquals('GUILHERME', $resultArray[0][1]);
62
63
        $scalarResult = $query->getScalarResult();
64
        self::assertCount(1, $scalarResult);
65
        self::assertEquals('Guilherme', $scalarResult[0]['u_name']);
66
        self::assertEquals('gblanco', $scalarResult[0]['u_username']);
67
        self::assertEquals('developer', $scalarResult[0]['u_status']);
68
        self::assertEquals('GUILHERME', $scalarResult[0][1]);
69
70
        $query = $this->em->createQuery("select upper(u.name) from Doctrine\Tests\Models\CMS\CmsUser u where u.username = 'gblanco'");
71
        self::assertEquals('GUILHERME', $query->getSingleScalarResult());
72
    }
73
74
    public function testJoinQueries() : void
75
    {
76
        $user           = new CmsUser();
77
        $user->name     = 'Guilherme';
78
        $user->username = 'gblanco';
79
        $user->status   = 'developer';
80
81
        $article1        = new CmsArticle();
82
        $article1->topic = 'Doctrine 2';
83
        $article1->text  = 'This is an introduction to Doctrine 2.';
84
        $user->addArticle($article1);
85
86
        $article2        = new CmsArticle();
87
        $article2->topic = 'Symfony 2';
88
        $article2->text  = 'This is an introduction to Symfony 2.';
89
        $user->addArticle($article2);
90
91
        $this->em->persist($user);
92
        $this->em->persist($article1);
93
        $this->em->persist($article2);
94
95
        $this->em->flush();
96
        $this->em->clear();
97
98
        $query = $this->em->createQuery('select u, a from ' . CmsUser::class . ' u join u.articles a ORDER BY a.topic');
99
        $users = $query->getResult();
100
101
        self::assertCount(1, $users);
102
        self::assertInstanceOf(CmsUser::class, $users[0]);
103
        self::assertCount(2, $users[0]->articles);
104
        self::assertEquals('Doctrine 2', $users[0]->articles[0]->topic);
105
        self::assertEquals('Symfony 2', $users[0]->articles[1]->topic);
106
    }
107
108
    public function testUsingZeroBasedQueryParameterShouldWork() : void
109
    {
110
        $user           = new CmsUser();
111
        $user->name     = 'Jonathan';
112
        $user->username = 'jwage';
113
        $user->status   = 'developer';
114
        $this->em->persist($user);
115
        $this->em->flush();
116
        $this->em->clear();
117
118
        $q = $this->em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.username = ?0');
119
        $q->setParameter(0, 'jwage');
120
        $user = $q->getSingleResult();
121
122
        self::assertNotNull($user);
123
    }
124
125
    public function testUsingUnknownQueryParameterShouldThrowException() : void
126
    {
127
        $this->expectException(QueryException::class);
128
        $this->expectExceptionMessage('Invalid parameter: token 2 is not defined in the query.');
129
130
        $q = $this->em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?1');
131
        $q->setParameter(2, 'jwage');
132
        $user = $q->getSingleResult();
0 ignored issues
show
Unused Code introduced by
The assignment to $user is dead and can be removed.
Loading history...
133
    }
134
135
    public function testTooManyParametersShouldThrowException() : void
136
    {
137
        $this->expectException(QueryException::class);
138
        $this->expectExceptionMessage('Too many parameters: the query defines 1 parameters and you bound 2');
139
140
        $q = $this->em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?1');
141
        $q->setParameter(1, 'jwage');
142
        $q->setParameter(2, 'jwage');
143
144
        $user = $q->getSingleResult();
0 ignored issues
show
Unused Code introduced by
The assignment to $user is dead and can be removed.
Loading history...
145
    }
146
147
    public function testTooFewParametersShouldThrowException() : void
148
    {
149
        $this->expectException(QueryException::class);
150
        $this->expectExceptionMessage('Too few parameters: the query defines 1 parameters but you only bound 0');
151
152
        $this->em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?1')
153
                  ->getSingleResult();
154
    }
155
156
    public function testInvalidInputParameterThrowsException() : void
157
    {
158
        $this->expectException(QueryException::class);
159
160
        $this->em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?')
161
                  ->setParameter(1, 'jwage')
162
                  ->getSingleResult();
163
    }
164
165
    public function testSetParameters() : void
166
    {
167
        $parameters = new ArrayCollection();
168
        $parameters->add(new Parameter(1, 'jwage'));
169
        $parameters->add(new Parameter(2, 'active'));
170
171
        $this->em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?1 AND u.status = ?2')
172
                  ->setParameters($parameters)
173
                  ->getResult();
174
175
        $extractValue = static function (Parameter $parameter) {
176
            return $parameter->getValue();
177
        };
178
179
        self::assertSame(
180
            $parameters->map($extractValue)->toArray(),
181
            $this->sqlLoggerStack->queries[$this->sqlLoggerStack->currentQuery]['params']
182
        );
183
    }
184
185
    public function testSetParametersBackwardsCompatible() : void
186
    {
187
        $parameters = [1 => 'jwage', 2 => 'active'];
188
189
        $this->em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?1 AND u.status = ?2')
190
                  ->setParameters($parameters)
191
                  ->getResult();
192
193
        self::assertSame(
194
            array_values($parameters),
195
            $this->sqlLoggerStack->queries[$this->sqlLoggerStack->currentQuery]['params']
196
        );
197
    }
198
199
    /**
200
     * @group DDC-1070
201
     */
202
    public function testIterateResultAsArrayAndParams() : void
203
    {
204
        $article1        = new CmsArticle();
205
        $article1->topic = 'Doctrine 2';
206
        $article1->text  = 'This is an introduction to Doctrine 2.';
207
208
        $article2        = new CmsArticle();
209
        $article2->topic = 'Symfony 2';
210
        $article2->text  = 'This is an introduction to Symfony 2.';
211
212
        $this->em->persist($article1);
213
        $this->em->persist($article2);
214
215
        $this->em->flush();
216
        $this->em->clear();
217
        $articleId = $article1->id;
218
219
        $query    = $this->em->createQuery('select a from ' . CmsArticle::class . ' a WHERE a.topic = ?1');
220
        $articles = $query->iterate(new ArrayCollection([new Parameter(1, 'Doctrine 2')]), Query::HYDRATE_ARRAY);
221
222
        $expectedArticle = [
223
            'id'      => $articleId,
224
            'topic'   => 'Doctrine 2',
225
            'text'    => 'This is an introduction to Doctrine 2.',
226
            'version' => 1,
227
        ];
228
229
        $found = [];
230
231
        foreach ($articles as $article) {
232
            $found[] = $article;
233
        }
234
235
        self::assertCount(1, $found);
236
        self::assertEquals(
237
            [
238
                [
0 ignored issues
show
Coding Style introduced by
Multi-line array contains a single value; use single-line array instead
Loading history...
239
                    $expectedArticle,
240
                ],
241
            ],
242
            $found
243
        );
244
245
        $articles = $query->getIterable(
246
            new ArrayCollection([new Parameter(1, 'Doctrine 2')]), Query::HYDRATE_ARRAY
247
        );
248
249
        $found = [];
250
251
        foreach ($articles as $article) {
252
            $found[] = $article;
253
        }
254
255
        self::assertCount(1, $found);
256
        self::assertEquals(
257
            [
0 ignored issues
show
Coding Style introduced by
Multi-line array contains a single value; use single-line array instead
Loading history...
258
                $expectedArticle,
259
            ],
260
            $found
261
        );
262
    }
263
264
    public function testIterateResultIterativelyBuildUpUnitOfWork() : void
265
    {
266
        $article1        = new CmsArticle();
267
        $article1->topic = 'Doctrine 2';
268
        $article1->text  = 'This is an introduction to Doctrine 2.';
269
270
        $article2        = new CmsArticle();
271
        $article2->topic = 'Symfony 2';
272
        $article2->text  = 'This is an introduction to Symfony 2.';
273
274
        $this->em->persist($article1);
275
        $this->em->persist($article2);
276
277
        $this->em->flush();
278
        $this->em->clear();
279
280
        $query    = $this->em->createQuery('select a from ' . CmsArticle::class . ' a');
281
        $articles = $query->iterate();
282
283
        $iteratedCount = 0;
284
        $topics        = [];
285
286
        foreach ($articles as $row) {
287
            $article  = $row[0];
288
            $topics[] = $article->topic;
289
290
            $identityMap      = $this->em->getUnitOfWork()->getIdentityMap();
291
            $identityMapCount = count($identityMap[CmsArticle::class]);
292
            self::assertGreaterThan($iteratedCount, $identityMapCount);
293
294
            $iteratedCount++;
295
        }
296
297
        self::assertSame(['Doctrine 2', 'Symfony 2'], $topics);
298
        self::assertSame(2, $iteratedCount);
299
300
        $articles = $query->getIterable();
301
302
        $iteratedCount = 0;
303
        $topics        = [];
304
305
        foreach ($articles as $article) {
306
            $topics[] = $article->topic;
307
308
            $identityMap      = $this->em->getUnitOfWork()->getIdentityMap();
309
            $identityMapCount = count($identityMap[CmsArticle::class]);
310
            self::assertGreaterThan($iteratedCount, $identityMapCount);
311
312
            $iteratedCount++;
313
        }
314
315
        self::assertSame(['Doctrine 2', 'Symfony 2'], $topics);
316
        self::assertSame(2, $iteratedCount);
317
    }
318
319
    public function testIterateResultClearEveryCycle() : void
320
    {
321
        $article1        = new CmsArticle();
322
        $article1->topic = 'Doctrine 2';
323
        $article1->text  = 'This is an introduction to Doctrine 2.';
324
325
        $article2        = new CmsArticle();
326
        $article2->topic = 'Symfony 2';
327
        $article2->text  = 'This is an introduction to Symfony 2.';
328
329
        $this->em->persist($article1);
330
        $this->em->persist($article2);
331
332
        $this->em->flush();
333
        $this->em->clear();
334
335
        $query    = $this->em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsArticle a');
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 4 spaces
Loading history...
336
337
        $articles = $query->iterate();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 6 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
338
        $iteratedCount = 0;
339
        $topics        = [];
340
        foreach ($articles as $row) {
341
            $article  = $row[0];
342
            $topics[] = $article->topic;
343
344
            $this->em->clear();
345
346
            $iteratedCount++;
347
        }
348
349
        self::assertSame(['Doctrine 2', 'Symfony 2'], $topics);
350
        self::assertSame(2, $iteratedCount);
351
352
        $articles = $query->getIterable();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 6 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
353
        $iteratedCount = 0;
354
        $topics        = [];
355
        foreach ($articles as $article) {
356
            $topics[] = $article->topic;
357
358
            $this->em->clear();
359
360
            $iteratedCount++;
361
        }
362
363
        self::assertSame(['Doctrine 2', 'Symfony 2'], $topics);
364
        self::assertSame(2, $iteratedCount);
365
366
        $this->em->flush();
367
    }
368
369
    public function testIterateResultFetchJoinedCollectionThrowsException() : void
370
    {
371
        $this->expectException(QueryException::class);
372
373
        $query = $this->em->createQuery("SELECT u, a FROM ' . CmsUser::class . ' u JOIN u.articles a");
374
        $query->iterate();
375
    }
376
377
    public function testGetIterableResultFetchJoinedCollectionThrowsException() : void
378
    {
379
        $this->expectException(QueryException::class);
380
381
        $query    = $this->em->createQuery("SELECT u, a FROM ' . CmsUser::class . ' u JOIN u.articles a");
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 4 spaces
Loading history...
382
        $query->getIterable();
383
    }
384
385
    /**
386
     * @expectedException Doctrine\ORM\NoResultException
387
     */
388
    public function testGetSingleResultThrowsExceptionOnNoResult() : void
389
    {
390
        $this->em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsArticle a')
391
             ->getSingleResult();
392
    }
393
394
    /**
395
     * @expectedException Doctrine\ORM\NoResultException
396
     */
397
    public function testGetSingleScalarResultThrowsExceptionOnNoResult() : void
398
    {
399
        $this->em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsArticle a')
400
             ->getSingleScalarResult();
401
    }
402
403
    /**
404
     * @expectedException Doctrine\ORM\NonUniqueResultException
405
     */
406
    public function testGetSingleScalarResultThrowsExceptionOnNonUniqueResult() : void
407
    {
408
        $user           = new CmsUser();
409
        $user->name     = 'Guilherme';
410
        $user->username = 'gblanco';
411
        $user->status   = 'developer';
412
413
        $article1        = new CmsArticle();
414
        $article1->topic = 'Doctrine 2';
415
        $article1->text  = 'This is an introduction to Doctrine 2.';
416
        $user->addArticle($article1);
417
418
        $article2        = new CmsArticle();
419
        $article2->topic = 'Symfony 2';
420
        $article2->text  = 'This is an introduction to Symfony 2.';
421
        $user->addArticle($article2);
422
423
        $this->em->persist($user);
424
        $this->em->persist($article1);
425
        $this->em->persist($article2);
426
427
        $this->em->flush();
428
        $this->em->clear();
429
430
        $this->em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsArticle a')
431
             ->getSingleScalarResult();
432
    }
433
434
    public function testModifiedLimitQuery() : void
435
    {
436
        for ($i = 0; $i < 5; $i++) {
437
            $user           = new CmsUser();
438
            $user->name     = 'Guilherme' . $i;
439
            $user->username = 'gblanco' . $i;
440
            $user->status   = 'developer';
441
            $this->em->persist($user);
442
        }
443
444
        $this->em->flush();
445
        $this->em->clear();
446
447
        $data = $this->em->createQuery('SELECT u FROM ' . CmsUser::class . ' u')
448
                  ->setFirstResult(1)
449
                  ->setMaxResults(2)
450
                  ->getResult();
451
452
        self::assertCount(2, $data);
453
        self::assertEquals('gblanco1', $data[0]->username);
454
        self::assertEquals('gblanco2', $data[1]->username);
455
456
        $data = $this->em->createQuery('SELECT u FROM ' . CmsUser::class . ' u')
457
                  ->setFirstResult(3)
458
                  ->setMaxResults(2)
459
                  ->getResult();
460
461
        self::assertCount(2, $data);
462
        self::assertEquals('gblanco3', $data[0]->username);
463
        self::assertEquals('gblanco4', $data[1]->username);
464
465
        $data = $this->em->createQuery('SELECT u FROM ' . CmsUser::class . ' u')
0 ignored issues
show
Unused Code introduced by
The assignment to $data is dead and can be removed.
Loading history...
466
                  ->setFirstResult(3)
467
                  ->setMaxResults(2)
468
                  ->getScalarResult();
469
    }
470
471
    /**
472
     * @group DDC-604
473
     */
474
    public function testEntityParameters() : void
475
    {
476
        $article          = new CmsArticle();
477
        $article->topic   = 'dr. dolittle';
478
        $article->text    = 'Once upon a time ...';
479
        $author           = new CmsUser();
480
        $author->name     = 'anonymous';
481
        $author->username = 'anon';
482
        $author->status   = 'here';
483
        $article->user    = $author;
484
        $this->em->persist($author);
485
        $this->em->persist($article);
486
        $this->em->flush();
487
        $this->em->clear();
488
489
        /** @var CmsArticle[] $result */
490
        $result = $this->em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsArticle a where a.topic = :topic and a.user = :user')
491
                ->setParameter('user', $this->em->getReference(CmsUser::class, $author->id))
492
                ->setParameter('topic', 'dr. dolittle')
493
                ->getResult();
494
495
        self::assertCount(1, $result);
496
        self::assertInstanceOf(CmsArticle::class, $result[0]);
497
        self::assertEquals('dr. dolittle', $result[0]->topic);
498
499
        /** @var CmsUser|GhostObjectInterface $user */
500
        $user = $result[0]->user;
501
502
        self::assertInstanceOf(CmsUser::class, $user);
503
        self::assertInstanceOf(GhostObjectInterface::class, $user);
504
        self::assertFalse($user->isProxyInitialized());
0 ignored issues
show
Bug introduced by
The method isProxyInitialized() does not exist on Doctrine\Tests\Models\CMS\CmsUser. ( Ignorable by Annotation )

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

504
        self::assertFalse($user->/** @scrutinizer ignore-call */ isProxyInitialized());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
505
    }
506
507
    /**
508
     * @group DDC-952
509
     */
510
    public function testEnableFetchEagerMode() : void
511
    {
512
        for ($i = 0; $i < 10; $i++) {
513
            $article = new CmsArticle();
514
515
            $article->topic = 'dr. dolittle';
516
            $article->text  = 'Once upon a time ...';
517
518
            $author = new CmsUser();
519
520
            $author->name     = 'anonymous';
521
            $author->username = 'anon' . $i;
522
            $author->status   = 'here';
523
            $article->user    = $author;
524
525
            $this->em->persist($author);
526
            $this->em->persist($article);
527
        }
528
529
        $this->em->flush();
530
        $this->em->clear();
531
532
        $articles = $this->em
533
            ->createQuery('select a from Doctrine\Tests\Models\CMS\CmsArticle a')
534
            ->setFetchMode(CmsArticle::class, 'user', FetchMode::EAGER)
0 ignored issues
show
Bug introduced by
Doctrine\ORM\Mapping\FetchMode::EAGER of type string is incompatible with the type integer expected by parameter $fetchMode of Doctrine\ORM\AbstractQuery::setFetchMode(). ( Ignorable by Annotation )

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

534
            ->setFetchMode(CmsArticle::class, 'user', /** @scrutinizer ignore-type */ FetchMode::EAGER)
Loading history...
535
            ->getResult();
536
537
        self::assertCount(10, $articles);
538
539
        foreach ($articles as $article) {
540
            self::assertNotInstanceOf(GhostObjectInterface::class, $article);
541
        }
542
    }
543
544
    /**
545
     * @group DDC-991
546
     */
547
    public function testgetOneOrNullResult() : void
548
    {
549
        $user           = new CmsUser();
550
        $user->name     = 'Guilherme';
551
        $user->username = 'gblanco';
552
        $user->status   = 'developer';
553
        $this->em->persist($user);
554
        $this->em->flush();
555
        $this->em->clear();
556
557
        $query       = $this->em->createQuery('select u from ' . CmsUser::class . " u where u.username = 'gblanco'");
558
        $fetchedUser = $query->getOneOrNullResult();
559
560
        self::assertInstanceOf(CmsUser::class, $fetchedUser);
561
        self::assertEquals('gblanco', $fetchedUser->username);
562
563
        $query           = $this->em->createQuery('select u.username from ' . CmsUser::class . " u where u.username = 'gblanco'");
564
        $fetchedUsername = $query->getOneOrNullResult(Query::HYDRATE_SINGLE_SCALAR);
565
566
        self::assertEquals('gblanco', $fetchedUsername);
567
    }
568
569
    /**
570
     * @group DDC-991
571
     */
572
    public function testgetOneOrNullResultSeveralRows() : void
573
    {
574
        $user           = new CmsUser();
575
        $user->name     = 'Guilherme';
576
        $user->username = 'gblanco';
577
        $user->status   = 'developer';
578
        $this->em->persist($user);
579
        $user           = new CmsUser();
580
        $user->name     = 'Roman';
581
        $user->username = 'romanb';
582
        $user->status   = 'developer';
583
        $this->em->persist($user);
584
        $this->em->flush();
585
        $this->em->clear();
586
587
        $query = $this->em->createQuery('select u from Doctrine\Tests\Models\CMS\CmsUser u');
588
589
        $this->expectException(NonUniqueResultException::class);
590
591
        $fetchedUser = $query->getOneOrNullResult();
0 ignored issues
show
Unused Code introduced by
The assignment to $fetchedUser is dead and can be removed.
Loading history...
592
    }
593
594
    /**
595
     * @group DDC-991
596
     */
597
    public function testgetOneOrNullResultNoRows() : void
598
    {
599
        $query = $this->em->createQuery('select u from Doctrine\Tests\Models\CMS\CmsUser u');
600
        self::assertNull($query->getOneOrNullResult());
601
602
        $query = $this->em->createQuery("select u.username from Doctrine\Tests\Models\CMS\CmsUser u where u.username = 'gblanco'");
603
        self::assertNull($query->getOneOrNullResult(Query::HYDRATE_SCALAR));
604
    }
605
606
    /**
607
     * @group DBAL-171
608
     */
609
    public function testParameterOrder() : void
610
    {
611
        $user1           = new CmsUser();
612
        $user1->name     = 'Benjamin';
613
        $user1->username = 'beberlei';
614
        $user1->status   = 'developer';
615
        $this->em->persist($user1);
616
617
        $user2           = new CmsUser();
618
        $user2->name     = 'Roman';
619
        $user2->username = 'romanb';
620
        $user2->status   = 'developer';
621
        $this->em->persist($user2);
622
623
        $user3           = new CmsUser();
624
        $user3->name     = 'Jonathan';
625
        $user3->username = 'jwage';
626
        $user3->status   = 'developer';
627
        $this->em->persist($user3);
628
629
        $this->em->flush();
630
        $this->em->clear();
631
632
        $query = $this->em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.status = :a AND u.id IN (:b)');
633
        $query->setParameters(new ArrayCollection(
634
            [
635
                new Parameter('b', [$user1->id, $user2->id, $user3->id]),
636
                new Parameter('a', 'developer'),
637
            ]
638
        ));
639
        $result = $query->getResult();
640
641
        self::assertCount(3, $result);
642
    }
643
644
    public function testDqlWithAutoInferOfParameters() : void
645
    {
646
        $user           = new CmsUser();
647
        $user->name     = 'Benjamin';
648
        $user->username = 'beberlei';
649
        $user->status   = 'developer';
650
        $this->em->persist($user);
651
652
        $user           = new CmsUser();
653
        $user->name     = 'Roman';
654
        $user->username = 'romanb';
655
        $user->status   = 'developer';
656
        $this->em->persist($user);
657
658
        $user           = new CmsUser();
659
        $user->name     = 'Jonathan';
660
        $user->username = 'jwage';
661
        $user->status   = 'developer';
662
        $this->em->persist($user);
663
664
        $this->em->flush();
665
        $this->em->clear();
666
667
        $query = $this->em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username IN (?0)');
668
        $query->setParameter(0, ['beberlei', 'jwage']);
669
670
        $users = $query->execute();
671
672
        self::assertCount(2, $users);
673
    }
674
675
    public function testQueryBuilderWithStringWhereClauseContainingOrAndConditionalPrimary() : void
676
    {
677
        $qb = $this->em->createQueryBuilder();
678
        $qb->select('u')
679
           ->from(CmsUser::class, 'u')
680
           ->innerJoin('u.articles', 'a')
681
           ->where('(u.id = 0) OR (u.id IS NULL)');
682
683
        $query = $qb->getQuery();
684
        $users = $query->execute();
685
686
        self::assertCount(0, $users);
687
    }
688
689
    public function testQueryWithArrayOfEntitiesAsParameter() : void
690
    {
691
        $userA           = new CmsUser();
692
        $userA->name     = 'Benjamin';
693
        $userA->username = 'beberlei';
694
        $userA->status   = 'developer';
695
        $this->em->persist($userA);
696
697
        $userB           = new CmsUser();
698
        $userB->name     = 'Roman';
699
        $userB->username = 'romanb';
700
        $userB->status   = 'developer';
701
        $this->em->persist($userB);
702
703
        $userC           = new CmsUser();
704
        $userC->name     = 'Jonathan';
705
        $userC->username = 'jwage';
706
        $userC->status   = 'developer';
707
        $this->em->persist($userC);
708
709
        $this->em->flush();
710
        $this->em->clear();
711
712
        $query = $this->em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u IN (?0) OR u.username = ?1');
713
        $query->setParameter(0, [$userA, $userC]);
714
        $query->setParameter(1, 'beberlei');
715
716
        $users = $query->execute();
717
718
        self::assertCount(2, $users);
719
    }
720
721
    public function testQueryWithHiddenAsSelectExpression() : void
722
    {
723
        $userA           = new CmsUser();
724
        $userA->name     = 'Benjamin';
725
        $userA->username = 'beberlei';
726
        $userA->status   = 'developer';
727
        $this->em->persist($userA);
728
729
        $userB           = new CmsUser();
730
        $userB->name     = 'Roman';
731
        $userB->username = 'romanb';
732
        $userB->status   = 'developer';
733
        $this->em->persist($userB);
734
735
        $userC           = new CmsUser();
736
        $userC->name     = 'Jonathan';
737
        $userC->username = 'jwage';
738
        $userC->status   = 'developer';
739
        $this->em->persist($userC);
740
741
        $this->em->flush();
742
        $this->em->clear();
743
744
        $query = $this->em->createQuery('SELECT u, (SELECT COUNT(u2.id) FROM Doctrine\Tests\Models\CMS\CmsUser u2) AS HIDDEN total FROM Doctrine\Tests\Models\CMS\CmsUser u');
745
        $users = $query->execute();
746
747
        self::assertCount(3, $users);
748
        self::assertInstanceOf(CmsUser::class, $users[0]);
749
    }
750
751
    /**
752
     * @group DDC-1651
753
     */
754
    public function testSetParameterBindingSingleIdentifierObject() : void
755
    {
756
        $userC           = new CmsUser();
757
        $userC->name     = 'Jonathan';
758
        $userC->username = 'jwage';
759
        $userC->status   = 'developer';
760
        $this->em->persist($userC);
761
762
        $this->em->flush();
763
        $this->em->clear();
764
765
        $q = $this->em->createQuery('SELECT DISTINCT u from Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1');
766
        $q->setParameter(1, $userC);
767
768
        self::assertEquals($userC, $q->getParameter(1)->getValue());
769
770
        // Parameter is not converted before, but it should be converted during execution. Test should not fail here
771
        $q->getResult();
772
    }
773
774
    /**
775
     * @group DDC-2319
776
     */
777
    public function testSetCollectionParameterBindingSingleIdentifierObject() : void
778
    {
779
        $u1           = new CmsUser();
780
        $u1->name     = 'Name1';
781
        $u1->username = 'username1';
782
        $u1->status   = 'developer';
783
        $this->em->persist($u1);
784
785
        $u2           = new CmsUser();
786
        $u2->name     = 'Name2';
787
        $u2->username = 'username2';
788
        $u2->status   = 'tester';
789
        $this->em->persist($u2);
790
791
        $u3           = new CmsUser();
792
        $u3->name     = 'Name3';
793
        $u3->username = 'username3';
794
        $u3->status   = 'tester';
795
        $this->em->persist($u3);
796
797
        $this->em->flush();
798
        $this->em->clear();
799
800
        $userCollection = new ArrayCollection();
801
802
        $userCollection->add($u1);
803
        $userCollection->add($u2);
804
        $userCollection->add($u3->getId());
805
806
        $q = $this->em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u IN (:users) ORDER BY u.id');
807
        $q->setParameter('users', $userCollection);
808
        $users = $q->execute();
809
810
        self::assertCount(3, $users);
811
        self::assertInstanceOf(CmsUser::class, $users[0]);
812
        self::assertInstanceOf(CmsUser::class, $users[1]);
813
        self::assertInstanceOf(CmsUser::class, $users[2]);
814
815
        $resultUser1 = $users[0];
816
        $resultUser2 = $users[1];
817
        $resultUser3 = $users[2];
818
819
        self::assertEquals($u1->username, $resultUser1->username);
820
        self::assertEquals($u2->username, $resultUser2->username);
821
        self::assertEquals($u3->username, $resultUser3->username);
822
    }
823
824
    /**
825
     * @group DDC-1822
826
     */
827
    public function testUnexpectedResultException() : void
828
    {
829
        $dql          = 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u';
830
        $u1           = new CmsUser();
831
        $u2           = new CmsUser();
832
        $u1->name     = 'Fabio B. Silva';
833
        $u1->username = 'FabioBatSilva';
834
        $u1->status   = 'developer';
835
        $u2->name     = 'Test';
836
        $u2->username = 'test';
837
        $u2->status   = 'tester';
838
839
        try {
840
            $this->em->createQuery($dql)->getSingleResult();
841
            $this->fail('Expected exception "\Doctrine\ORM\NoResultException".');
842
        } catch (UnexpectedResultException $exc) {
843
            self::assertInstanceOf('\Doctrine\ORM\NoResultException', $exc);
844
        }
845
846
        $this->em->persist($u1);
847
        $this->em->persist($u2);
848
        $this->em->flush();
849
        $this->em->clear();
850
851
        try {
852
            $this->em->createQuery($dql)->getSingleResult();
853
            $this->fail('Expected exception "\Doctrine\ORM\NonUniqueResultException".');
854
        } catch (UnexpectedResultException $exc) {
855
            self::assertInstanceOf('\Doctrine\ORM\NonUniqueResultException', $exc);
856
        }
857
    }
858
859
    public function testMultipleJoinComponentsUsingInnerJoin() : void
860
    {
861
        $userA           = new CmsUser();
862
        $userA->name     = 'Benjamin';
863
        $userA->username = 'beberlei';
864
        $userA->status   = 'developer';
865
866
        $phonenumberA              = new CmsPhonenumber();
867
        $phonenumberA->phonenumber = '111111';
868
        $userA->addPhonenumber($phonenumberA);
869
870
        $userB           = new CmsUser();
871
        $userB->name     = 'Alexander';
872
        $userB->username = 'asm89';
873
        $userB->status   = 'developer';
874
875
        $this->em->persist($userA);
876
        $this->em->persist($userB);
877
        $this->em->flush();
878
        $this->em->clear();
879
880
        $query = $this->em->createQuery('
881
            SELECT u, p
882
              FROM Doctrine\Tests\Models\CMS\CmsUser u
883
             INNER JOIN Doctrine\Tests\Models\CMS\CmsPhonenumber p WITH u = p.user
884
        ');
885
        $users = $query->execute();
886
887
        self::assertCount(2, $users);
888
        self::assertInstanceOf(CmsUser::class, $users[0]);
889
        self::assertInstanceOf(CmsPhonenumber::class, $users[1]);
890
    }
891
892
    public function testMultipleJoinComponentsUsingLeftJoin() : void
893
    {
894
        $userA           = new CmsUser();
895
        $userA->name     = 'Benjamin';
896
        $userA->username = 'beberlei';
897
        $userA->status   = 'developer';
898
899
        $phonenumberA              = new CmsPhonenumber();
900
        $phonenumberA->phonenumber = '111111';
901
        $userA->addPhonenumber($phonenumberA);
902
903
        $userB           = new CmsUser();
904
        $userB->name     = 'Alexander';
905
        $userB->username = 'asm89';
906
        $userB->status   = 'developer';
907
908
        $this->em->persist($userA);
909
        $this->em->persist($userB);
910
        $this->em->flush();
911
        $this->em->clear();
912
913
        $query = $this->em->createQuery('
914
            SELECT u, p
915
              FROM Doctrine\Tests\Models\CMS\CmsUser u
916
              LEFT JOIN Doctrine\Tests\Models\CMS\CmsPhonenumber p WITH u = p.user
917
        ');
918
        $users = $query->execute();
919
920
        self::assertCount(4, $users);
921
        self::assertInstanceOf(CmsUser::class, $users[0]);
922
        self::assertInstanceOf(CmsPhonenumber::class, $users[1]);
923
        self::assertInstanceOf(CmsUser::class, $users[2]);
924
        self::assertNull($users[3]);
925
    }
926
}
927