ConnectionTest.php 46 KB

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