/
ConnectionTest.php
1133 lines (977 loc) · 39.4 KB
/
ConnectionTest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Test\TestCase\Database;
use Cake\Cache\Engine\NullEngine;
use Cake\Core\App;
use Cake\Database\Connection;
use Cake\Database\Driver;
use Cake\Database\Driver\Mysql;
use Cake\Database\Driver\Sqlserver;
use Cake\Database\Exception\MissingConnectionException;
use Cake\Database\Exception\MissingDriverException;
use Cake\Database\Exception\MissingExtensionException;
use Cake\Database\Exception\NestedTransactionRollbackException;
use Cake\Database\Schema\CachedCollection;
use Cake\Database\StatementInterface;
use Cake\Datasource\ConnectionManager;
use Cake\Log\Log;
use Cake\TestSuite\TestCase;
use DateTime;
use Error;
use Exception;
use InvalidArgumentException;
use PDO;
use ReflectionMethod;
use ReflectionProperty;
use TestApp\Database\Driver\DisabledDriver;
use TestApp\Database\Driver\RetryDriver;
use function Cake\Core\namespaceSplit;
/**
* Tests Connection class
*/
class ConnectionTest extends TestCase
{
/**
* @var array<string>
*/
protected array $fixtures = ['core.Things'];
/**
* Where the NestedTransactionRollbackException was created.
*
* @var int
*/
protected $rollbackSourceLine = -1;
/**
* Internal states of nested transaction.
*
* @var array
*/
protected $nestedTransactionStates = [];
/**
* @var bool
*/
protected $logState;
/**
* @var \Cake\Database\Connection
*/
protected $connection;
/**
* @var \Cake\Database\Log\QueryLogger
*/
protected $defaultLogger;
public function setUp(): void
{
parent::setUp();
$this->connection = ConnectionManager::get('test');
static::setAppNamespace();
}
public function tearDown(): void
{
parent::tearDown();
$this->connection->disableSavePoints();
ConnectionManager::drop('test:read');
ConnectionManager::dropAlias('test:read');
Log::reset();
unset($this->connection);
}
/**
* Auxiliary method to build a mock for a driver so it can be injected into
* the connection object
*
* @return \Cake\Database\Driver|\PHPUnit\Framework\MockObject\MockObject
*/
public function getMockFormDriver()
{
$driver = $this->getMockBuilder(Driver::class)->getMock();
$driver->expects($this->once())
->method('enabled')
->willReturn(true);
return $driver;
}
/**
* Tests creating a connection using no driver throws an exception
*/
public function testNoDriver(): void
{
$this->expectException(MissingDriverException::class);
$this->expectExceptionMessage('Could not find driver `` for connection ``.');
new Connection([]);
}
/**
* Tests creating a connection using an invalid driver throws an exception
*/
public function testEmptyDriver(): void
{
$this->expectException(Error::class);
new Connection(['driver' => false]);
}
/**
* Tests creating a connection using an invalid driver throws an exception
*/
public function testMissingDriver(): void
{
$this->expectException(MissingDriverException::class);
$this->expectExceptionMessage('Could not find driver `\Foo\InvalidDriver` for connection ``.');
new Connection(['driver' => '\Foo\InvalidDriver']);
}
/**
* Tests trying to use a disabled driver throws an exception
*/
public function testDisabledDriver(): void
{
$this->expectException(MissingExtensionException::class);
$this->expectExceptionMessage(
'Database driver `DriverMock` cannot be used due to a missing PHP extension or unmet dependency. ' .
'Requested by connection `custom_connection_name`'
);
$mock = $this->getMockBuilder(Mysql::class)
->onlyMethods(['enabled'])
->setMockClassName('DriverMock')
->getMock();
new Connection(['driver' => $mock, 'name' => 'custom_connection_name']);
}
/**
* Tests that the `driver` option supports the short classname/plugin syntax.
*/
public function testDriverOptionClassNameSupport(): void
{
$connection = new Connection(['driver' => 'TestDriver']);
$this->assertInstanceOf('TestApp\Database\Driver\TestDriver', $connection->getDriver());
$connection = new Connection(['driver' => 'TestPlugin.TestDriver']);
$this->assertInstanceOf('TestPlugin\Database\Driver\TestDriver', $connection->getDriver());
[, $name] = namespaceSplit(get_class($this->connection->getDriver()));
$connection = new Connection(['driver' => $name]);
$this->assertInstanceOf(get_class($this->connection->getDriver()), $connection->getDriver());
}
/**
* Test providing a unique read config only creates separate drivers.
*/
public function testDifferentReadDriver(): void
{
$this->skipIf(!extension_loaded('pdo_sqlite'), 'Skipping as SQLite extension is missing');
$config = ConnectionManager::getConfig('test') + ['read' => ['database' => 'read_test.db']];
$connection = new Connection($config);
$this->assertNotSame($connection->getDriver(Connection::ROLE_READ), $connection->getDriver(Connection::ROLE_WRITE));
$this->assertSame(Connection::ROLE_READ, $connection->getDriver(Connection::ROLE_READ)->getRole());
$this->assertSame(Connection::ROLE_WRITE, $connection->getDriver(Connection::ROLE_WRITE)->getRole());
}
/**
* Test providing a unique write config only creates separate drivers.
*/
public function testDifferentWriteDriver(): void
{
$this->skipIf(!extension_loaded('pdo_sqlite'), 'Skipping as SQLite extension is missing');
$config = ConnectionManager::getConfig('test') + ['write' => ['database' => 'read_test.db']];
$connection = new Connection($config);
$this->assertNotSame($connection->getDriver(Connection::ROLE_READ), $connection->getDriver(Connection::ROLE_WRITE));
$this->assertSame(Connection::ROLE_READ, $connection->getDriver(Connection::ROLE_READ)->getRole());
$this->assertSame(Connection::ROLE_WRITE, $connection->getDriver(Connection::ROLE_WRITE)->getRole());
}
/**
* Test providing the same read and write config uses a shared driver.
*/
public function testSameReadWriteDriver(): void
{
$this->skipIf(!extension_loaded('pdo_sqlite'), 'Skipping as SQLite extension is missing');
$config = ConnectionManager::getConfig('test') + ['read' => ['database' => 'read_test.db'], 'write' => ['database' => 'read_test.db']];
$connection = new Connection($config);
$this->assertSame($connection->getDriver(Connection::ROLE_READ), $connection->getDriver(Connection::ROLE_WRITE));
$this->assertSame(Connection::ROLE_WRITE, $connection->getDriver(Connection::ROLE_READ)->getRole());
$this->assertSame(Connection::ROLE_WRITE, $connection->getDriver(Connection::ROLE_WRITE)->getRole());
}
public function testDisabledReadWriteDriver(): void
{
$this->skipIf(!extension_loaded('pdo_sqlite'), 'Skipping as SQLite extension is missing');
$config = ['driver' => DisabledDriver::class] + ConnectionManager::getConfig('test');
$this->expectException(MissingExtensionException::class);
new Connection($config);
}
/**
* Tests that connecting with invalid credentials or database name throws an exception
*/
public function testWrongCredentials(): void
{
$config = ConnectionManager::getConfig('test');
$this->skipIf(isset($config['url']), 'Datasource has dsn, skipping.');
$connection = new Connection(['database' => '/dev/nonexistent'] + ConnectionManager::getConfig('test'));
$e = null;
try {
$connection->getDriver()->connect();
} catch (MissingConnectionException $e) {
}
$this->assertNotNull($e);
$this->assertStringStartsWith(
sprintf(
'Connection to %s could not be established:',
App::shortName(get_class($connection->getDriver()), 'Database/Driver')
),
$e->getMessage()
);
$this->assertInstanceOf('PDOException', $e->getPrevious());
}
public function testConnectRetry(): void
{
$this->skipIf(!ConnectionManager::get('test')->getDriver() instanceof Sqlserver);
$connection = new Connection(['driver' => 'RetryDriver']);
$this->assertInstanceOf(RetryDriver::class, $connection->getDriver());
try {
$connection->execute('SELECT 1');
} catch (MissingConnectionException $e) {
$this->assertSame(4, $connection->getDriver()->getConnectRetries());
}
}
/**
* Tests executing a simple query using bound values
*/
public function testExecuteWithArguments(): void
{
$sql = 'SELECT 1 + ?';
$statement = $this->connection->execute($sql, [1], ['integer']);
$result = $statement->fetchAll();
$this->assertCount(1, $result);
$this->assertEquals([2], $result[0]);
$statement->closeCursor();
$sql = 'SELECT 1 + ? + ? AS total';
$statement = $this->connection->execute($sql, [2, 3], ['integer', 'integer']);
$result = $statement->fetchAll('assoc');
$statement->closeCursor();
$this->assertCount(1, $result);
$this->assertEquals(['total' => 6], $result[0]);
$sql = 'SELECT 1 + :one + :two AS total';
$statement = $this->connection->execute($sql, ['one' => 2, 'two' => 3], ['one' => 'integer', 'two' => 'integer']);
$result = $statement->fetchAll('assoc');
$statement->closeCursor();
$this->assertCount(1, $result);
$this->assertEquals(['total' => 6], $result[0]);
}
/**
* Tests executing a query with params and associated types
*/
public function testExecuteWithArgumentsAndTypes(): void
{
$sql = "SELECT '2012-01-01' = ?";
$statement = $this->connection->execute($sql, [new DateTime('2012-01-01')], ['date']);
$result = $statement->fetch();
$statement->closeCursor();
$this->assertTrue((bool)$result[0]);
}
/**
* Tests that passing a unknown value to a query throws an exception
*/
public function testExecuteWithMissingType(): void
{
$this->expectException(InvalidArgumentException::class);
$sql = 'SELECT ?';
$this->connection->execute($sql, [new DateTime('2012-01-01')], ['bar']);
}
/**
* Tests executing a query with no params also works
*/
public function testExecuteWithNoParams(): void
{
$sql = 'SELECT 1';
$statement = $this->connection->execute($sql);
$result = $statement->fetch();
$this->assertCount(1, $result);
$this->assertEquals([1], $result);
$statement->closeCursor();
}
/**
* Tests it is possible to insert data into a table using matching types by key name
*/
public function testInsertWithMatchingTypes(): void
{
$data = ['id' => '3', 'title' => 'a title', 'body' => 'a body'];
$result = $this->connection->insert(
'things',
$data,
['id' => 'integer', 'title' => 'string', 'body' => 'string']
);
$this->assertInstanceOf(StatementInterface::class, $result);
$result->closeCursor();
$result = $this->connection->execute('SELECT * from things where id = 3');
$rows = $result->fetchAll('assoc');
$this->assertCount(1, $rows);
$result->closeCursor();
$this->assertEquals($data, $rows[0]);
}
/**
* Tests insertQuery
*/
public function testInsertQuery(): void
{
$data = ['id' => '3', 'title' => 'a title', 'body' => 'a body'];
$query = $this->connection->insertQuery(
'things',
$data,
['id' => 'integer', 'title' => 'string', 'body' => 'string']
);
$result = $query->execute();
$this->assertInstanceOf('Cake\Database\StatementInterface', $result);
$result->closeCursor();
$result = $this->connection->execute('SELECT * from things where id = 3');
$row = $result->fetch('assoc');
$result->closeCursor();
$this->assertEquals($data, $row);
}
/**
* Tests it is possible to insert data into a table using matching types by array position
*/
public function testInsertWithPositionalTypes(): void
{
$data = ['id' => '3', 'title' => 'a title', 'body' => 'a body'];
$result = $this->connection->insert(
'things',
$data,
['integer', 'string', 'string']
);
$result->closeCursor();
$this->assertInstanceOf(StatementInterface::class, $result);
$result = $this->connection->execute('SELECT * from things where id = 3');
$rows = $result->fetchAll('assoc');
$result->closeCursor();
$this->assertCount(1, $rows);
$this->assertEquals($data, $rows[0]);
}
/**
* Tests an statement class can be reused for multiple executions
*/
public function testStatementReusing(): void
{
$total = $this->connection->execute('SELECT COUNT(*) AS total FROM things');
$result = $total->fetch('assoc');
$this->assertEquals(2, $result['total']);
$total->closeCursor();
$total->execute();
$result = $total->fetch('assoc');
$this->assertEquals(2, $result['total']);
$total->closeCursor();
$result = $this->connection->execute('SELECT title, body FROM things');
$row = $result->fetch('assoc');
$this->assertSame('a title', $row['title']);
$this->assertSame('a body', $row['body']);
$row = $result->fetch('assoc');
$result->closeCursor();
$this->assertSame('another title', $row['title']);
$this->assertSame('another body', $row['body']);
$result->execute();
$row = $result->fetch('assoc');
$result->closeCursor();
$this->assertSame('a title', $row['title']);
}
/**
* Tests that it is possible to pass PDO constants to the underlying statement
* object for using alternate fetch types
*/
public function testStatementFetchObject(): void
{
$statement = $this->connection->execute('SELECT title, body FROM things');
$row = $statement->fetch(PDO::FETCH_OBJ);
$this->assertSame('a title', $row->title);
$this->assertSame('a body', $row->body);
$statement->closeCursor();
}
/**
* Tests rows can be updated without specifying any conditions nor types
*/
public function testUpdateWithoutConditionsNorTypes(): void
{
$title = 'changed the title!';
$body = 'changed the body!';
$this->connection->update('things', ['title' => $title, 'body' => $body]);
$result = $this->connection->execute('SELECT * FROM things WHERE title = ? AND body = ?', [$title, $body]);
$this->assertCount(2, $result->fetchAll());
$result->closeCursor();
}
/**
* Tests it is possible to use key => value conditions for update
*/
public function testUpdateWithConditionsNoTypes(): void
{
$title = 'changed the title!';
$body = 'changed the body!';
$this->connection->update('things', ['title' => $title, 'body' => $body], ['id' => 2]);
$result = $this->connection->execute('SELECT * FROM things WHERE title = ? AND body = ?', [$title, $body]);
$this->assertCount(1, $result->fetchAll());
$result->closeCursor();
}
/**
* Tests it is possible to use key => value and string conditions for update
*/
public function testUpdateWithConditionsCombinedNoTypes(): void
{
$title = 'changed the title!';
$body = 'changed the body!';
$this->connection->update('things', ['title' => $title, 'body' => $body], ['id' => 2, 'body is not null']);
$result = $this->connection->execute('SELECT * FROM things WHERE title = ? AND body = ?', [$title, $body]);
$this->assertCount(1, $result->fetchAll());
$result->closeCursor();
}
/**
* Tests you can bind types to update values
*/
public function testUpdateWithTypes(): void
{
$title = 'changed the title!';
$body = new DateTime('2012-01-01');
$values = compact('title', 'body');
$this->connection->update('things', $values, [], ['body' => 'date']);
$result = $this->connection->execute('SELECT * FROM things WHERE title = :title AND body = :body', $values, ['body' => 'date']);
$rows = $result->fetchAll('assoc');
$this->assertCount(2, $rows);
$this->assertSame('2012-01-01', $rows[0]['body']);
$this->assertSame('2012-01-01', $rows[1]['body']);
$result->closeCursor();
}
/**
* Tests you can bind types to update values
*/
public function testUpdateWithConditionsAndTypes(): void
{
$title = 'changed the title!';
$body = new DateTime('2012-01-01');
$values = compact('title', 'body');
$this->connection->update('things', $values, ['id' => '1'], ['body' => 'date', 'id' => 'integer']);
$result = $this->connection->execute('SELECT * FROM things WHERE title = :title AND body = :body', $values, ['body' => 'date']);
$rows = $result->fetchAll('assoc');
$this->assertCount(1, $rows);
$this->assertSame('2012-01-01', $rows[0]['body']);
$result->closeCursor();
}
/**
* Tests you can bind types to update values
*/
public function testUpdateQueryWithConditionsAndTypes(): void
{
$title = 'changed the title!';
$body = new DateTime('2012-01-01');
$values = compact('title', 'body');
$query = $this->connection->updateQuery('things', $values, ['id' => '1'], ['body' => 'date', 'id' => 'integer']);
$query->execute()->closeCursor();
$result = $this->connection->execute('SELECT * FROM things WHERE title = :title AND body = :body', $values, ['body' => 'date']);
$row = $result->fetch('assoc');
$this->assertSame('2012-01-01', $row['body']);
$result->closeCursor();
}
/**
* Tests delete from table with no conditions
*/
public function testDeleteNoConditions(): void
{
$this->connection->delete('things');
$result = $this->connection->execute('SELECT * FROM things');
$this->assertCount(0, $result->fetchAll());
$result->closeCursor();
}
/**
* Tests delete from table with conditions
*/
public function testDeleteWithConditions(): void
{
$this->connection->delete('things', ['id' => '1'], ['id' => 'integer']);
$result = $this->connection->execute('SELECT * FROM things');
$this->assertCount(1, $result->fetchAll());
$result->closeCursor();
$this->connection->delete('things', ['id' => '2'], ['id' => 'integer']);
$result = $this->connection->execute('SELECT * FROM things');
$this->assertCount(0, $result->fetchAll());
$result->closeCursor();
}
/**
* Tests delete from table with conditions
*/
public function testDeleteQuery(): void
{
$query = $this->connection->deleteQuery('things', ['id' => '1'], ['id' => 'integer']);
$query->execute()->closeCursor();
$result = $this->connection->execute('SELECT * FROM things');
$result->closeCursor();
$query = $this->connection->deleteQuery('things')->where(['id' => 2], ['id' => 'integer']);
$query->execute()->closeCursor();
$result = $this->connection->execute('SELECT * FROM things');
$this->assertCount(0, $result->fetchAll());
$result->closeCursor();
}
/**
* Test basic selectQuery behavior
*/
public function testSelectQuery(): void
{
$query = $this->connection->selectQuery(['*'], 'things');
$statement = $query->execute();
$row = $statement->fetchAssoc();
$statement->closeCursor();
$this->assertArrayHasKey('title', $row);
$this->assertArrayHasKey('body', $row);
}
/**
* Tests that it is possible to use simple database transactions
*/
public function testSimpleTransactions(): void
{
$this->connection->begin();
$this->assertTrue($this->connection->getDriver()->inTransaction());
$this->connection->delete('things', ['id' => 1]);
$this->connection->rollback();
$this->assertFalse($this->connection->getDriver()->inTransaction());
$result = $this->connection->execute('SELECT * FROM things');
$this->assertCount(2, $result->fetchAll());
$result->closeCursor();
$this->connection->begin();
$this->assertTrue($this->connection->getDriver()->inTransaction());
$this->connection->delete('things', ['id' => 1]);
$this->connection->commit();
$this->assertFalse($this->connection->getDriver()->inTransaction());
$result = $this->connection->execute('SELECT * FROM things');
$this->assertCount(1, $result->fetchAll());
}
/**
* Tests that the destructor of Connection generates a warning log
* when transaction is not closed
*/
public function testDestructorWithUncommittedTransaction(): void
{
$driver = $this->getMockFormDriver();
$connection = new Connection(['driver' => $driver]);
$connection->begin();
$this->assertTrue($connection->inTransaction());
$logger = $this->createMock('Psr\Log\AbstractLogger');
$logger->expects($this->once())
->method('log')
->with('warning', $this->stringContains('The connection is going to be closed'));
Log::setConfig('error', $logger);
// Destroy the connection
unset($connection);
}
/**
* Tests that it is possible to use virtualized nested transaction
* with early rollback algorithm
*/
public function testVirtualNestedTransaction(): void
{
//starting 3 virtual transaction
$this->connection->begin();
$this->connection->begin();
$this->connection->begin();
$this->assertTrue($this->connection->getDriver()->inTransaction());
$this->connection->delete('things', ['id' => 1]);
$result = $this->connection->execute('SELECT * FROM things');
$this->assertCount(1, $result->fetchAll());
$this->connection->commit();
$this->assertTrue($this->connection->getDriver()->inTransaction());
$this->connection->rollback();
$this->assertFalse($this->connection->getDriver()->inTransaction());
$result = $this->connection->execute('SELECT * FROM things');
$this->assertCount(2, $result->fetchAll());
}
/**
* Tests that it is possible to use virtualized nested transaction
* with early rollback algorithm
*/
public function testVirtualNestedTransaction2(): void
{
//starting 3 virtual transaction
$this->connection->begin();
$this->connection->begin();
$this->connection->begin();
$this->connection->delete('things', ['id' => 1]);
$result = $this->connection->execute('SELECT * FROM things');
$this->assertCount(1, $result->fetchAll());
$this->connection->rollback();
$result = $this->connection->execute('SELECT * FROM things');
$this->assertCount(2, $result->fetchAll());
}
/**
* Tests that it is possible to use virtualized nested transaction
* with early rollback algorithm
*/
public function testVirtualNestedTransaction3(): void
{
//starting 3 virtual transaction
$this->connection->begin();
$this->connection->begin();
$this->connection->begin();
$this->connection->delete('things', ['id' => 1]);
$result = $this->connection->execute('SELECT * FROM things');
$this->assertCount(1, $result->fetchAll());
$this->connection->commit();
$this->connection->commit();
$this->connection->commit();
$result = $this->connection->execute('SELECT * FROM things');
$this->assertCount(1, $result->fetchAll());
}
/**
* Tests that it is possible to real use nested transactions
*/
public function testSavePoints(): void
{
$this->connection->enableSavePoints(true);
$this->skipIf(!$this->connection->isSavePointsEnabled(), 'Database driver doesn\'t support save points');
$this->connection->begin();
$this->connection->delete('things', ['id' => 1]);
$result = $this->connection->execute('SELECT * FROM things');
$this->assertCount(1, $result->fetchAll());
$this->connection->begin();
$this->connection->delete('things', ['id' => 2]);
$result = $this->connection->execute('SELECT * FROM things');
$this->assertCount(0, $result->fetchAll());
$this->connection->rollback();
$result = $this->connection->execute('SELECT * FROM things');
$this->assertCount(1, $result->fetchAll());
$this->connection->rollback();
$result = $this->connection->execute('SELECT * FROM things');
$this->assertCount(2, $result->fetchAll());
}
/**
* Tests that it is possible to real use nested transactions
*/
public function testSavePoints2(): void
{
$this->connection->enableSavePoints(true);
$this->skipIf(!$this->connection->isSavePointsEnabled(), 'Database driver doesn\'t support save points');
$this->connection->begin();
$this->connection->delete('things', ['id' => 1]);
$result = $this->connection->execute('SELECT * FROM things');
$this->assertCount(1, $result->fetchAll());
$this->connection->begin();
$this->connection->delete('things', ['id' => 2]);
$result = $this->connection->execute('SELECT * FROM things');
$this->assertCount(0, $result->fetchAll());
$this->connection->rollback();
$result = $this->connection->execute('SELECT * FROM things');
$this->assertCount(1, $result->fetchAll());
$this->connection->commit();
$result = $this->connection->execute('SELECT * FROM things');
$this->assertCount(1, $result->fetchAll());
}
/**
* Tests inTransaction()
*/
public function testInTransaction(): void
{
$this->connection->begin();
$this->assertTrue($this->connection->inTransaction());
$this->connection->begin();
$this->assertTrue($this->connection->inTransaction());
$this->connection->commit();
$this->assertTrue($this->connection->inTransaction());
$this->connection->commit();
$this->assertFalse($this->connection->inTransaction());
$this->connection->begin();
$this->assertTrue($this->connection->inTransaction());
$this->connection->begin();
$this->connection->rollback();
$this->assertFalse($this->connection->inTransaction());
}
/**
* Tests inTransaction() with save points
*/
public function testInTransactionWithSavePoints(): void
{
$this->skipIf(
$this->connection->getDriver() instanceof Sqlserver,
'SQLServer fails when this test is included.'
);
$this->connection->enableSavePoints(true);
$this->skipIf(!$this->connection->isSavePointsEnabled(), 'Database driver doesn\'t support save points');
$this->connection->begin();
$this->assertTrue($this->connection->inTransaction());
$this->connection->begin();
$this->assertTrue($this->connection->inTransaction());
$this->connection->commit();
$this->assertTrue($this->connection->inTransaction());
$this->connection->commit();
$this->assertFalse($this->connection->inTransaction());
$this->connection->begin();
$this->assertTrue($this->connection->inTransaction());
$this->connection->begin();
$this->connection->rollback();
$this->assertTrue($this->connection->inTransaction());
$this->connection->rollback();
$this->assertFalse($this->connection->inTransaction());
}
/**
* Tests setting and getting the cacher object
*/
public function testGetAndSetCacher(): void
{
$cacher = new NullEngine();
$this->connection->setCacher($cacher);
$this->assertSame($cacher, $this->connection->getCacher());
}
/**
* Tests that the transactional method will start and commit a transaction
* around some arbitrary function passed as argument
*/
public function testTransactionalSuccess(): void
{
$driver = $this->getMockFormDriver();
$connection = $this->getMockBuilder(Connection::class)
->onlyMethods(['commit', 'begin'])
->setConstructorArgs([['driver' => $driver]])
->getMock();
$connection->expects($this->once())->method('begin');
$connection->expects($this->once())->method('commit');
$result = $connection->transactional(function ($conn) use ($connection) {
$this->assertSame($connection, $conn);
return 'thing';
});
$this->assertSame('thing', $result);
}
/**
* Tests that the transactional method will rollback the transaction if false
* is returned from the callback
*/
public function testTransactionalFail(): void
{
$driver = $this->getMockFormDriver();
$connection = $this->getMockBuilder(Connection::class)
->onlyMethods(['commit', 'begin', 'rollback'])
->setConstructorArgs([['driver' => $driver]])
->getMock();
$connection->expects($this->once())->method('begin');
$connection->expects($this->once())->method('rollback');
$connection->expects($this->never())->method('commit');
$result = $connection->transactional(function ($conn) use ($connection) {
$this->assertSame($connection, $conn);
return false;
});
$this->assertFalse($result);
}
/**
* Tests that the transactional method will rollback the transaction
* and throw the same exception if the callback raises one
*
* @throws \InvalidArgumentException
*/
public function testTransactionalWithException(): void
{
$this->expectException(InvalidArgumentException::class);
$driver = $this->getMockFormDriver();
$connection = $this->getMockBuilder(Connection::class)
->onlyMethods(['commit', 'begin', 'rollback'])
->setConstructorArgs([['driver' => $driver]])
->getMock();
$connection->expects($this->once())->method('begin');
$connection->expects($this->once())->method('rollback');
$connection->expects($this->never())->method('commit');
$connection->transactional(function ($conn) use ($connection): void {
$this->assertSame($connection, $conn);
throw new InvalidArgumentException();
});
}
/**
* Tests it is possible to set a schema collection object
*/
public function testSetSchemaCollection(): void
{
$driver = $this->getMockFormDriver();
$connection = new Connection(['driver' => $driver]);
$schema = $connection->getSchemaCollection();
$this->assertInstanceOf('Cake\Database\Schema\Collection', $schema);
$schema = $this->getMockBuilder('Cake\Database\Schema\Collection')
->setConstructorArgs([$connection])
->getMock();
$connection->setSchemaCollection($schema);
$this->assertSame($schema, $connection->getSchemaCollection());
}
/**
* Test CachedCollection creation with default and custom cache key prefix.
*/
public function testGetCachedCollection(): void
{
$driver = $this->getMockFormDriver();
$connection = new Connection([
'driver' => $driver,
'name' => 'default',
'cacheMetadata' => true,
]);
$schema = $connection->getSchemaCollection();
$this->assertInstanceOf(CachedCollection::class, $schema);
$this->assertSame('default_key', $schema->cacheKey('key'));
$driver = $this->getMockFormDriver();
$connection = new Connection([
'driver' => $driver,
'name' => 'default',
'cacheMetadata' => true,
'cacheKeyPrefix' => 'foo',
]);
$schema = $connection->getSchemaCollection();
$this->assertInstanceOf(CachedCollection::class, $schema);
$this->assertSame('foo_key', $schema->cacheKey('key'));
}
/**
* Tests that allowed nesting of commit/rollback operations doesn't
* throw any exceptions.
*/
public function testNestedTransactionRollbackExceptionNotThrown(): void
{
$this->connection->transactional(function () {
$this->connection->transactional(function () {
return true;
});
return true;
});
$this->assertFalse($this->connection->inTransaction());
$this->connection->transactional(function () {
$this->connection->transactional(function () {
return true;
});
return false;
});
$this->assertFalse($this->connection->inTransaction());
$this->connection->transactional(function () {
$this->connection->transactional(function () {
return false;
});
return false;
});
$this->assertFalse($this->connection->inTransaction());
}
/**
* Tests that not allowed nesting of commit/rollback operations throws
* a NestedTransactionRollbackException.
*/
public function testNestedTransactionRollbackExceptionThrown(): void
{
$this->rollbackSourceLine = -1;
$e = null;
try {
$this->connection->transactional(function () {
$this->connection->transactional(function () {
return false;
});
$this->rollbackSourceLine = __LINE__ - 1;
if (PHP_VERSION_ID >= 80200) {
$this->rollbackSourceLine -= 2;
}
return true;
});
$this->fail('NestedTransactionRollbackException should be thrown');
} catch (NestedTransactionRollbackException $e) {
}
$trace = $e->getTrace();
$this->assertEquals(__FILE__, $trace[1]['file']);
$this->assertEquals($this->rollbackSourceLine, $trace[1]['line']);