ConnectionTest.php 39 KB

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