ConnectionTest.php 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392
  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\StatementInterface;
  24. use Cake\Database\Statement\BufferedStatement;
  25. use Cake\Datasource\ConnectionManager;
  26. use Cake\Log\Log;
  27. use Cake\TestSuite\TestCase;
  28. use Error;
  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 that the transactional method will rollback the transaction
  983. * and throw the same error if the callback raises one
  984. *
  985. * @return void
  986. * @throws \Error
  987. */
  988. public function testTransactionalWithPHP7Error()
  989. {
  990. $this->skipIf(version_compare(PHP_VERSION, '7.0.0', '<'), 'Error class only exists since PHP 7.');
  991. $this->expectException(\Error::class);
  992. $driver = $this->getMockFormDriver();
  993. $connection = $this->getMockBuilder(Connection::class)
  994. ->setMethods(['connect', 'commit', 'begin', 'rollback'])
  995. ->setConstructorArgs([['driver' => $driver]])
  996. ->getMock();
  997. $connection->expects($this->at(0))->method('begin');
  998. $connection->expects($this->at(1))->method('rollback');
  999. $connection->expects($this->never())->method('commit');
  1000. $connection->transactional(function ($conn) use ($connection) {
  1001. $this->assertSame($connection, $conn);
  1002. throw new \Error();
  1003. });
  1004. }
  1005. /**
  1006. * Tests it is possible to set a schema collection object
  1007. *
  1008. * @return void
  1009. */
  1010. public function testSetSchemaCollection()
  1011. {
  1012. $driver = $this->getMockFormDriver();
  1013. $connection = $this->getMockBuilder(Connection::class)
  1014. ->setMethods(['connect'])
  1015. ->setConstructorArgs([['driver' => $driver]])
  1016. ->getMock();
  1017. $schema = $connection->getSchemaCollection();
  1018. $this->assertInstanceOf('Cake\Database\Schema\Collection', $schema);
  1019. $schema = $this->getMockBuilder('Cake\Database\Schema\Collection')
  1020. ->setConstructorArgs([$connection])
  1021. ->getMock();
  1022. $connection->setSchemaCollection($schema);
  1023. $this->assertSame($schema, $connection->getSchemaCollection());
  1024. }
  1025. /**
  1026. * Tests it is possible to set a schema collection object
  1027. *
  1028. * @group deprecated
  1029. * @return void
  1030. */
  1031. public function testSchemaCollection()
  1032. {
  1033. $this->deprecated(function () {
  1034. $driver = $this->getMockFormDriver();
  1035. $connection = $this->getMockBuilder(Connection::class)
  1036. ->setMethods(['connect'])
  1037. ->setConstructorArgs([['driver' => $driver]])
  1038. ->getMock();
  1039. $schema = $connection->schemaCollection();
  1040. $this->assertInstanceOf('Cake\Database\Schema\Collection', $schema);
  1041. $schema = $this->getMockBuilder('Cake\Database\Schema\Collection')
  1042. ->setConstructorArgs([$connection])
  1043. ->getMock();
  1044. $connection->schemaCollection($schema);
  1045. $this->assertSame($schema, $connection->schemaCollection());
  1046. });
  1047. }
  1048. /**
  1049. * Tests that allowed nesting of commit/rollback operations doesn't
  1050. * throw any exceptions.
  1051. *
  1052. * @return void
  1053. */
  1054. public function testNestedTransactionRollbackExceptionNotThrown()
  1055. {
  1056. $this->connection->transactional(function () {
  1057. $this->connection->transactional(function () {
  1058. return true;
  1059. });
  1060. return true;
  1061. });
  1062. $this->assertFalse($this->connection->inTransaction());
  1063. $this->connection->transactional(function () {
  1064. $this->connection->transactional(function () {
  1065. return true;
  1066. });
  1067. return false;
  1068. });
  1069. $this->assertFalse($this->connection->inTransaction());
  1070. $this->connection->transactional(function () {
  1071. $this->connection->transactional(function () {
  1072. return false;
  1073. });
  1074. return false;
  1075. });
  1076. $this->assertFalse($this->connection->inTransaction());
  1077. }
  1078. /**
  1079. * Tests that not allowed nesting of commit/rollback operations throws
  1080. * a NestedTransactionRollbackException.
  1081. *
  1082. * @return void
  1083. */
  1084. public function testNestedTransactionRollbackExceptionThrown()
  1085. {
  1086. $this->rollbackSourceLine = -1;
  1087. $e = null;
  1088. try {
  1089. $this->connection->transactional(function () {
  1090. $this->connection->transactional(function () {
  1091. return false;
  1092. });
  1093. $this->rollbackSourceLine = __LINE__ - 1;
  1094. return true;
  1095. });
  1096. $this->fail('NestedTransactionRollbackException should be thrown');
  1097. } catch (NestedTransactionRollbackException $e) {
  1098. }
  1099. $trace = $e->getTrace();
  1100. $this->assertEquals(__FILE__, $trace[1]['file']);
  1101. $this->assertEquals($this->rollbackSourceLine, $trace[1]['line']);
  1102. }
  1103. /**
  1104. * Tests more detail about that not allowed nesting of rollback/commit
  1105. * operations throws a NestedTransactionRollbackException.
  1106. *
  1107. * @return void
  1108. */
  1109. public function testNestedTransactionStates()
  1110. {
  1111. $this->rollbackSourceLine = -1;
  1112. $this->nestedTransactionStates = [];
  1113. $e = null;
  1114. try {
  1115. $this->connection->transactional(function () {
  1116. $this->pushNestedTransactionState();
  1117. $this->connection->transactional(function () {
  1118. return true;
  1119. });
  1120. $this->connection->transactional(function () {
  1121. $this->pushNestedTransactionState();
  1122. $this->connection->transactional(function () {
  1123. return false;
  1124. });
  1125. $this->rollbackSourceLine = __LINE__ - 1;
  1126. $this->pushNestedTransactionState();
  1127. return true;
  1128. });
  1129. $this->connection->transactional(function () {
  1130. return false;
  1131. });
  1132. $this->pushNestedTransactionState();
  1133. return true;
  1134. });
  1135. $this->fail('NestedTransactionRollbackException should be thrown');
  1136. } catch (NestedTransactionRollbackException $e) {
  1137. }
  1138. $this->pushNestedTransactionState();
  1139. $this->assertSame([false, false, true, true, false], $this->nestedTransactionStates);
  1140. $this->assertFalse($this->connection->inTransaction());
  1141. $trace = $e->getTrace();
  1142. $this->assertEquals(__FILE__, $trace[1]['file']);
  1143. $this->assertEquals($this->rollbackSourceLine, $trace[1]['line']);
  1144. }
  1145. /**
  1146. * Helper method to trace nested transaction states.
  1147. *
  1148. * @return void
  1149. */
  1150. public function pushNestedTransactionState()
  1151. {
  1152. $method = new ReflectionMethod($this->connection, 'wasNestedTransactionRolledback');
  1153. $method->setAccessible(true);
  1154. $this->nestedTransactionStates[] = $method->invoke($this->connection);
  1155. }
  1156. /**
  1157. * Tests that the connection is restablished whenever it is interrupted
  1158. * after having used the connection at least once.
  1159. *
  1160. * @return void
  1161. */
  1162. public function testAutomaticReconnect()
  1163. {
  1164. $conn = clone $this->connection;
  1165. $statement = $conn->query('SELECT 1');
  1166. $statement->execute();
  1167. $statement->closeCursor();
  1168. $prop = new ReflectionProperty($conn, '_driver');
  1169. $prop->setAccessible(true);
  1170. $oldDriver = $prop->getValue($conn);
  1171. $newDriver = $this->getMockBuilder('Cake\Database\Driver')->getMock();
  1172. $prop->setValue($conn, $newDriver);
  1173. $newDriver->expects($this->at(0))
  1174. ->method('prepare')
  1175. ->will($this->throwException(new Exception('server gone away')));
  1176. $newDriver->expects($this->at(1))->method('disconnect');
  1177. $newDriver->expects($this->at(2))->method('connect');
  1178. $newDriver->expects($this->at(3))
  1179. ->method('prepare')
  1180. ->will($this->returnValue($statement));
  1181. $res = $conn->query('SELECT 1');
  1182. $this->assertInstanceOf(StatementInterface::class, $res);
  1183. }
  1184. /**
  1185. * Tests that the connection is not restablished whenever it is interrupted
  1186. * inside a transaction.
  1187. *
  1188. * @return void
  1189. */
  1190. public function testNoAutomaticReconnect()
  1191. {
  1192. $conn = clone $this->connection;
  1193. $statement = $conn->query('SELECT 1');
  1194. $statement->execute();
  1195. $statement->closeCursor();
  1196. $conn->begin();
  1197. $prop = new ReflectionProperty($conn, '_driver');
  1198. $prop->setAccessible(true);
  1199. $oldDriver = $prop->getValue($conn);
  1200. $newDriver = $this->getMockBuilder('Cake\Database\Driver')->getMock();
  1201. $prop->setValue($conn, $newDriver);
  1202. $newDriver->expects($this->once())
  1203. ->method('prepare')
  1204. ->will($this->throwException(new Exception('server gone away')));
  1205. $this->expectException(Exception::class);
  1206. $conn->query('SELECT 1');
  1207. }
  1208. }