ConnectionTest.php 42 KB

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