ConnectionTest.php 46 KB

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