ConnectionTest.php 45 KB

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