ConnectionTest.php 46 KB

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