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. * @return void
  450. */
  451. public function testDeleteWithConditions()
  452. {
  453. $this->connection->delete('things', ['id' => '1'], ['id' => 'integer']);
  454. $result = $this->connection->execute('SELECT * FROM things');
  455. $this->assertCount(1, $result);
  456. $result->closeCursor();
  457. $this->connection->delete('things', ['id' => '1'], ['id' => 'integer']);
  458. $result = $this->connection->execute('SELECT * FROM things');
  459. $this->assertCount(1, $result);
  460. $result->closeCursor();
  461. $this->connection->delete('things', ['id' => '2'], ['id' => 'integer']);
  462. $result = $this->connection->execute('SELECT * FROM things');
  463. $this->assertCount(0, $result);
  464. $result->closeCursor();
  465. }
  466. /**
  467. * Tests that it is possible to use simple database transactions
  468. *
  469. * @return void
  470. */
  471. public function testSimpleTransactions()
  472. {
  473. $this->connection->begin();
  474. $this->connection->delete('things', ['id' => 1]);
  475. $this->connection->rollback();
  476. $result = $this->connection->execute('SELECT * FROM things');
  477. $this->assertCount(2, $result);
  478. $result->closeCursor();
  479. $this->connection->begin();
  480. $this->connection->delete('things', ['id' => 1]);
  481. $this->connection->commit();
  482. $result = $this->connection->execute('SELECT * FROM things');
  483. $this->assertCount(1, $result);
  484. }
  485. /**
  486. * Tests that the destructor of Connection generates a warning log
  487. * when transaction is not closed
  488. *
  489. * @return void
  490. */
  491. public function testDestructorWithUncommittedTransaction()
  492. {
  493. $driver = $this->getMockFormDriver();
  494. $connection = new Connection(['driver' => $driver]);
  495. $connection->begin();
  496. $this->assertTrue($connection->inTransaction());
  497. $logger = $this->createMock('Psr\Log\AbstractLogger');
  498. $logger->expects($this->once())
  499. ->method('log')
  500. ->with('warning', $this->stringContains('The connection is going to be closed'));
  501. Log::setConfig('error', $logger);
  502. // Destroy the connection
  503. unset($connection);
  504. }
  505. /**
  506. * Tests that it is possible to use virtualized nested transaction
  507. * with early rollback algorithm
  508. *
  509. * @return void
  510. */
  511. public function testVirtualNestedTransaction()
  512. {
  513. //starting 3 virtual transaction
  514. $this->connection->begin();
  515. $this->connection->begin();
  516. $this->connection->begin();
  517. $this->connection->delete('things', ['id' => 1]);
  518. $result = $this->connection->execute('SELECT * FROM things');
  519. $this->assertCount(1, $result);
  520. $this->connection->commit();
  521. $this->connection->rollback();
  522. $result = $this->connection->execute('SELECT * FROM things');
  523. $this->assertCount(2, $result);
  524. }
  525. /**
  526. * Tests that it is possible to use virtualized nested transaction
  527. * with early rollback algorithm
  528. *
  529. * @return void
  530. */
  531. public function testVirtualNestedTransaction2()
  532. {
  533. //starting 3 virtual transaction
  534. $this->connection->begin();
  535. $this->connection->begin();
  536. $this->connection->begin();
  537. $this->connection->delete('things', ['id' => 1]);
  538. $result = $this->connection->execute('SELECT * FROM things');
  539. $this->assertCount(1, $result);
  540. $this->connection->rollback();
  541. $result = $this->connection->execute('SELECT * FROM things');
  542. $this->assertCount(2, $result);
  543. }
  544. /**
  545. * Tests that it is possible to use virtualized nested transaction
  546. * with early rollback algorithm
  547. *
  548. * @return void
  549. */
  550. public function testVirtualNestedTransaction3()
  551. {
  552. //starting 3 virtual transaction
  553. $this->connection->begin();
  554. $this->connection->begin();
  555. $this->connection->begin();
  556. $this->connection->delete('things', ['id' => 1]);
  557. $result = $this->connection->execute('SELECT * FROM things');
  558. $this->assertCount(1, $result);
  559. $this->connection->commit();
  560. $this->connection->commit();
  561. $this->connection->commit();
  562. $result = $this->connection->execute('SELECT * FROM things');
  563. $this->assertCount(1, $result);
  564. }
  565. /**
  566. * Tests that it is possible to real use nested transactions
  567. *
  568. * @return void
  569. */
  570. public function testSavePoints()
  571. {
  572. $this->skipIf(!$this->connection->enableSavePoints(true));
  573. $this->connection->begin();
  574. $this->connection->delete('things', ['id' => 1]);
  575. $result = $this->connection->execute('SELECT * FROM things');
  576. $this->assertCount(1, $result);
  577. $this->connection->begin();
  578. $this->connection->delete('things', ['id' => 2]);
  579. $result = $this->connection->execute('SELECT * FROM things');
  580. $this->assertCount(0, $result);
  581. $this->connection->rollback();
  582. $result = $this->connection->execute('SELECT * FROM things');
  583. $this->assertCount(1, $result);
  584. $this->connection->rollback();
  585. $result = $this->connection->execute('SELECT * FROM things');
  586. $this->assertCount(2, $result);
  587. }
  588. /**
  589. * Tests that it is possible to real use nested transactions
  590. *
  591. * @return void
  592. */
  593. public function testSavePoints2()
  594. {
  595. $this->skipIf(!$this->connection->enableSavePoints(true));
  596. $this->connection->begin();
  597. $this->connection->delete('things', ['id' => 1]);
  598. $result = $this->connection->execute('SELECT * FROM things');
  599. $this->assertCount(1, $result);
  600. $this->connection->begin();
  601. $this->connection->delete('things', ['id' => 2]);
  602. $result = $this->connection->execute('SELECT * FROM things');
  603. $this->assertCount(0, $result);
  604. $this->connection->rollback();
  605. $result = $this->connection->execute('SELECT * FROM things');
  606. $this->assertCount(1, $result);
  607. $this->connection->commit();
  608. $result = $this->connection->execute('SELECT * FROM things');
  609. $this->assertCount(1, $result);
  610. }
  611. /**
  612. * Tests inTransaction()
  613. *
  614. * @return void
  615. */
  616. public function testInTransaction()
  617. {
  618. $this->connection->begin();
  619. $this->assertTrue($this->connection->inTransaction());
  620. $this->connection->begin();
  621. $this->assertTrue($this->connection->inTransaction());
  622. $this->connection->commit();
  623. $this->assertTrue($this->connection->inTransaction());
  624. $this->connection->commit();
  625. $this->assertFalse($this->connection->inTransaction());
  626. $this->connection->begin();
  627. $this->assertTrue($this->connection->inTransaction());
  628. $this->connection->begin();
  629. $this->connection->rollback();
  630. $this->assertFalse($this->connection->inTransaction());
  631. }
  632. /**
  633. * Tests inTransaction() with save points
  634. *
  635. * @return void
  636. */
  637. public function testInTransactionWithSavePoints()
  638. {
  639. $this->skipIf(
  640. $this->connection->getDriver() instanceof \Cake\Database\Driver\Sqlserver,
  641. 'SQLServer fails when this test is included.'
  642. );
  643. $this->skipIf(!$this->connection->enableSavePoints(true));
  644. $this->connection->begin();
  645. $this->assertTrue($this->connection->inTransaction());
  646. $this->connection->begin();
  647. $this->assertTrue($this->connection->inTransaction());
  648. $this->connection->commit();
  649. $this->assertTrue($this->connection->inTransaction());
  650. $this->connection->commit();
  651. $this->assertFalse($this->connection->inTransaction());
  652. $this->connection->begin();
  653. $this->assertTrue($this->connection->inTransaction());
  654. $this->connection->begin();
  655. $this->connection->rollback();
  656. $this->assertTrue($this->connection->inTransaction());
  657. $this->connection->rollback();
  658. $this->assertFalse($this->connection->inTransaction());
  659. }
  660. /**
  661. * Tests connection can quote values to be safely used in query strings
  662. *
  663. * @return void
  664. */
  665. public function testQuote()
  666. {
  667. $this->skipIf(!$this->connection->supportsQuoting());
  668. $expected = "'2012-01-01'";
  669. $result = $this->connection->quote(new \DateTime('2012-01-01'), 'date');
  670. $this->assertEquals($expected, $result);
  671. $expected = "'1'";
  672. $result = $this->connection->quote(1, 'string');
  673. $this->assertEquals($expected, $result);
  674. $expected = "'hello'";
  675. $result = $this->connection->quote('hello', 'string');
  676. $this->assertEquals($expected, $result);
  677. }
  678. /**
  679. * Tests identifier quoting
  680. *
  681. * @return void
  682. */
  683. public function testQuoteIdentifier()
  684. {
  685. $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlite')
  686. ->setMethods(['enabled'])
  687. ->getMock();
  688. $driver->expects($this->once())
  689. ->method('enabled')
  690. ->will($this->returnValue(true));
  691. $connection = new Connection(['driver' => $driver]);
  692. $result = $connection->quoteIdentifier('name');
  693. $expected = '"name"';
  694. $this->assertEquals($expected, $result);
  695. $result = $connection->quoteIdentifier('Model.*');
  696. $expected = '"Model".*';
  697. $this->assertEquals($expected, $result);
  698. $result = $connection->quoteIdentifier('Items.No_ 2');
  699. $expected = '"Items"."No_ 2"';
  700. $this->assertEquals($expected, $result);
  701. $result = $connection->quoteIdentifier('Items.No_ 2 thing');
  702. $expected = '"Items"."No_ 2 thing"';
  703. $this->assertEquals($expected, $result);
  704. $result = $connection->quoteIdentifier('Items.No_ 2 thing AS thing');
  705. $expected = '"Items"."No_ 2 thing" AS "thing"';
  706. $this->assertEquals($expected, $result);
  707. $result = $connection->quoteIdentifier('Items.Item Category Code = :c1');
  708. $expected = '"Items"."Item Category Code" = :c1';
  709. $this->assertEquals($expected, $result);
  710. $result = $connection->quoteIdentifier('MTD()');
  711. $expected = 'MTD()';
  712. $this->assertEquals($expected, $result);
  713. $result = $connection->quoteIdentifier('(sm)');
  714. $expected = '(sm)';
  715. $this->assertEquals($expected, $result);
  716. $result = $connection->quoteIdentifier('name AS x');
  717. $expected = '"name" AS "x"';
  718. $this->assertEquals($expected, $result);
  719. $result = $connection->quoteIdentifier('Model.name AS x');
  720. $expected = '"Model"."name" AS "x"';
  721. $this->assertEquals($expected, $result);
  722. $result = $connection->quoteIdentifier('Function(Something.foo)');
  723. $expected = 'Function("Something"."foo")';
  724. $this->assertEquals($expected, $result);
  725. $result = $connection->quoteIdentifier('Function(SubFunction(Something.foo))');
  726. $expected = 'Function(SubFunction("Something"."foo"))';
  727. $this->assertEquals($expected, $result);
  728. $result = $connection->quoteIdentifier('Function(Something.foo) AS x');
  729. $expected = 'Function("Something"."foo") AS "x"';
  730. $this->assertEquals($expected, $result);
  731. $result = $connection->quoteIdentifier('name-with-minus');
  732. $expected = '"name-with-minus"';
  733. $this->assertEquals($expected, $result);
  734. $result = $connection->quoteIdentifier('my-name');
  735. $expected = '"my-name"';
  736. $this->assertEquals($expected, $result);
  737. $result = $connection->quoteIdentifier('Foo-Model.*');
  738. $expected = '"Foo-Model".*';
  739. $this->assertEquals($expected, $result);
  740. $result = $connection->quoteIdentifier('Team.P%');
  741. $expected = '"Team"."P%"';
  742. $this->assertEquals($expected, $result);
  743. $result = $connection->quoteIdentifier('Team.G/G');
  744. $expected = '"Team"."G/G"';
  745. $this->assertEquals($expected, $result);
  746. $result = $connection->quoteIdentifier('Model.name as y');
  747. $expected = '"Model"."name" AS "y"';
  748. $this->assertEquals($expected, $result);
  749. $result = $connection->quoteIdentifier('nämé');
  750. $expected = '"nämé"';
  751. $this->assertEquals($expected, $result);
  752. $result = $connection->quoteIdentifier('aßa.nämé');
  753. $expected = '"aßa"."nämé"';
  754. $this->assertEquals($expected, $result);
  755. $result = $connection->quoteIdentifier('aßa.*');
  756. $expected = '"aßa".*';
  757. $this->assertEquals($expected, $result);
  758. $result = $connection->quoteIdentifier('Modeß.nämé as y');
  759. $expected = '"Modeß"."nämé" AS "y"';
  760. $this->assertEquals($expected, $result);
  761. $result = $connection->quoteIdentifier('Model.näme Datum as y');
  762. $expected = '"Model"."näme Datum" AS "y"';
  763. $this->assertEquals($expected, $result);
  764. }
  765. /**
  766. * Tests default return vale for logger() function
  767. *
  768. * @return void
  769. */
  770. public function testGetLoggerDefault()
  771. {
  772. $logger = $this->connection->getLogger();
  773. $this->assertInstanceOf('Cake\Database\Log\QueryLogger', $logger);
  774. $this->assertSame($logger, $this->connection->getLogger());
  775. }
  776. /**
  777. * Tests that a custom logger object can be set
  778. *
  779. * @group deprecated
  780. * @return void
  781. */
  782. public function testSetLogger()
  783. {
  784. $this->deprecated(function () {
  785. $logger = new QueryLogger;
  786. $this->connection->logger($logger);
  787. $this->assertSame($logger, $this->connection->logger());
  788. });
  789. }
  790. /**
  791. * Tests setting and getting the logger object
  792. *
  793. * @return void
  794. */
  795. public function testGetAndSetLogger()
  796. {
  797. $logger = new QueryLogger();
  798. $this->connection->setLogger($logger);
  799. $this->assertSame($logger, $this->connection->getLogger());
  800. }
  801. /**
  802. * Tests that statements are decorated with a logger when logQueries is set to true
  803. *
  804. * @return void
  805. */
  806. public function testLoggerDecorator()
  807. {
  808. $logger = new QueryLogger;
  809. $this->connection->enableQueryLogging(true);
  810. $this->connection->setLogger($logger);
  811. $st = $this->connection->prepare('SELECT 1');
  812. $this->assertInstanceOf(LoggingStatement::class, $st);
  813. $this->assertSame($logger, $st->getLogger());
  814. $this->connection->enableQueryLogging(false);
  815. $st = $this->connection->prepare('SELECT 1');
  816. $this->assertNotInstanceOf('\Cake\Database\Log\LoggingStatement', $st);
  817. }
  818. /**
  819. * test logQueries method
  820. *
  821. * @deprecated
  822. * @return void
  823. */
  824. public function testLogQueries()
  825. {
  826. $this->deprecated(function () {
  827. $this->connection->logQueries(true);
  828. $this->assertTrue($this->connection->logQueries());
  829. $this->connection->logQueries(false);
  830. $this->assertFalse($this->connection->logQueries());
  831. });
  832. }
  833. /**
  834. * test enableQueryLogging method
  835. *
  836. * @return void
  837. */
  838. public function testEnableQueryLogging()
  839. {
  840. $this->connection->enableQueryLogging(true);
  841. $this->assertTrue($this->connection->isQueryLoggingEnabled());
  842. $this->connection->disableQueryLogging();
  843. $this->assertFalse($this->connection->isQueryLoggingEnabled());
  844. }
  845. /**
  846. * Tests that log() function logs to the configured query logger
  847. *
  848. * @return void
  849. */
  850. public function testLogFunction()
  851. {
  852. $logger = $this->getMockBuilder(QueryLogger::class)->getMock();
  853. $this->connection->setLogger($logger);
  854. $logger->expects($this->once())->method('log')
  855. ->with($this->logicalAnd(
  856. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  857. $this->attributeEqualTo('query', 'SELECT 1')
  858. ));
  859. $this->connection->log('SELECT 1');
  860. }
  861. /**
  862. * Tests that begin and rollback are also logged
  863. *
  864. * @return void
  865. */
  866. public function testLogBeginRollbackTransaction()
  867. {
  868. $connection = $this
  869. ->getMockBuilder(Connection::class)
  870. ->setMethods(['connect'])
  871. ->disableOriginalConstructor()
  872. ->getMock();
  873. $connection->enableQueryLogging(true);
  874. $driver = $this->getMockFormDriver();
  875. $connection->setDriver($driver);
  876. $logger = $this->getMockBuilder(QueryLogger::class)->getMock();
  877. $connection->setLogger($logger);
  878. $logger->expects($this->at(0))->method('log')
  879. ->with($this->logicalAnd(
  880. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  881. $this->attributeEqualTo('query', 'BEGIN')
  882. ));
  883. $logger->expects($this->at(1))->method('log')
  884. ->with($this->logicalAnd(
  885. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  886. $this->attributeEqualTo('query', 'ROLLBACK')
  887. ));
  888. $connection->begin();
  889. $connection->begin(); //This one will not be logged
  890. $connection->rollback();
  891. }
  892. /**
  893. * Tests that commits are logged
  894. *
  895. * @return void
  896. */
  897. public function testLogCommitTransaction()
  898. {
  899. $driver = $this->getMockFormDriver();
  900. $connection = $this->getMockBuilder(Connection::class)
  901. ->setMethods(['connect'])
  902. ->setConstructorArgs([['driver' => $driver]])
  903. ->getMock();
  904. $logger = $this->getMockBuilder(QueryLogger::class)->getMock();
  905. $connection->setLogger($logger);
  906. $logger->expects($this->at(1))->method('log')
  907. ->with($this->logicalAnd(
  908. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  909. $this->attributeEqualTo('query', 'COMMIT')
  910. ));
  911. $connection->enableQueryLogging(true);
  912. $connection->begin();
  913. $connection->commit();
  914. }
  915. /**
  916. * Tests that the transactional method will start and commit a transaction
  917. * around some arbitrary function passed as argument
  918. *
  919. * @return void
  920. */
  921. public function testTransactionalSuccess()
  922. {
  923. $driver = $this->getMockFormDriver();
  924. $connection = $this->getMockBuilder(Connection::class)
  925. ->setMethods(['connect', 'commit', 'begin'])
  926. ->setConstructorArgs([['driver' => $driver]])
  927. ->getMock();
  928. $connection->expects($this->at(0))->method('begin');
  929. $connection->expects($this->at(1))->method('commit');
  930. $result = $connection->transactional(function ($conn) use ($connection) {
  931. $this->assertSame($connection, $conn);
  932. return 'thing';
  933. });
  934. $this->assertEquals('thing', $result);
  935. }
  936. /**
  937. * Tests that the transactional method will rollback the transaction if false
  938. * is returned from the callback
  939. *
  940. * @return void
  941. */
  942. public function testTransactionalFail()
  943. {
  944. $driver = $this->getMockFormDriver();
  945. $connection = $this->getMockBuilder(Connection::class)
  946. ->setMethods(['connect', 'commit', 'begin', 'rollback'])
  947. ->setConstructorArgs([['driver' => $driver]])
  948. ->getMock();
  949. $connection->expects($this->at(0))->method('begin');
  950. $connection->expects($this->at(1))->method('rollback');
  951. $connection->expects($this->never())->method('commit');
  952. $result = $connection->transactional(function ($conn) use ($connection) {
  953. $this->assertSame($connection, $conn);
  954. return false;
  955. });
  956. $this->assertFalse($result);
  957. }
  958. /**
  959. * Tests that the transactional method will rollback the transaction
  960. * and throw the same exception if the callback raises one
  961. *
  962. * @return void
  963. * @throws \InvalidArgumentException
  964. */
  965. public function testTransactionalWithException()
  966. {
  967. $this->expectException(\InvalidArgumentException::class);
  968. $driver = $this->getMockFormDriver();
  969. $connection = $this->getMockBuilder(Connection::class)
  970. ->setMethods(['connect', 'commit', 'begin', 'rollback'])
  971. ->setConstructorArgs([['driver' => $driver]])
  972. ->getMock();
  973. $connection->expects($this->at(0))->method('begin');
  974. $connection->expects($this->at(1))->method('rollback');
  975. $connection->expects($this->never())->method('commit');
  976. $connection->transactional(function ($conn) use ($connection) {
  977. $this->assertSame($connection, $conn);
  978. throw new \InvalidArgumentException;
  979. });
  980. }
  981. /**
  982. * Tests it is possible to set a schema collection object
  983. *
  984. * @return void
  985. */
  986. public function testSetSchemaCollection()
  987. {
  988. $driver = $this->getMockFormDriver();
  989. $connection = $this->getMockBuilder(Connection::class)
  990. ->setMethods(['connect'])
  991. ->setConstructorArgs([['driver' => $driver]])
  992. ->getMock();
  993. $schema = $connection->getSchemaCollection();
  994. $this->assertInstanceOf('Cake\Database\Schema\Collection', $schema);
  995. $schema = $this->getMockBuilder('Cake\Database\Schema\Collection')
  996. ->setConstructorArgs([$connection])
  997. ->getMock();
  998. $connection->setSchemaCollection($schema);
  999. $this->assertSame($schema, $connection->getSchemaCollection());
  1000. }
  1001. /**
  1002. * Tests it is possible to set a schema collection object
  1003. *
  1004. * @group deprecated
  1005. * @return void
  1006. */
  1007. public function testSchemaCollection()
  1008. {
  1009. $this->deprecated(function () {
  1010. $driver = $this->getMockFormDriver();
  1011. $connection = $this->getMockBuilder(Connection::class)
  1012. ->setMethods(['connect'])
  1013. ->setConstructorArgs([['driver' => $driver]])
  1014. ->getMock();
  1015. $schema = $connection->schemaCollection();
  1016. $this->assertInstanceOf('Cake\Database\Schema\Collection', $schema);
  1017. $schema = $this->getMockBuilder('Cake\Database\Schema\Collection')
  1018. ->setConstructorArgs([$connection])
  1019. ->getMock();
  1020. $connection->schemaCollection($schema);
  1021. $this->assertSame($schema, $connection->schemaCollection());
  1022. });
  1023. }
  1024. /**
  1025. * Test CachedCollection creation with default and custom cache key prefix.
  1026. *
  1027. * @return void
  1028. */
  1029. public function testGetCachedCollection()
  1030. {
  1031. $driver = $this->getMockFormDriver();
  1032. $connection = $this->getMockBuilder(Connection::class)
  1033. ->setMethods(['connect'])
  1034. ->setConstructorArgs([[
  1035. 'driver' => $driver,
  1036. 'name' => 'default',
  1037. 'cacheMetadata' => true,
  1038. ]])
  1039. ->getMock();
  1040. $schema = $connection->getSchemaCollection();
  1041. $this->assertInstanceOf(CachedCollection::class, $schema);
  1042. $this->assertSame('default_key', $schema->cacheKey('key'));
  1043. $driver = $this->getMockFormDriver();
  1044. $connection = $this->getMockBuilder(Connection::class)
  1045. ->setMethods(['connect'])
  1046. ->setConstructorArgs([[
  1047. 'driver' => $driver,
  1048. 'name' => 'default',
  1049. 'cacheMetadata' => true,
  1050. 'cacheKeyPrefix' => 'foo',
  1051. ]])
  1052. ->getMock();
  1053. $schema = $connection->getSchemaCollection();
  1054. $this->assertInstanceOf(CachedCollection::class, $schema);
  1055. $this->assertSame('foo_key', $schema->cacheKey('key'));
  1056. }
  1057. /**
  1058. * Tests that allowed nesting of commit/rollback operations doesn't
  1059. * throw any exceptions.
  1060. *
  1061. * @return void
  1062. */
  1063. public function testNestedTransactionRollbackExceptionNotThrown()
  1064. {
  1065. $this->connection->transactional(function () {
  1066. $this->connection->transactional(function () {
  1067. return true;
  1068. });
  1069. return true;
  1070. });
  1071. $this->assertFalse($this->connection->inTransaction());
  1072. $this->connection->transactional(function () {
  1073. $this->connection->transactional(function () {
  1074. return true;
  1075. });
  1076. return false;
  1077. });
  1078. $this->assertFalse($this->connection->inTransaction());
  1079. $this->connection->transactional(function () {
  1080. $this->connection->transactional(function () {
  1081. return false;
  1082. });
  1083. return false;
  1084. });
  1085. $this->assertFalse($this->connection->inTransaction());
  1086. }
  1087. /**
  1088. * Tests that not allowed nesting of commit/rollback operations throws
  1089. * a NestedTransactionRollbackException.
  1090. *
  1091. * @return void
  1092. */
  1093. public function testNestedTransactionRollbackExceptionThrown()
  1094. {
  1095. $this->rollbackSourceLine = -1;
  1096. $e = null;
  1097. try {
  1098. $this->connection->transactional(function () {
  1099. $this->connection->transactional(function () {
  1100. return false;
  1101. });
  1102. $this->rollbackSourceLine = __LINE__ - 1;
  1103. return true;
  1104. });
  1105. $this->fail('NestedTransactionRollbackException should be thrown');
  1106. } catch (NestedTransactionRollbackException $e) {
  1107. }
  1108. $trace = $e->getTrace();
  1109. $this->assertEquals(__FILE__, $trace[1]['file']);
  1110. $this->assertEquals($this->rollbackSourceLine, $trace[1]['line']);
  1111. }
  1112. /**
  1113. * Tests more detail about that not allowed nesting of rollback/commit
  1114. * operations throws a NestedTransactionRollbackException.
  1115. *
  1116. * @return void
  1117. */
  1118. public function testNestedTransactionStates()
  1119. {
  1120. $this->rollbackSourceLine = -1;
  1121. $this->nestedTransactionStates = [];
  1122. $e = null;
  1123. try {
  1124. $this->connection->transactional(function () {
  1125. $this->pushNestedTransactionState();
  1126. $this->connection->transactional(function () {
  1127. return true;
  1128. });
  1129. $this->connection->transactional(function () {
  1130. $this->pushNestedTransactionState();
  1131. $this->connection->transactional(function () {
  1132. return false;
  1133. });
  1134. $this->rollbackSourceLine = __LINE__ - 1;
  1135. $this->pushNestedTransactionState();
  1136. return true;
  1137. });
  1138. $this->connection->transactional(function () {
  1139. return false;
  1140. });
  1141. $this->pushNestedTransactionState();
  1142. return true;
  1143. });
  1144. $this->fail('NestedTransactionRollbackException should be thrown');
  1145. } catch (NestedTransactionRollbackException $e) {
  1146. }
  1147. $this->pushNestedTransactionState();
  1148. $this->assertSame([false, false, true, true, false], $this->nestedTransactionStates);
  1149. $this->assertFalse($this->connection->inTransaction());
  1150. $trace = $e->getTrace();
  1151. $this->assertEquals(__FILE__, $trace[1]['file']);
  1152. $this->assertEquals($this->rollbackSourceLine, $trace[1]['line']);
  1153. }
  1154. /**
  1155. * Helper method to trace nested transaction states.
  1156. *
  1157. * @return void
  1158. */
  1159. public function pushNestedTransactionState()
  1160. {
  1161. $method = new ReflectionMethod($this->connection, 'wasNestedTransactionRolledback');
  1162. $method->setAccessible(true);
  1163. $this->nestedTransactionStates[] = $method->invoke($this->connection);
  1164. }
  1165. /**
  1166. * Tests that the connection is restablished whenever it is interrupted
  1167. * after having used the connection at least once.
  1168. *
  1169. * @return void
  1170. */
  1171. public function testAutomaticReconnect()
  1172. {
  1173. $conn = clone $this->connection;
  1174. $statement = $conn->query('SELECT 1');
  1175. $statement->execute();
  1176. $statement->closeCursor();
  1177. $prop = new ReflectionProperty($conn, '_driver');
  1178. $prop->setAccessible(true);
  1179. $oldDriver = $prop->getValue($conn);
  1180. $newDriver = $this->getMockBuilder('Cake\Database\Driver')->getMock();
  1181. $prop->setValue($conn, $newDriver);
  1182. $newDriver->expects($this->at(0))
  1183. ->method('prepare')
  1184. ->will($this->throwException(new Exception('server gone away')));
  1185. $newDriver->expects($this->at(1))->method('disconnect');
  1186. $newDriver->expects($this->at(2))->method('connect');
  1187. $newDriver->expects($this->at(3))
  1188. ->method('prepare')
  1189. ->will($this->returnValue($statement));
  1190. $res = $conn->query('SELECT 1');
  1191. $this->assertInstanceOf(StatementInterface::class, $res);
  1192. }
  1193. /**
  1194. * Tests that the connection is not restablished whenever it is interrupted
  1195. * inside a transaction.
  1196. *
  1197. * @return void
  1198. */
  1199. public function testNoAutomaticReconnect()
  1200. {
  1201. $conn = clone $this->connection;
  1202. $statement = $conn->query('SELECT 1');
  1203. $statement->execute();
  1204. $statement->closeCursor();
  1205. $conn->begin();
  1206. $prop = new ReflectionProperty($conn, '_driver');
  1207. $prop->setAccessible(true);
  1208. $oldDriver = $prop->getValue($conn);
  1209. $newDriver = $this->getMockBuilder('Cake\Database\Driver')->getMock();
  1210. $prop->setValue($conn, $newDriver);
  1211. $newDriver->expects($this->once())
  1212. ->method('prepare')
  1213. ->will($this->throwException(new Exception('server gone away')));
  1214. $this->expectException(Exception::class);
  1215. $conn->query('SELECT 1');
  1216. }
  1217. }