ConnectionTest.php 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 3.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Database;
  17. use Cake\Cache\Engine\NullEngine;
  18. use Cake\Collection\Collection;
  19. use Cake\Core\App;
  20. use Cake\Database\Connection;
  21. use Cake\Database\Driver;
  22. use Cake\Database\Driver\Mysql;
  23. use Cake\Database\Driver\Sqlite;
  24. use Cake\Database\Driver\Sqlserver;
  25. use Cake\Database\Exception\MissingConnectionException;
  26. use Cake\Database\Exception\MissingDriverException;
  27. use Cake\Database\Exception\MissingExtensionException;
  28. use Cake\Database\Exception\NestedTransactionRollbackException;
  29. use Cake\Database\Log\LoggingStatement;
  30. use Cake\Database\Log\QueryLogger;
  31. use Cake\Database\Schema\CachedCollection;
  32. use Cake\Database\StatementInterface;
  33. use Cake\Datasource\ConnectionManager;
  34. use Cake\Log\Log;
  35. use Cake\TestSuite\TestCase;
  36. use DateTime;
  37. use Error;
  38. use Exception;
  39. use InvalidArgumentException;
  40. use PDO;
  41. use ReflectionMethod;
  42. use ReflectionProperty;
  43. use TestApp\Log\Engine\TestBaseLog;
  44. /**
  45. * Tests Connection class
  46. */
  47. class ConnectionTest extends TestCase
  48. {
  49. /**
  50. * @var array<string>
  51. */
  52. protected $fixtures = ['core.Things'];
  53. /**
  54. * Where the NestedTransactionRollbackException was created.
  55. *
  56. * @var int
  57. */
  58. protected $rollbackSourceLine = -1;
  59. /**
  60. * Internal states of nested transaction.
  61. *
  62. * @var array
  63. */
  64. protected $nestedTransactionStates = [];
  65. /**
  66. * @var bool
  67. */
  68. protected $logState;
  69. /**
  70. * @var \Cake\Datasource\ConnectionInterface
  71. */
  72. protected $connection;
  73. /**
  74. * @var \Cake\Database\Log\QueryLogger
  75. */
  76. protected $defaultLogger;
  77. public function setUp(): void
  78. {
  79. parent::setUp();
  80. $this->connection = ConnectionManager::get('test');
  81. $this->defaultLogger = $this->connection->getLogger();
  82. $this->logState = $this->connection->isQueryLoggingEnabled();
  83. $this->connection->disableQueryLogging();
  84. static::setAppNamespace();
  85. }
  86. public function tearDown(): void
  87. {
  88. parent::tearDown();
  89. $this->connection->disableSavePoints();
  90. $this->connection->setLogger($this->defaultLogger);
  91. $this->connection->enableQueryLogging($this->logState);
  92. ConnectionManager::dropAlias('test:read');
  93. ConnectionManager::drop('test:read');
  94. Log::reset();
  95. unset($this->connection);
  96. }
  97. /**
  98. * Auxiliary method to build a mock for a driver so it can be injected into
  99. * the connection object
  100. *
  101. * @return \Cake\Database\Driver|\PHPUnit\Framework\MockObject\MockObject
  102. */
  103. public function getMockFormDriver()
  104. {
  105. $driver = $this->getMockBuilder(Driver::class)->getMock();
  106. $driver->expects($this->once())
  107. ->method('enabled')
  108. ->will($this->returnValue(true));
  109. return $driver;
  110. }
  111. /**
  112. * Tests connecting to database
  113. */
  114. public function testConnect(): void
  115. {
  116. $this->assertTrue($this->connection->connect());
  117. $this->assertTrue($this->connection->isConnected());
  118. }
  119. /**
  120. * Tests creating a connection using no driver throws an exception
  121. */
  122. public function testNoDriver(): void
  123. {
  124. $this->expectException(MissingDriverException::class);
  125. $this->expectExceptionMessage('Could not find driver `` for connection ``.');
  126. $connection = new Connection([]);
  127. }
  128. /**
  129. * Tests creating a connection using an invalid driver throws an exception
  130. */
  131. public function testEmptyDriver(): void
  132. {
  133. $this->expectException(Error::class);
  134. $connection = new Connection(['driver' => false]);
  135. }
  136. /**
  137. * Tests creating a connection using an invalid driver throws an exception
  138. */
  139. public function testMissingDriver(): void
  140. {
  141. $this->expectException(MissingDriverException::class);
  142. $this->expectExceptionMessage('Could not find driver `\Foo\InvalidDriver` for connection ``.');
  143. $connection = new Connection(['driver' => '\Foo\InvalidDriver']);
  144. }
  145. /**
  146. * Tests trying to use a disabled driver throws an exception
  147. */
  148. public function testDisabledDriver(): void
  149. {
  150. $this->expectException(MissingExtensionException::class);
  151. $this->expectExceptionMessage(
  152. 'Database driver DriverMock cannot be used due to a missing PHP extension or unmet dependency. ' .
  153. 'Requested by connection "custom_connection_name"'
  154. );
  155. $mock = $this->getMockBuilder(Mysql::class)
  156. ->onlyMethods(['enabled'])
  157. ->setMockClassName('DriverMock')
  158. ->getMock();
  159. $connection = new Connection(['driver' => $mock, 'name' => 'custom_connection_name']);
  160. }
  161. /**
  162. * Tests that the `driver` option supports the short classname/plugin syntax.
  163. */
  164. public function testDriverOptionClassNameSupport(): void
  165. {
  166. $connection = new Connection(['driver' => 'TestDriver']);
  167. $this->assertInstanceOf('TestApp\Database\Driver\TestDriver', $connection->getDriver());
  168. $connection = new Connection(['driver' => 'TestPlugin.TestDriver']);
  169. $this->assertInstanceOf('TestPlugin\Database\Driver\TestDriver', $connection->getDriver());
  170. [, $name] = namespaceSplit(get_class($this->connection->getDriver()));
  171. $connection = new Connection(['driver' => $name]);
  172. $this->assertInstanceOf(get_class($this->connection->getDriver()), $connection->getDriver());
  173. }
  174. /**
  175. * Tests that connecting with invalid credentials or database name throws an exception
  176. */
  177. public function testWrongCredentials(): void
  178. {
  179. $config = ConnectionManager::getConfig('test');
  180. $this->skipIf(isset($config['url']), 'Datasource has dsn, skipping.');
  181. $connection = new Connection(['database' => '/dev/nonexistent'] + ConnectionManager::getConfig('test'));
  182. $e = null;
  183. try {
  184. $connection->connect();
  185. } catch (MissingConnectionException $e) {
  186. }
  187. $this->assertNotNull($e);
  188. $this->assertStringStartsWith(
  189. sprintf(
  190. 'Connection to %s could not be established:',
  191. App::shortName(get_class($connection->getDriver()), 'Database/Driver')
  192. ),
  193. $e->getMessage()
  194. );
  195. $this->assertInstanceOf('PDOException', $e->getPrevious());
  196. }
  197. public function testConnectRetry(): void
  198. {
  199. $this->skipIf(!ConnectionManager::get('test')->getDriver() instanceof Sqlserver);
  200. $connection = new Connection(['driver' => 'RetryDriver']);
  201. $this->assertInstanceOf('TestApp\Database\Driver\RetryDriver', $connection->getDriver());
  202. try {
  203. $connection->connect();
  204. } catch (MissingConnectionException $e) {
  205. }
  206. $this->assertSame(4, $connection->getDriver()->getConnectRetries());
  207. }
  208. /**
  209. * Tests creation of prepared statements
  210. */
  211. public function testPrepare(): void
  212. {
  213. $sql = 'SELECT 1 + 1';
  214. $result = $this->connection->prepare($sql);
  215. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  216. $this->assertEquals($sql, $result->queryString);
  217. $query = $this->connection->newQuery()->select('1 + 1');
  218. $result = $this->connection->prepare($query);
  219. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  220. $sql = '#SELECT [`"\[]?1 \+ 1[`"\]]?#';
  221. $this->assertMatchesRegularExpression($sql, $result->queryString);
  222. }
  223. /**
  224. * Tests executing a simple query using bound values
  225. */
  226. public function testExecuteWithArguments(): void
  227. {
  228. $sql = 'SELECT 1 + ?';
  229. $statement = $this->connection->execute($sql, [1], ['integer']);
  230. $this->assertCount(1, $statement);
  231. $result = $statement->fetch();
  232. $this->assertEquals([2], $result);
  233. $statement->closeCursor();
  234. $sql = 'SELECT 1 + ? + ? AS total';
  235. $statement = $this->connection->execute($sql, [2, 3], ['integer', 'integer']);
  236. $this->assertCount(1, $statement);
  237. $result = $statement->fetch('assoc');
  238. $this->assertEquals(['total' => 6], $result);
  239. $statement->closeCursor();
  240. $sql = 'SELECT 1 + :one + :two AS total';
  241. $statement = $this->connection->execute($sql, ['one' => 2, 'two' => 3], ['one' => 'integer', 'two' => 'integer']);
  242. $this->assertCount(1, $statement);
  243. $result = $statement->fetch('assoc');
  244. $statement->closeCursor();
  245. $this->assertEquals(['total' => 6], $result);
  246. }
  247. /**
  248. * Tests executing a query with params and associated types
  249. */
  250. public function testExecuteWithArgumentsAndTypes(): void
  251. {
  252. $sql = "SELECT '2012-01-01' = ?";
  253. $statement = $this->connection->execute($sql, [new DateTime('2012-01-01')], ['date']);
  254. $result = $statement->fetch();
  255. $statement->closeCursor();
  256. $this->assertTrue((bool)$result[0]);
  257. }
  258. /**
  259. * test executing a buffered query interacts with Collection well.
  260. */
  261. public function testBufferedStatementCollectionWrappingStatement(): void
  262. {
  263. $this->skipIf(
  264. !($this->connection->getDriver() instanceof Sqlite),
  265. 'Only required for SQLite driver which does not support buffered results natively'
  266. );
  267. $statement = $this->connection->query('SELECT * FROM things LIMIT 3');
  268. $collection = new Collection($statement);
  269. $result = $collection->extract('id')->toArray();
  270. $this->assertEquals(['1', '2'], $result);
  271. // Check iteration after extraction
  272. $result = [];
  273. foreach ($collection as $v) {
  274. $result[] = $v['id'];
  275. }
  276. $this->assertEquals(['1', '2'], $result);
  277. }
  278. /**
  279. * Tests that passing a unknown value to a query throws an exception
  280. */
  281. public function testExecuteWithMissingType(): void
  282. {
  283. $this->expectException(InvalidArgumentException::class);
  284. $sql = 'SELECT ?';
  285. $statement = $this->connection->execute($sql, [new DateTime('2012-01-01')], ['bar']);
  286. }
  287. /**
  288. * Tests executing a query with no params also works
  289. */
  290. public function testExecuteWithNoParams(): void
  291. {
  292. $sql = 'SELECT 1';
  293. $statement = $this->connection->execute($sql);
  294. $result = $statement->fetch();
  295. $this->assertCount(1, $result);
  296. $this->assertEquals([1], $result);
  297. $statement->closeCursor();
  298. }
  299. /**
  300. * Tests it is possible to insert data into a table using matching types by key name
  301. */
  302. public function testInsertWithMatchingTypes(): void
  303. {
  304. $data = ['id' => '3', 'title' => 'a title', 'body' => 'a body'];
  305. $result = $this->connection->insert(
  306. 'things',
  307. $data,
  308. ['id' => 'integer', 'title' => 'string', 'body' => 'string']
  309. );
  310. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  311. $result->closeCursor();
  312. $result = $this->connection->execute('SELECT * from things where id = 3');
  313. $this->assertCount(1, $result);
  314. $row = $result->fetch('assoc');
  315. $result->closeCursor();
  316. $this->assertEquals($data, $row);
  317. }
  318. /**
  319. * Tests insertQuery
  320. */
  321. public function testInsertQuery(): void
  322. {
  323. $data = ['id' => '3', 'title' => 'a title', 'body' => 'a body'];
  324. $query = $this->connection->insertQuery(
  325. 'things',
  326. $data,
  327. ['id' => 'integer', 'title' => 'string', 'body' => 'string']
  328. );
  329. $result = $query->execute();
  330. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  331. $result->closeCursor();
  332. $result = $this->connection->execute('SELECT * from things where id = 3');
  333. $this->assertCount(1, $result);
  334. $row = $result->fetch('assoc');
  335. $result->closeCursor();
  336. $this->assertEquals($data, $row);
  337. }
  338. /**
  339. * Tests it is possible to insert data into a table using matching types by array position
  340. */
  341. public function testInsertWithPositionalTypes(): void
  342. {
  343. $data = ['id' => '3', 'title' => 'a title', 'body' => 'a body'];
  344. $result = $this->connection->insert(
  345. 'things',
  346. $data,
  347. ['integer', 'string', 'string']
  348. );
  349. $result->closeCursor();
  350. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  351. $result = $this->connection->execute('SELECT * from things where id = 3');
  352. $this->assertCount(1, $result);
  353. $row = $result->fetch('assoc');
  354. $result->closeCursor();
  355. $this->assertEquals($data, $row);
  356. }
  357. /**
  358. * Tests an statement class can be reused for multiple executions
  359. */
  360. public function testStatementReusing(): void
  361. {
  362. $total = $this->connection->execute('SELECT COUNT(*) AS total FROM things');
  363. $result = $total->fetch('assoc');
  364. $this->assertEquals(2, $result['total']);
  365. $total->closeCursor();
  366. $total->execute();
  367. $result = $total->fetch('assoc');
  368. $this->assertEquals(2, $result['total']);
  369. $total->closeCursor();
  370. $result = $this->connection->execute('SELECT title, body FROM things');
  371. $row = $result->fetch('assoc');
  372. $this->assertSame('a title', $row['title']);
  373. $this->assertSame('a body', $row['body']);
  374. $row = $result->fetch('assoc');
  375. $result->closeCursor();
  376. $this->assertSame('another title', $row['title']);
  377. $this->assertSame('another body', $row['body']);
  378. $result->execute();
  379. $row = $result->fetch('assoc');
  380. $result->closeCursor();
  381. $this->assertSame('a title', $row['title']);
  382. }
  383. /**
  384. * Tests that it is possible to pass PDO constants to the underlying statement
  385. * object for using alternate fetch types
  386. */
  387. public function testStatementFetchObject(): void
  388. {
  389. $statement = $this->connection->execute('SELECT title, body FROM things');
  390. $row = $statement->fetch(PDO::FETCH_OBJ);
  391. $this->assertSame('a title', $row->title);
  392. $this->assertSame('a body', $row->body);
  393. $statement->closeCursor();
  394. }
  395. /**
  396. * Tests rows can be updated without specifying any conditions nor types
  397. */
  398. public function testUpdateWithoutConditionsNorTypes(): void
  399. {
  400. $title = 'changed the title!';
  401. $body = 'changed the body!';
  402. $this->connection->update('things', ['title' => $title, 'body' => $body]);
  403. $result = $this->connection->execute('SELECT * FROM things WHERE title = ? AND body = ?', [$title, $body]);
  404. $this->assertCount(2, $result);
  405. $result->closeCursor();
  406. }
  407. /**
  408. * Tests it is possible to use key => value conditions for update
  409. */
  410. public function testUpdateWithConditionsNoTypes(): void
  411. {
  412. $title = 'changed the title!';
  413. $body = 'changed the body!';
  414. $this->connection->update('things', ['title' => $title, 'body' => $body], ['id' => 2]);
  415. $result = $this->connection->execute('SELECT * FROM things WHERE title = ? AND body = ?', [$title, $body]);
  416. $this->assertCount(1, $result);
  417. $result->closeCursor();
  418. }
  419. /**
  420. * Tests it is possible to use key => value and string conditions for update
  421. */
  422. public function testUpdateWithConditionsCombinedNoTypes(): void
  423. {
  424. $title = 'changed the title!';
  425. $body = 'changed the body!';
  426. $this->connection->update('things', ['title' => $title, 'body' => $body], ['id' => 2, 'body is not null']);
  427. $result = $this->connection->execute('SELECT * FROM things WHERE title = ? AND body = ?', [$title, $body]);
  428. $this->assertCount(1, $result);
  429. $result->closeCursor();
  430. }
  431. /**
  432. * Tests you can bind types to update values
  433. */
  434. public function testUpdateWithTypes(): void
  435. {
  436. $title = 'changed the title!';
  437. $body = new DateTime('2012-01-01');
  438. $values = compact('title', 'body');
  439. $this->connection->update('things', $values, [], ['body' => 'date']);
  440. $result = $this->connection->execute('SELECT * FROM things WHERE title = :title AND body = :body', $values, ['body' => 'date']);
  441. $this->assertCount(2, $result);
  442. $row = $result->fetch('assoc');
  443. $this->assertSame('2012-01-01', $row['body']);
  444. $row = $result->fetch('assoc');
  445. $this->assertSame('2012-01-01', $row['body']);
  446. $result->closeCursor();
  447. }
  448. /**
  449. * Tests you can bind types to update values
  450. */
  451. public function testUpdateWithConditionsAndTypes(): void
  452. {
  453. $title = 'changed the title!';
  454. $body = new DateTime('2012-01-01');
  455. $values = compact('title', 'body');
  456. $this->connection->update('things', $values, ['id' => '1'], ['body' => 'date', 'id' => 'integer']);
  457. $result = $this->connection->execute('SELECT * FROM things WHERE title = :title AND body = :body', $values, ['body' => 'date']);
  458. $this->assertCount(1, $result);
  459. $row = $result->fetch('assoc');
  460. $this->assertSame('2012-01-01', $row['body']);
  461. $result->closeCursor();
  462. }
  463. /**
  464. * Tests you can bind types to update values
  465. */
  466. public function testUpdateQueryWithConditionsAndTypes(): void
  467. {
  468. $title = 'changed the title!';
  469. $body = new DateTime('2012-01-01');
  470. $values = compact('title', 'body');
  471. $query = $this->connection->updateQuery('things', $values, ['id' => '1'], ['body' => 'date', 'id' => 'integer']);
  472. $query->execute()->closeCursor();
  473. $result = $this->connection->execute('SELECT * FROM things WHERE title = :title AND body = :body', $values, ['body' => 'date']);
  474. $this->assertCount(1, $result);
  475. $row = $result->fetch('assoc');
  476. $this->assertSame('2012-01-01', $row['body']);
  477. $result->closeCursor();
  478. }
  479. /**
  480. * Tests delete from table with no conditions
  481. */
  482. public function testDeleteNoConditions(): void
  483. {
  484. $this->connection->delete('things');
  485. $result = $this->connection->execute('SELECT * FROM things');
  486. $this->assertCount(0, $result);
  487. $result->closeCursor();
  488. }
  489. /**
  490. * Tests delete from table with conditions
  491. */
  492. public function testDeleteWithConditions(): void
  493. {
  494. $this->connection->delete('things', ['id' => '1'], ['id' => 'integer']);
  495. $result = $this->connection->execute('SELECT * FROM things');
  496. $this->assertCount(1, $result);
  497. $result->closeCursor();
  498. $this->connection->delete('things', ['id' => '2'], ['id' => 'integer']);
  499. $result = $this->connection->execute('SELECT * FROM things');
  500. $this->assertCount(0, $result);
  501. $result->closeCursor();
  502. }
  503. /**
  504. * Tests delete from table with conditions
  505. */
  506. public function testDeleteQuery(): void
  507. {
  508. $query = $this->connection->deleteQuery('things', ['id' => '1'], ['id' => 'integer']);
  509. $query->execute()->closeCursor();
  510. $result = $this->connection->execute('SELECT * FROM things');
  511. $this->assertCount(1, $result);
  512. $result->closeCursor();
  513. $query = $this->connection->deleteQuery('things')->where(['id' => 2], ['id' => 'integer']);
  514. $query->execute()->closeCursor();
  515. $result = $this->connection->execute('SELECT * FROM things');
  516. $this->assertCount(0, $result);
  517. $result->closeCursor();
  518. }
  519. /**
  520. * Tests that it is possible to use simple database transactions
  521. */
  522. public function testSimpleTransactions(): void
  523. {
  524. $this->connection->begin();
  525. $this->assertTrue($this->connection->getDriver()->inTransaction());
  526. $this->connection->delete('things', ['id' => 1]);
  527. $this->connection->rollback();
  528. $this->assertFalse($this->connection->getDriver()->inTransaction());
  529. $result = $this->connection->execute('SELECT * FROM things');
  530. $this->assertCount(2, $result);
  531. $result->closeCursor();
  532. $this->connection->begin();
  533. $this->assertTrue($this->connection->getDriver()->inTransaction());
  534. $this->connection->delete('things', ['id' => 1]);
  535. $this->connection->commit();
  536. $this->assertFalse($this->connection->getDriver()->inTransaction());
  537. $result = $this->connection->execute('SELECT * FROM things');
  538. $this->assertCount(1, $result);
  539. }
  540. /**
  541. * Tests that the destructor of Connection generates a warning log
  542. * when transaction is not closed
  543. */
  544. public function testDestructorWithUncommittedTransaction(): void
  545. {
  546. $driver = $this->getMockFormDriver();
  547. $connection = new Connection(['driver' => $driver]);
  548. $connection->begin();
  549. $this->assertTrue($connection->inTransaction());
  550. $logger = $this->createMock('Psr\Log\AbstractLogger');
  551. $logger->expects($this->once())
  552. ->method('log')
  553. ->with('warning', $this->stringContains('The connection is going to be closed'));
  554. Log::setConfig('error', $logger);
  555. // Destroy the connection
  556. unset($connection);
  557. }
  558. /**
  559. * Tests that it is possible to use virtualized nested transaction
  560. * with early rollback algorithm
  561. */
  562. public function testVirtualNestedTransaction(): void
  563. {
  564. //starting 3 virtual transaction
  565. $this->connection->begin();
  566. $this->connection->begin();
  567. $this->connection->begin();
  568. $this->assertTrue($this->connection->getDriver()->inTransaction());
  569. $this->connection->delete('things', ['id' => 1]);
  570. $result = $this->connection->execute('SELECT * FROM things');
  571. $this->assertCount(1, $result);
  572. $this->connection->commit();
  573. $this->assertTrue($this->connection->getDriver()->inTransaction());
  574. $this->connection->rollback();
  575. $this->assertFalse($this->connection->getDriver()->inTransaction());
  576. $result = $this->connection->execute('SELECT * FROM things');
  577. $this->assertCount(2, $result);
  578. }
  579. /**
  580. * Tests that it is possible to use virtualized nested transaction
  581. * with early rollback algorithm
  582. */
  583. public function testVirtualNestedTransaction2(): void
  584. {
  585. //starting 3 virtual transaction
  586. $this->connection->begin();
  587. $this->connection->begin();
  588. $this->connection->begin();
  589. $this->connection->delete('things', ['id' => 1]);
  590. $result = $this->connection->execute('SELECT * FROM things');
  591. $this->assertCount(1, $result);
  592. $this->connection->rollback();
  593. $result = $this->connection->execute('SELECT * FROM things');
  594. $this->assertCount(2, $result);
  595. }
  596. /**
  597. * Tests that it is possible to use virtualized nested transaction
  598. * with early rollback algorithm
  599. */
  600. public function testVirtualNestedTransaction3(): void
  601. {
  602. //starting 3 virtual transaction
  603. $this->connection->begin();
  604. $this->connection->begin();
  605. $this->connection->begin();
  606. $this->connection->delete('things', ['id' => 1]);
  607. $result = $this->connection->execute('SELECT * FROM things');
  608. $this->assertCount(1, $result);
  609. $this->connection->commit();
  610. $this->connection->commit();
  611. $this->connection->commit();
  612. $result = $this->connection->execute('SELECT * FROM things');
  613. $this->assertCount(1, $result);
  614. }
  615. /**
  616. * Tests that it is possible to real use nested transactions
  617. */
  618. public function testSavePoints(): void
  619. {
  620. $this->connection->enableSavePoints(true);
  621. $this->skipIf(!$this->connection->isSavePointsEnabled(), 'Database driver doesn\'t support save points');
  622. $this->connection->begin();
  623. $this->connection->delete('things', ['id' => 1]);
  624. $result = $this->connection->execute('SELECT * FROM things');
  625. $this->assertCount(1, $result);
  626. $this->connection->begin();
  627. $this->connection->delete('things', ['id' => 2]);
  628. $result = $this->connection->execute('SELECT * FROM things');
  629. $this->assertCount(0, $result);
  630. $this->connection->rollback();
  631. $result = $this->connection->execute('SELECT * FROM things');
  632. $this->assertCount(1, $result);
  633. $this->connection->rollback();
  634. $result = $this->connection->execute('SELECT * FROM things');
  635. $this->assertCount(2, $result);
  636. }
  637. /**
  638. * Tests that it is possible to real use nested transactions
  639. */
  640. public function testSavePoints2(): void
  641. {
  642. $this->connection->enableSavePoints(true);
  643. $this->skipIf(!$this->connection->isSavePointsEnabled(), 'Database driver doesn\'t support save points');
  644. $this->connection->begin();
  645. $this->connection->delete('things', ['id' => 1]);
  646. $result = $this->connection->execute('SELECT * FROM things');
  647. $this->assertCount(1, $result);
  648. $this->connection->begin();
  649. $this->connection->delete('things', ['id' => 2]);
  650. $result = $this->connection->execute('SELECT * FROM things');
  651. $this->assertCount(0, $result);
  652. $this->connection->rollback();
  653. $result = $this->connection->execute('SELECT * FROM things');
  654. $this->assertCount(1, $result);
  655. $this->connection->commit();
  656. $result = $this->connection->execute('SELECT * FROM things');
  657. $this->assertCount(1, $result);
  658. }
  659. /**
  660. * Tests inTransaction()
  661. */
  662. public function testInTransaction(): void
  663. {
  664. $this->connection->begin();
  665. $this->assertTrue($this->connection->inTransaction());
  666. $this->connection->begin();
  667. $this->assertTrue($this->connection->inTransaction());
  668. $this->connection->commit();
  669. $this->assertTrue($this->connection->inTransaction());
  670. $this->connection->commit();
  671. $this->assertFalse($this->connection->inTransaction());
  672. $this->connection->begin();
  673. $this->assertTrue($this->connection->inTransaction());
  674. $this->connection->begin();
  675. $this->connection->rollback();
  676. $this->assertFalse($this->connection->inTransaction());
  677. }
  678. /**
  679. * Tests inTransaction() with save points
  680. */
  681. public function testInTransactionWithSavePoints(): void
  682. {
  683. $this->skipIf(
  684. $this->connection->getDriver() instanceof Sqlserver,
  685. 'SQLServer fails when this test is included.'
  686. );
  687. $this->connection->enableSavePoints(true);
  688. $this->skipIf(!$this->connection->isSavePointsEnabled(), 'Database driver doesn\'t support save points');
  689. $this->connection->begin();
  690. $this->assertTrue($this->connection->inTransaction());
  691. $this->connection->begin();
  692. $this->assertTrue($this->connection->inTransaction());
  693. $this->connection->commit();
  694. $this->assertTrue($this->connection->inTransaction());
  695. $this->connection->commit();
  696. $this->assertFalse($this->connection->inTransaction());
  697. $this->connection->begin();
  698. $this->assertTrue($this->connection->inTransaction());
  699. $this->connection->begin();
  700. $this->connection->rollback();
  701. $this->assertTrue($this->connection->inTransaction());
  702. $this->connection->rollback();
  703. $this->assertFalse($this->connection->inTransaction());
  704. }
  705. /**
  706. * Tests connection can quote values to be safely used in query strings
  707. */
  708. public function testQuote(): void
  709. {
  710. $this->skipIf(!$this->connection->supportsQuoting());
  711. $expected = "'2012-01-01'";
  712. $result = $this->connection->quote(new DateTime('2012-01-01'), 'date');
  713. $this->assertEquals($expected, $result);
  714. $expected = "'1'";
  715. $result = $this->connection->quote(1, 'string');
  716. $this->assertEquals($expected, $result);
  717. $expected = "'hello'";
  718. $result = $this->connection->quote('hello', 'string');
  719. $this->assertEquals($expected, $result);
  720. }
  721. /**
  722. * Tests identifier quoting
  723. */
  724. public function testQuoteIdentifier(): void
  725. {
  726. $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlite')
  727. ->onlyMethods(['enabled'])
  728. ->getMock();
  729. $driver->expects($this->once())
  730. ->method('enabled')
  731. ->will($this->returnValue(true));
  732. $connection = new Connection(['driver' => $driver]);
  733. $result = $connection->quoteIdentifier('name');
  734. $expected = '"name"';
  735. $this->assertEquals($expected, $result);
  736. $result = $connection->quoteIdentifier('Model.*');
  737. $expected = '"Model".*';
  738. $this->assertEquals($expected, $result);
  739. $result = $connection->quoteIdentifier('Items.No_ 2');
  740. $expected = '"Items"."No_ 2"';
  741. $this->assertEquals($expected, $result);
  742. $result = $connection->quoteIdentifier('Items.No_ 2 thing');
  743. $expected = '"Items"."No_ 2 thing"';
  744. $this->assertEquals($expected, $result);
  745. $result = $connection->quoteIdentifier('Items.No_ 2 thing AS thing');
  746. $expected = '"Items"."No_ 2 thing" AS "thing"';
  747. $this->assertEquals($expected, $result);
  748. $result = $connection->quoteIdentifier('Items.Item Category Code = :c1');
  749. $expected = '"Items"."Item Category Code" = :c1';
  750. $this->assertEquals($expected, $result);
  751. $result = $connection->quoteIdentifier('MTD()');
  752. $expected = 'MTD()';
  753. $this->assertEquals($expected, $result);
  754. $result = $connection->quoteIdentifier('(sm)');
  755. $expected = '(sm)';
  756. $this->assertEquals($expected, $result);
  757. $result = $connection->quoteIdentifier('name AS x');
  758. $expected = '"name" AS "x"';
  759. $this->assertEquals($expected, $result);
  760. $result = $connection->quoteIdentifier('Model.name AS x');
  761. $expected = '"Model"."name" AS "x"';
  762. $this->assertEquals($expected, $result);
  763. $result = $connection->quoteIdentifier('Function(Something.foo)');
  764. $expected = 'Function("Something"."foo")';
  765. $this->assertEquals($expected, $result);
  766. $result = $connection->quoteIdentifier('Function(SubFunction(Something.foo))');
  767. $expected = 'Function(SubFunction("Something"."foo"))';
  768. $this->assertEquals($expected, $result);
  769. $result = $connection->quoteIdentifier('Function(Something.foo) AS x');
  770. $expected = 'Function("Something"."foo") AS "x"';
  771. $this->assertEquals($expected, $result);
  772. $result = $connection->quoteIdentifier('name-with-minus');
  773. $expected = '"name-with-minus"';
  774. $this->assertEquals($expected, $result);
  775. $result = $connection->quoteIdentifier('my-name');
  776. $expected = '"my-name"';
  777. $this->assertEquals($expected, $result);
  778. $result = $connection->quoteIdentifier('Foo-Model.*');
  779. $expected = '"Foo-Model".*';
  780. $this->assertEquals($expected, $result);
  781. $result = $connection->quoteIdentifier('Team.P%');
  782. $expected = '"Team"."P%"';
  783. $this->assertEquals($expected, $result);
  784. $result = $connection->quoteIdentifier('Team.G/G');
  785. $expected = '"Team"."G/G"';
  786. $this->assertEquals($expected, $result);
  787. $result = $connection->quoteIdentifier('Model.name as y');
  788. $expected = '"Model"."name" AS "y"';
  789. $this->assertEquals($expected, $result);
  790. $result = $connection->quoteIdentifier('nämé');
  791. $expected = '"nämé"';
  792. $this->assertEquals($expected, $result);
  793. $result = $connection->quoteIdentifier('aßa.nämé');
  794. $expected = '"aßa"."nämé"';
  795. $this->assertEquals($expected, $result);
  796. $result = $connection->quoteIdentifier('aßa.*');
  797. $expected = '"aßa".*';
  798. $this->assertEquals($expected, $result);
  799. $result = $connection->quoteIdentifier('Modeß.nämé as y');
  800. $expected = '"Modeß"."nämé" AS "y"';
  801. $this->assertEquals($expected, $result);
  802. $result = $connection->quoteIdentifier('Model.näme Datum as y');
  803. $expected = '"Model"."näme Datum" AS "y"';
  804. $this->assertEquals($expected, $result);
  805. }
  806. /**
  807. * Tests default return vale for logger() function
  808. */
  809. public function testGetLoggerDefault(): void
  810. {
  811. $logger = $this->connection->getLogger();
  812. $this->assertInstanceOf('Cake\Database\Log\QueryLogger', $logger);
  813. $this->assertSame($logger, $this->connection->getLogger());
  814. }
  815. /**
  816. * Tests setting and getting the logger object
  817. */
  818. public function testGetAndSetLogger(): void
  819. {
  820. $logger = new QueryLogger();
  821. $this->connection->setLogger($logger);
  822. $this->assertSame($logger, $this->connection->getLogger());
  823. }
  824. /**
  825. * Tests that statements are decorated with a logger when logQueries is set to true
  826. */
  827. public function testLoggerDecorator(): void
  828. {
  829. $logger = new QueryLogger();
  830. $this->connection->enableQueryLogging(true);
  831. $this->connection->setLogger($logger);
  832. $st = $this->connection->prepare('SELECT 1');
  833. $this->assertInstanceOf(LoggingStatement::class, $st);
  834. $this->assertSame($logger, $st->getLogger());
  835. $this->connection->enableQueryLogging(false);
  836. $st = $this->connection->prepare('SELECT 1');
  837. $this->assertNotInstanceOf('Cake\Database\Log\LoggingStatement', $st);
  838. }
  839. /**
  840. * test enableQueryLogging method
  841. */
  842. public function testEnableQueryLogging(): void
  843. {
  844. $this->connection->enableQueryLogging(true);
  845. $this->assertTrue($this->connection->isQueryLoggingEnabled());
  846. $this->connection->disableQueryLogging();
  847. $this->assertFalse($this->connection->isQueryLoggingEnabled());
  848. }
  849. /**
  850. * Tests that log() function logs to the configured query logger
  851. */
  852. public function testLogFunction(): void
  853. {
  854. Log::setConfig('queries', ['className' => 'Array']);
  855. $this->connection->enableQueryLogging();
  856. $this->connection->log('SELECT 1');
  857. $messages = Log::engine('queries')->read();
  858. $this->assertCount(1, $messages);
  859. $this->assertSame('debug: connection=test duration=0 rows=0 SELECT 1', $messages[0]);
  860. }
  861. /**
  862. * @see https://github.com/cakephp/cakephp/issues/14676
  863. */
  864. public function testLoggerDecoratorDoesNotPrematurelyFetchRecords(): void
  865. {
  866. Log::setConfig('queries', ['className' => 'Array']);
  867. $logger = new QueryLogger();
  868. $this->connection->enableQueryLogging(true);
  869. $this->connection->setLogger($logger);
  870. $st = $this->connection->execute('SELECT * FROM things');
  871. $this->assertInstanceOf(LoggingStatement::class, $st);
  872. $messages = Log::engine('queries')->read();
  873. $this->assertCount(0, $messages);
  874. $expected = [
  875. [1, 'a title', 'a body'],
  876. [2, 'another title', 'another body'],
  877. ];
  878. $results = $st->fetchAll();
  879. $this->assertEquals($expected, $results);
  880. $messages = Log::engine('queries')->read();
  881. $this->assertCount(1, $messages);
  882. $st = $this->connection->execute('SELECT * FROM things WHERE id = 0');
  883. $this->assertSame(0, $st->rowCount());
  884. $messages = Log::engine('queries')->read();
  885. $this->assertCount(2, $messages, 'Select queries without any matching rows should also be logged.');
  886. }
  887. /**
  888. * Tests that begin and rollback are also logged
  889. */
  890. public function testLogBeginRollbackTransaction(): void
  891. {
  892. Log::setConfig('queries', ['className' => 'Array']);
  893. $connection = $this
  894. ->getMockBuilder(Connection::class)
  895. ->onlyMethods(['connect'])
  896. ->disableOriginalConstructor()
  897. ->getMock();
  898. $connection->enableQueryLogging(true);
  899. $this->deprecated(function () use ($connection) {
  900. $driver = $this->getMockFormDriver();
  901. $connection->setDriver($driver);
  902. });
  903. $connection->begin();
  904. $connection->begin(); //This one will not be logged
  905. $connection->rollback();
  906. $messages = Log::engine('queries')->read();
  907. $this->assertCount(2, $messages);
  908. $this->assertSame('debug: connection= duration=0 rows=0 BEGIN', $messages[0]);
  909. $this->assertSame('debug: connection= duration=0 rows=0 ROLLBACK', $messages[1]);
  910. }
  911. /**
  912. * Tests that commits are logged
  913. */
  914. public function testLogCommitTransaction(): void
  915. {
  916. $driver = $this->getMockFormDriver();
  917. $connection = $this->getMockBuilder(Connection::class)
  918. ->onlyMethods(['connect'])
  919. ->setConstructorArgs([['driver' => $driver]])
  920. ->getMock();
  921. Log::setConfig('queries', ['className' => 'Array']);
  922. $connection->enableQueryLogging(true);
  923. $connection->begin();
  924. $connection->commit();
  925. $messages = Log::engine('queries')->read();
  926. $this->assertCount(2, $messages);
  927. $this->assertSame('debug: connection= duration=0 rows=0 BEGIN', $messages[0]);
  928. $this->assertSame('debug: connection= duration=0 rows=0 COMMIT', $messages[1]);
  929. }
  930. /**
  931. * Tests setting and getting the cacher object
  932. */
  933. public function testGetAndSetCacher(): void
  934. {
  935. $cacher = new NullEngine();
  936. $this->connection->setCacher($cacher);
  937. $this->assertSame($cacher, $this->connection->getCacher());
  938. }
  939. /**
  940. * Tests that the transactional method will start and commit a transaction
  941. * around some arbitrary function passed as argument
  942. */
  943. public function testTransactionalSuccess(): void
  944. {
  945. $driver = $this->getMockFormDriver();
  946. $connection = $this->getMockBuilder(Connection::class)
  947. ->onlyMethods(['connect', 'commit', 'begin'])
  948. ->setConstructorArgs([['driver' => $driver]])
  949. ->getMock();
  950. $connection->expects($this->once())->method('begin');
  951. $connection->expects($this->once())->method('commit');
  952. $result = $connection->transactional(function ($conn) use ($connection) {
  953. $this->assertSame($connection, $conn);
  954. return 'thing';
  955. });
  956. $this->assertSame('thing', $result);
  957. }
  958. /**
  959. * Tests that the transactional method will rollback the transaction if false
  960. * is returned from the callback
  961. */
  962. public function testTransactionalFail(): void
  963. {
  964. $driver = $this->getMockFormDriver();
  965. $connection = $this->getMockBuilder(Connection::class)
  966. ->onlyMethods(['connect', 'commit', 'begin', 'rollback'])
  967. ->setConstructorArgs([['driver' => $driver]])
  968. ->getMock();
  969. $connection->expects($this->once())->method('begin');
  970. $connection->expects($this->once())->method('rollback');
  971. $connection->expects($this->never())->method('commit');
  972. $result = $connection->transactional(function ($conn) use ($connection) {
  973. $this->assertSame($connection, $conn);
  974. return false;
  975. });
  976. $this->assertFalse($result);
  977. }
  978. /**
  979. * Tests that the transactional method will rollback the transaction
  980. * and throw the same exception if the callback raises one
  981. *
  982. * @throws \InvalidArgumentException
  983. */
  984. public function testTransactionalWithException(): void
  985. {
  986. $this->expectException(InvalidArgumentException::class);
  987. $driver = $this->getMockFormDriver();
  988. $connection = $this->getMockBuilder(Connection::class)
  989. ->onlyMethods(['connect', 'commit', 'begin', 'rollback'])
  990. ->setConstructorArgs([['driver' => $driver]])
  991. ->getMock();
  992. $connection->expects($this->once())->method('begin');
  993. $connection->expects($this->once())->method('rollback');
  994. $connection->expects($this->never())->method('commit');
  995. $connection->transactional(function ($conn) use ($connection): void {
  996. $this->assertSame($connection, $conn);
  997. throw new InvalidArgumentException();
  998. });
  999. }
  1000. /**
  1001. * Tests it is possible to set a schema collection object
  1002. */
  1003. public function testSetSchemaCollection(): void
  1004. {
  1005. $driver = $this->getMockFormDriver();
  1006. $connection = $this->getMockBuilder(Connection::class)
  1007. ->onlyMethods(['connect'])
  1008. ->setConstructorArgs([['driver' => $driver]])
  1009. ->getMock();
  1010. $schema = $connection->getSchemaCollection();
  1011. $this->assertInstanceOf('Cake\Database\Schema\Collection', $schema);
  1012. $schema = $this->getMockBuilder('Cake\Database\Schema\Collection')
  1013. ->setConstructorArgs([$connection])
  1014. ->getMock();
  1015. $connection->setSchemaCollection($schema);
  1016. $this->assertSame($schema, $connection->getSchemaCollection());
  1017. }
  1018. /**
  1019. * Test CachedCollection creation with default and custom cache key prefix.
  1020. */
  1021. public function testGetCachedCollection(): void
  1022. {
  1023. $driver = $this->getMockFormDriver();
  1024. $connection = $this->getMockBuilder(Connection::class)
  1025. ->onlyMethods(['connect'])
  1026. ->setConstructorArgs([[
  1027. 'driver' => $driver,
  1028. 'name' => 'default',
  1029. 'cacheMetadata' => true,
  1030. ]])
  1031. ->getMock();
  1032. $schema = $connection->getSchemaCollection();
  1033. $this->assertInstanceOf(CachedCollection::class, $schema);
  1034. $this->assertSame('default_key', $schema->cacheKey('key'));
  1035. $driver = $this->getMockFormDriver();
  1036. $connection = $this->getMockBuilder(Connection::class)
  1037. ->onlyMethods(['connect'])
  1038. ->setConstructorArgs([[
  1039. 'driver' => $driver,
  1040. 'name' => 'default',
  1041. 'cacheMetadata' => true,
  1042. 'cacheKeyPrefix' => 'foo',
  1043. ]])
  1044. ->getMock();
  1045. $schema = $connection->getSchemaCollection();
  1046. $this->assertInstanceOf(CachedCollection::class, $schema);
  1047. $this->assertSame('foo_key', $schema->cacheKey('key'));
  1048. }
  1049. /**
  1050. * Tests that allowed nesting of commit/rollback operations doesn't
  1051. * throw any exceptions.
  1052. */
  1053. public function testNestedTransactionRollbackExceptionNotThrown(): void
  1054. {
  1055. $this->connection->transactional(function () {
  1056. $this->connection->transactional(function () {
  1057. return true;
  1058. });
  1059. return true;
  1060. });
  1061. $this->assertFalse($this->connection->inTransaction());
  1062. $this->connection->transactional(function () {
  1063. $this->connection->transactional(function () {
  1064. return true;
  1065. });
  1066. return false;
  1067. });
  1068. $this->assertFalse($this->connection->inTransaction());
  1069. $this->connection->transactional(function () {
  1070. $this->connection->transactional(function () {
  1071. return false;
  1072. });
  1073. return false;
  1074. });
  1075. $this->assertFalse($this->connection->inTransaction());
  1076. }
  1077. /**
  1078. * Tests that not allowed nesting of commit/rollback operations throws
  1079. * a NestedTransactionRollbackException.
  1080. */
  1081. public function testNestedTransactionRollbackExceptionThrown(): void
  1082. {
  1083. $this->rollbackSourceLine = -1;
  1084. $e = null;
  1085. try {
  1086. $this->connection->transactional(function () {
  1087. $this->connection->transactional(function () {
  1088. return false;
  1089. });
  1090. $this->rollbackSourceLine = __LINE__ - 1;
  1091. if (PHP_VERSION_ID >= 80200) {
  1092. $this->rollbackSourceLine -= 2;
  1093. }
  1094. return true;
  1095. });
  1096. $this->fail('NestedTransactionRollbackException should be thrown');
  1097. } catch (NestedTransactionRollbackException $e) {
  1098. }
  1099. $trace = $e->getTrace();
  1100. $this->assertEquals(__FILE__, $trace[1]['file']);
  1101. $this->assertEquals($this->rollbackSourceLine, $trace[1]['line']);
  1102. }
  1103. /**
  1104. * Tests more detail about that not allowed nesting of rollback/commit
  1105. * operations throws a NestedTransactionRollbackException.
  1106. */
  1107. public function testNestedTransactionStates(): void
  1108. {
  1109. $this->rollbackSourceLine = -1;
  1110. $this->nestedTransactionStates = [];
  1111. $e = null;
  1112. try {
  1113. $this->connection->transactional(function () {
  1114. $this->pushNestedTransactionState();
  1115. $this->connection->transactional(function () {
  1116. return true;
  1117. });
  1118. $this->connection->transactional(function () {
  1119. $this->pushNestedTransactionState();
  1120. $this->connection->transactional(function () {
  1121. return false;
  1122. });
  1123. $this->rollbackSourceLine = __LINE__ - 1;
  1124. if (PHP_VERSION_ID >= 80200) {
  1125. $this->rollbackSourceLine -= 2;
  1126. }
  1127. $this->pushNestedTransactionState();
  1128. return true;
  1129. });
  1130. $this->connection->transactional(function () {
  1131. return false;
  1132. });
  1133. $this->pushNestedTransactionState();
  1134. return true;
  1135. });
  1136. $this->fail('NestedTransactionRollbackException should be thrown');
  1137. } catch (NestedTransactionRollbackException $e) {
  1138. }
  1139. $this->pushNestedTransactionState();
  1140. $this->assertSame([false, false, true, true, false], $this->nestedTransactionStates);
  1141. $this->assertFalse($this->connection->inTransaction());
  1142. $trace = $e->getTrace();
  1143. $this->assertEquals(__FILE__, $trace[1]['file']);
  1144. $this->assertEquals($this->rollbackSourceLine, $trace[1]['line']);
  1145. }
  1146. /**
  1147. * Helper method to trace nested transaction states.
  1148. */
  1149. public function pushNestedTransactionState(): void
  1150. {
  1151. $method = new ReflectionMethod($this->connection, 'wasNestedTransactionRolledback');
  1152. $method->setAccessible(true);
  1153. $this->nestedTransactionStates[] = $method->invoke($this->connection);
  1154. }
  1155. /**
  1156. * Tests that the connection is restablished whenever it is interrupted
  1157. * after having used the connection at least once.
  1158. */
  1159. public function testAutomaticReconnect(): void
  1160. {
  1161. $conn = clone $this->connection;
  1162. $statement = $conn->query('SELECT 1');
  1163. $statement->execute();
  1164. $statement->closeCursor();
  1165. $prop = new ReflectionProperty($conn, '_driver');
  1166. $prop->setAccessible(true);
  1167. $oldDriver = $prop->getValue($conn);
  1168. $newDriver = $this->getMockBuilder(Driver::class)->getMock();
  1169. $prop->setValue($conn, $newDriver);
  1170. $newDriver->expects($this->exactly(2))
  1171. ->method('prepare')
  1172. ->will($this->onConsecutiveCalls(
  1173. $this->throwException(new Exception('server gone away')),
  1174. $this->returnValue($statement)
  1175. ));
  1176. $res = $conn->query('SELECT 1');
  1177. $this->assertInstanceOf(StatementInterface::class, $res);
  1178. }
  1179. /**
  1180. * Tests that the connection is not restablished whenever it is interrupted
  1181. * inside a transaction.
  1182. */
  1183. public function testNoAutomaticReconnect(): void
  1184. {
  1185. $conn = clone $this->connection;
  1186. $statement = $conn->query('SELECT 1');
  1187. $statement->execute();
  1188. $statement->closeCursor();
  1189. $conn->begin();
  1190. $prop = new ReflectionProperty($conn, '_driver');
  1191. $prop->setAccessible(true);
  1192. $oldDriver = $prop->getValue($conn);
  1193. $newDriver = $this->getMockBuilder(Driver::class)->getMock();
  1194. $prop->setValue($conn, $newDriver);
  1195. $newDriver->expects($this->once())
  1196. ->method('prepare')
  1197. ->will($this->throwException(new Exception('server gone away')));
  1198. try {
  1199. $conn->query('SELECT 1');
  1200. } catch (Exception $e) {
  1201. }
  1202. $this->assertInstanceOf(Exception::class, $e ?? null);
  1203. $prop->setValue($conn, $oldDriver);
  1204. $conn->rollback();
  1205. }
  1206. public function testRoles(): void
  1207. {
  1208. $this->assertSame(Connection::ROLE_WRITE, $this->connection->role());
  1209. ConnectionManager::setConfig('test:read', ['url' => getenv('DB_URL')]);
  1210. $this->assertSame(Connection::ROLE_READ, ConnectionManager::get(ConnectionManager::getName(Connection::ROLE_READ, 'test'))->role());
  1211. // when read connection is only an alias, it should resolve as the write connection
  1212. ConnectionManager::alias('test', 'test:read');
  1213. $this->assertSame(Connection::ROLE_WRITE, ConnectionManager::get(ConnectionManager::getName(Connection::ROLE_READ, 'test'))->role());
  1214. }
  1215. public function testAutomaticReconnectWithoutQueryLogging(): void
  1216. {
  1217. $conn = clone $this->connection;
  1218. $logger = new TestBaseLog();
  1219. $conn->setLogger($logger);
  1220. $conn->disableQueryLogging();
  1221. $statement = $conn->query('SELECT 1');
  1222. $statement->execute();
  1223. $statement->closeCursor();
  1224. $prop = new ReflectionProperty($conn, '_driver');
  1225. $prop->setAccessible(true);
  1226. $newDriver = $this->getMockBuilder(Driver::class)->getMock();
  1227. $prop->setValue($conn, $newDriver);
  1228. $newDriver->expects($this->exactly(2))
  1229. ->method('prepare')
  1230. ->will($this->onConsecutiveCalls(
  1231. $this->throwException(new Exception('server gone away')),
  1232. $this->returnValue($statement)
  1233. ));
  1234. $conn->query('SELECT 1');
  1235. $this->assertEmpty($logger->getMessage());
  1236. }
  1237. public function testAutomaticReconnectWithQueryLogging(): void
  1238. {
  1239. $conn = clone $this->connection;
  1240. $logger = new TestBaseLog();
  1241. $conn->setLogger($logger);
  1242. $conn->enableQueryLogging();
  1243. $statement = $conn->query('SELECT 1');
  1244. $statement->execute();
  1245. $statement->closeCursor();
  1246. $prop = new ReflectionProperty($conn, '_driver');
  1247. $prop->setAccessible(true);
  1248. $newDriver = $this->getMockBuilder(Driver::class)->getMock();
  1249. $prop->setValue($conn, $newDriver);
  1250. $newDriver->expects($this->exactly(2))
  1251. ->method('prepare')
  1252. ->will($this->onConsecutiveCalls(
  1253. $this->throwException(new Exception('server gone away')),
  1254. $this->returnValue($statement)
  1255. ));
  1256. $conn->query('SELECT 1');
  1257. $this->assertSame('[RECONNECT]', $logger->getMessage());
  1258. }
  1259. }