ConnectionTest.php 41 KB

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