ConnectionTest.php 42 KB

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