ConnectionTest.php 37 KB

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