ConnectionTest.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  14. */
  15. namespace Cake\Test\TestCase\Database;
  16. use Cake\Core\Configure;
  17. use Cake\Database\Connection;
  18. use Cake\Datasource\ConnectionManager;
  19. use Cake\TestSuite\TestCase;
  20. /**
  21. * Tests Connection class
  22. */
  23. class ConnectionTest extends TestCase {
  24. public $fixtures = ['core.thing'];
  25. public function setUp() {
  26. $this->connection = ConnectionManager::get('test');
  27. $this->skipIf($this->connection()->driver() instanceof \Cake\Database\Driver\Sqlite);
  28. parent::setUp();
  29. }
  30. public function tearDown() {
  31. $this->connection->useSavePoints(false);
  32. unset($this->connection);
  33. parent::tearDown();
  34. }
  35. /**
  36. * Auxiliary method to build a mock for a driver so it can be injected into
  37. * the connection object
  38. *
  39. * @return \Cake\Database\Driver
  40. */
  41. public function getMockFormDriver() {
  42. $driver = $this->getMock('Cake\Database\Driver');
  43. $driver->expects($this->once())
  44. ->method('enabled')
  45. ->will($this->returnValue(true));
  46. return $driver;
  47. }
  48. /**
  49. * Tests connecting to database
  50. *
  51. * @return void
  52. */
  53. public function testConnect() {
  54. $this->assertTrue($this->connection->connect());
  55. $this->assertTrue($this->connection->isConnected());
  56. }
  57. /**
  58. * Tests creating a connection using no driver throws an exception
  59. *
  60. * @expectedException \Cake\Database\Exception\MissingDriverException
  61. * @expectedExceptionMessage Database driver "" could not be found.
  62. * @return void
  63. */
  64. public function testNoDriver() {
  65. $connection = new Connection([]);
  66. }
  67. /**
  68. * Tests creating a connection using an invalid driver throws an exception
  69. *
  70. * @expectedException \Cake\Database\Exception\MissingDriverException
  71. * @expectedExceptionMessage Database driver "" could not be found.
  72. * @return void
  73. */
  74. public function testEmptyDriver() {
  75. $connection = new Connection(['driver' => false]);
  76. }
  77. /**
  78. * Tests creating a connection using an invalid driver throws an exception
  79. *
  80. * @expectedException \Cake\Database\Exception\MissingDriverException
  81. * @expectedExceptionMessage Database driver "\Foo\InvalidDriver" could not be found.
  82. * @return void
  83. */
  84. public function testMissingDriver() {
  85. $connection = new Connection(['driver' => '\Foo\InvalidDriver']);
  86. }
  87. /**
  88. * Tests trying to use a disabled driver throws an exception
  89. *
  90. * @expectedException \Cake\Database\Exception\MissingExtensionException
  91. * @expectedExceptionMessage Database driver DriverMock cannot be used due to a missing PHP extension or unmet dependency
  92. * @return void
  93. */
  94. public function testDisabledDriver() {
  95. $mock = $this->getMock('\Cake\Database\Connection\Driver', ['enabled'], [], 'DriverMock');
  96. $connection = new Connection(['driver' => $mock]);
  97. }
  98. /**
  99. * Tests that connecting with invalid credentials or database name throws an exception
  100. *
  101. * @expectedException \Cake\Database\Exception\MissingConnectionException
  102. * @return void
  103. **/
  104. public function testWrongCredentials() {
  105. $config = ConnectionManager::config('test');
  106. $this->skipIf(isset($config['dsn']), 'Datasource has dsn, skipping.');
  107. $connection = new Connection(['database' => '_probably_not_there_'] + ConnectionManager::config('test'));
  108. $connection->connect();
  109. }
  110. /**
  111. * Tests creation of prepared statements
  112. *
  113. * @return void
  114. **/
  115. public function testPrepare() {
  116. $sql = 'SELECT 1 + 1';
  117. $result = $this->connection->prepare($sql);
  118. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  119. $this->assertEquals($sql, $result->queryString);
  120. $query = $this->connection->newQuery()->select('1 + 1');
  121. $result = $this->connection->prepare($query);
  122. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  123. $sql = '#SELECT [`"\[]?1 \+ 1[`"\]]?#';
  124. $this->assertRegExp($sql, $result->queryString);
  125. }
  126. /**
  127. * Tests executing a simple query using bound values
  128. *
  129. * @return void
  130. **/
  131. public function testExecuteWithArguments() {
  132. $sql = 'SELECT 1 + ?';
  133. $statement = $this->connection->execute($sql, [1], array('integer'));
  134. $this->assertCount(1, $statement);
  135. $result = $statement->fetch();
  136. $this->assertEquals([2], $result);
  137. $statement->closeCursor();
  138. $sql = 'SELECT 1 + ? + ? AS total';
  139. $statement = $this->connection->execute($sql, [2, 3], array('integer', 'integer'));
  140. $this->assertCount(1, $statement);
  141. $result = $statement->fetch('assoc');
  142. $this->assertEquals(['total' => 6], $result);
  143. $statement->closeCursor();
  144. $sql = 'SELECT 1 + :one + :two AS total';
  145. $statement = $this->connection->execute($sql, ['one' => 2, 'two' => 3], array('one' => 'integer', 'two' => 'integer'));
  146. $this->assertCount(1, $statement);
  147. $result = $statement->fetch('assoc');
  148. $statement->closeCursor();
  149. $this->assertEquals(['total' => 6], $result);
  150. }
  151. /**
  152. * Tests executing a query with params and associated types
  153. *
  154. * @return void
  155. **/
  156. public function testExecuteWithArgumentsAndTypes() {
  157. $sql = "SELECT ? = '2012-01-01'";
  158. $statement = $this->connection->execute($sql, [new \DateTime('2012-01-01')], ['date']);
  159. $result = $statement->fetch();
  160. $statement->closeCursor();
  161. $this->assertTrue((bool)$result[0]);
  162. $sql = "SELECT ? = '2012-01-01', ? = '2000-01-01 10:10:10', ? = 2";
  163. $params = [new \DateTime('2012-01-01 10:10:10'), '2000-01-01 10:10:10', 2.1];
  164. $statement = $this->connection->execute($sql, $params, ['date', 'string', 'integer']);
  165. $result = $statement->fetch();
  166. $statement->closeCursor();
  167. $this->assertEquals($result, array_filter($result));
  168. }
  169. /**
  170. * Tests that passing a unknown value to a query throws an exception
  171. *
  172. * @expectedException \InvalidArgumentException
  173. * @return void
  174. **/
  175. public function testExecuteWithMissingType() {
  176. $sql = 'SELECT ?';
  177. $statement = $this->connection->execute($sql, [new \DateTime('2012-01-01')], ['bar']);
  178. }
  179. /**
  180. * Tests executing a query with no params also works
  181. *
  182. * @return void
  183. **/
  184. public function testExecuteWithNoParams() {
  185. $sql = 'SELECT 1';
  186. $statement = $this->connection->execute($sql);
  187. $result = $statement->fetch();
  188. $this->assertCount(1, $result);
  189. $this->assertEquals([1], $result);
  190. $statement->closeCursor();
  191. }
  192. /**
  193. * Tests it is possible to insert data into a table using matching types by key name
  194. *
  195. * @return void
  196. **/
  197. public function testInsertWithMatchingTypes() {
  198. $data = ['id' => '3', 'title' => 'a title', 'body' => 'a body'];
  199. $result = $this->connection->insert(
  200. 'things',
  201. $data,
  202. ['id' => 'integer', 'title' => 'string', 'body' => 'string']
  203. );
  204. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  205. $result->closeCursor();
  206. $result = $this->connection->execute('SELECT * from things where id = 3');
  207. $this->assertCount(1, $result);
  208. $row = $result->fetch('assoc');
  209. $result->closeCursor();
  210. $this->assertEquals($data, $row);
  211. }
  212. /**
  213. * Tests it is possible to insert data into a table using matching types by array position
  214. *
  215. * @return void
  216. **/
  217. public function testInsertWithPositionalTypes() {
  218. $data = ['id' => '3', 'title' => 'a title', 'body' => 'a body'];
  219. $result = $this->connection->insert(
  220. 'things',
  221. $data,
  222. ['integer', 'string', 'string']
  223. );
  224. $result->closeCursor();
  225. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  226. $result = $this->connection->execute('SELECT * from things where id = 3');
  227. $this->assertCount(1, $result);
  228. $row = $result->fetch('assoc');
  229. $result->closeCursor();
  230. $this->assertEquals($data, $row);
  231. }
  232. /**
  233. * Tests an statement class can be reused for multiple executions
  234. *
  235. * @return void
  236. **/
  237. public function testStatementReusing() {
  238. $total = $this->connection->execute('SELECT COUNT(*) AS total FROM things');
  239. $result = $total->fetch('assoc');
  240. $this->assertEquals(2, $result['total']);
  241. $total->closeCursor();
  242. $result = $this->connection->execute('SELECT title, body FROM things');
  243. $row = $result->fetch('assoc');
  244. $this->assertEquals('a title', $row['title']);
  245. $this->assertEquals('a body', $row['body']);
  246. $row = $result->fetch('assoc');
  247. $result->closeCursor();
  248. $this->assertEquals('another title', $row['title']);
  249. $this->assertEquals('another body', $row['body']);
  250. }
  251. /**
  252. * Tests rows can be updated without specifying any conditions nor types
  253. *
  254. * @return void
  255. **/
  256. public function testUpdateWithoutConditionsNorTypes() {
  257. $title = 'changed the title!';
  258. $body = 'changed the body!';
  259. $this->connection->update('things', ['title' => $title, 'body' => $body]);
  260. $result = $this->connection->execute('SELECT * FROM things WHERE title = ? AND body = ?', [$title, $body]);
  261. $this->assertCount(2, $result);
  262. $result->closeCursor();
  263. }
  264. /**
  265. * Tests it is possible to use key => value conditions for update
  266. *
  267. * @return void
  268. **/
  269. public function testUpdateWithConditionsNoTypes() {
  270. $title = 'changed the title!';
  271. $body = 'changed the body!';
  272. $this->connection->update('things', ['title' => $title, 'body' => $body], ['id' => 2]);
  273. $result = $this->connection->execute('SELECT * FROM things WHERE title = ? AND body = ?', [$title, $body]);
  274. $this->assertCount(1, $result);
  275. $result->closeCursor();
  276. }
  277. /**
  278. * Tests it is possible to use key => value and string conditions for update
  279. *
  280. * @return void
  281. **/
  282. public function testUpdateWithConditionsCombinedNoTypes() {
  283. $title = 'changed the title!';
  284. $body = 'changed the body!';
  285. $this->connection->update('things', ['title' => $title, 'body' => $body], ['id' => 2, 'body is not null']);
  286. $result = $this->connection->execute('SELECT * FROM things WHERE title = ? AND body = ?', [$title, $body]);
  287. $this->assertCount(1, $result);
  288. $result->closeCursor();
  289. }
  290. /**
  291. * Tests you can bind types to update values
  292. *
  293. * @return void
  294. **/
  295. public function testUpdateWithTypes() {
  296. $title = 'changed the title!';
  297. $body = new \DateTime('2012-01-01');
  298. $values = compact('title', 'body');
  299. $this->connection->update('things', $values, [], ['body' => 'date']);
  300. $result = $this->connection->execute('SELECT * FROM things WHERE title = :title AND body = :body', $values, ['body' => 'date']);
  301. $this->assertCount(2, $result);
  302. $row = $result->fetch('assoc');
  303. $this->assertEquals('2012-01-01', $row['body']);
  304. $row = $result->fetch('assoc');
  305. $this->assertEquals('2012-01-01', $row['body']);
  306. $result->closeCursor();
  307. }
  308. /**
  309. * Tests you can bind types to update values
  310. *
  311. * @return void
  312. **/
  313. public function testUpdateWithConditionsAndTypes() {
  314. $title = 'changed the title!';
  315. $body = new \DateTime('2012-01-01');
  316. $values = compact('title', 'body');
  317. $this->connection->update('things', $values, ['id' => '1-string-parsed-as-int'], ['body' => 'date', 'id' => 'integer']);
  318. $result = $this->connection->execute('SELECT * FROM things WHERE title = :title AND body = :body', $values, ['body' => 'date']);
  319. $this->assertCount(1, $result);
  320. $row = $result->fetch('assoc');
  321. $this->assertEquals('2012-01-01', $row['body']);
  322. $result->closeCursor();
  323. }
  324. /**
  325. * Tests delete from table with no conditions
  326. *
  327. * @return void
  328. **/
  329. public function testDeleteNoConditions() {
  330. $this->connection->delete('things');
  331. $result = $this->connection->execute('SELECT * FROM things');
  332. $this->assertCount(0, $result);
  333. $result->closeCursor();
  334. }
  335. /**
  336. * Tests delete from table with conditions
  337. * @return void
  338. **/
  339. public function testDeleteWithConditions() {
  340. $this->connection->delete('things', ['id' => '1-rest-is-ommited'], ['id' => 'integer']);
  341. $result = $this->connection->execute('SELECT * FROM things');
  342. $this->assertCount(1, $result);
  343. $result->closeCursor();
  344. $this->connection->delete('things', ['id' => '1-rest-is-ommited'], ['id' => 'integer']);
  345. $result = $this->connection->execute('SELECT * FROM things');
  346. $this->assertCount(1, $result);
  347. $result->closeCursor();
  348. $this->connection->delete('things', ['id' => '2-rest-is-ommited'], ['id' => 'integer']);
  349. $result = $this->connection->execute('SELECT * FROM things');
  350. $this->assertCount(0, $result);
  351. $result->closeCursor();
  352. }
  353. /**
  354. * Tests that it is possible to use simple database transactions
  355. *
  356. * @return void
  357. **/
  358. public function testSimpleTransactions() {
  359. $this->connection->begin();
  360. $this->connection->delete('things', ['id' => 1]);
  361. $this->connection->rollback();
  362. $result = $this->connection->execute('SELECT * FROM things');
  363. $this->assertCount(2, $result);
  364. $result->closeCursor();
  365. $this->connection->begin();
  366. $this->connection->delete('things', ['id' => 1]);
  367. $this->connection->commit();
  368. $result = $this->connection->execute('SELECT * FROM things');
  369. $this->assertCount(1, $result);
  370. }
  371. /**
  372. * Tests that it is possible to use virtualized nested transaction
  373. * with early rollback algorithm
  374. *
  375. * @return void
  376. **/
  377. public function testVirtualNestedTrasanction() {
  378. //starting 3 virtual transaction
  379. $this->connection->begin();
  380. $this->connection->begin();
  381. $this->connection->begin();
  382. $this->connection->delete('things', ['id' => 1]);
  383. $result = $this->connection->execute('SELECT * FROM things');
  384. $this->assertCount(1, $result);
  385. $this->connection->commit();
  386. $this->connection->rollback();
  387. $result = $this->connection->execute('SELECT * FROM things');
  388. $this->assertCount(2, $result);
  389. }
  390. /**
  391. * Tests that it is possible to use virtualized nested transaction
  392. * with early rollback algorithm
  393. *
  394. * @return void
  395. **/
  396. public function testVirtualNestedTrasanction2() {
  397. //starting 3 virtual transaction
  398. $this->connection->begin();
  399. $this->connection->begin();
  400. $this->connection->begin();
  401. $this->connection->delete('things', ['id' => 1]);
  402. $result = $this->connection->execute('SELECT * FROM things');
  403. $this->assertCount(1, $result);
  404. $this->connection->rollback();
  405. $result = $this->connection->execute('SELECT * FROM things');
  406. $this->assertCount(2, $result);
  407. }
  408. /**
  409. * Tests that it is possible to use virtualized nested transaction
  410. * with early rollback algorithm
  411. *
  412. * @return void
  413. **/
  414. public function testVirtualNestedTrasanction3() {
  415. //starting 3 virtual transaction
  416. $this->connection->begin();
  417. $this->connection->begin();
  418. $this->connection->begin();
  419. $this->connection->delete('things', ['id' => 1]);
  420. $result = $this->connection->execute('SELECT * FROM things');
  421. $this->assertCount(1, $result);
  422. $this->connection->commit();
  423. $this->connection->commit();
  424. $this->connection->commit();
  425. $result = $this->connection->execute('SELECT * FROM things');
  426. $this->assertCount(1, $result);
  427. }
  428. /**
  429. * Tests that it is possible to real use nested transactions
  430. *
  431. * @return void
  432. **/
  433. public function testSavePoints() {
  434. $this->skipIf(!$this->connection->useSavePoints(true));
  435. $this->connection->begin();
  436. $this->connection->delete('things', ['id' => 1]);
  437. $result = $this->connection->execute('SELECT * FROM things');
  438. $this->assertCount(1, $result);
  439. $this->connection->begin();
  440. $this->connection->delete('things', ['id' => 2]);
  441. $result = $this->connection->execute('SELECT * FROM things');
  442. $this->assertCount(0, $result);
  443. $this->connection->rollback();
  444. $result = $this->connection->execute('SELECT * FROM things');
  445. $this->assertCount(1, $result);
  446. $this->connection->rollback();
  447. $result = $this->connection->execute('SELECT * FROM things');
  448. $this->assertCount(2, $result);
  449. }
  450. /**
  451. * Tests that it is possible to real use nested transactions
  452. *
  453. * @return void
  454. **/
  455. public function testSavePoints2() {
  456. $this->skipIf(!$this->connection->useSavePoints(true));
  457. $this->connection->begin();
  458. $this->connection->delete('things', ['id' => 1]);
  459. $result = $this->connection->execute('SELECT * FROM things');
  460. $this->assertCount(1, $result);
  461. $this->connection->begin();
  462. $this->connection->delete('things', ['id' => 2]);
  463. $result = $this->connection->execute('SELECT * FROM things');
  464. $this->assertCount(0, $result);
  465. $this->connection->rollback();
  466. $result = $this->connection->execute('SELECT * FROM things');
  467. $this->assertCount(1, $result);
  468. $this->connection->commit();
  469. $result = $this->connection->execute('SELECT * FROM things');
  470. $this->assertCount(1, $result);
  471. }
  472. /**
  473. * Tests connection can quote values to be safely used in query strings
  474. *
  475. * @return void
  476. **/
  477. public function testQuote() {
  478. $this->skipIf(!$this->connection->supportsQuoting());
  479. $expected = "'2012-01-01'";
  480. $result = $this->connection->quote(new \DateTime('2012-01-01'), 'date');
  481. $this->assertEquals($expected, $result);
  482. $expected = "'1'";
  483. $result = $this->connection->quote(1, 'string');
  484. $this->assertEquals($expected, $result);
  485. $expected = "'hello'";
  486. $result = $this->connection->quote('hello', 'string');
  487. $this->assertEquals($expected, $result);
  488. }
  489. /**
  490. * Tests identifier quoting
  491. *
  492. * @return void
  493. */
  494. public function testQuoteIdentifier() {
  495. $driver = $this->getMock('Cake\Database\Driver\Sqlite', ['enabled']);
  496. $driver->expects($this->once())
  497. ->method('enabled')
  498. ->will($this->returnValue(true));
  499. $connection = new Connection(['driver' => $driver]);
  500. $result = $connection->quoteIdentifier('name');
  501. $expected = '"name"';
  502. $this->assertEquals($expected, $result);
  503. $result = $connection->quoteIdentifier('Model.*');
  504. $expected = '"Model".*';
  505. $this->assertEquals($expected, $result);
  506. $result = $connection->quoteIdentifier('MTD()');
  507. $expected = 'MTD()';
  508. $this->assertEquals($expected, $result);
  509. $result = $connection->quoteIdentifier('(sm)');
  510. $expected = '(sm)';
  511. $this->assertEquals($expected, $result);
  512. $result = $connection->quoteIdentifier('name AS x');
  513. $expected = '"name" AS "x"';
  514. $this->assertEquals($expected, $result);
  515. $result = $connection->quoteIdentifier('Model.name AS x');
  516. $expected = '"Model"."name" AS "x"';
  517. $this->assertEquals($expected, $result);
  518. $result = $connection->quoteIdentifier('Function(Something.foo)');
  519. $expected = 'Function("Something"."foo")';
  520. $this->assertEquals($expected, $result);
  521. $result = $connection->quoteIdentifier('Function(SubFunction(Something.foo))');
  522. $expected = 'Function(SubFunction("Something"."foo"))';
  523. $this->assertEquals($expected, $result);
  524. $result = $connection->quoteIdentifier('Function(Something.foo) AS x');
  525. $expected = 'Function("Something"."foo") AS "x"';
  526. $this->assertEquals($expected, $result);
  527. $result = $connection->quoteIdentifier('name-with-minus');
  528. $expected = '"name-with-minus"';
  529. $this->assertEquals($expected, $result);
  530. $result = $connection->quoteIdentifier('my-name');
  531. $expected = '"my-name"';
  532. $this->assertEquals($expected, $result);
  533. $result = $connection->quoteIdentifier('Foo-Model.*');
  534. $expected = '"Foo-Model".*';
  535. $this->assertEquals($expected, $result);
  536. $result = $connection->quoteIdentifier('Team.P%');
  537. $expected = '"Team"."P%"';
  538. $this->assertEquals($expected, $result);
  539. $result = $connection->quoteIdentifier('Team.G/G');
  540. $expected = '"Team"."G/G"';
  541. $result = $connection->quoteIdentifier('Model.name as y');
  542. $expected = '"Model"."name" AS "y"';
  543. $this->assertEquals($expected, $result);
  544. }
  545. /**
  546. * Tests default return vale for logger() function
  547. *
  548. * @return void
  549. */
  550. public function testLoggerDefault() {
  551. $logger = $this->connection->logger();
  552. $this->assertInstanceOf('\Cake\Database\Log\QueryLogger', $logger);
  553. $this->assertSame($logger, $this->connection->logger());
  554. }
  555. /**
  556. * Tests that a custom logger object can be set
  557. *
  558. * @return void
  559. */
  560. public function testSetLogger() {
  561. $logger = new \Cake\Database\Log\QueryLogger;
  562. $this->connection->logger($logger);
  563. $this->assertSame($logger, $this->connection->logger());
  564. }
  565. /**
  566. * Tests that statements are decorated with a logger when logQueries is set to true
  567. *
  568. * @return void
  569. */
  570. public function testLoggerDecorator() {
  571. $logger = new \Cake\Database\Log\QueryLogger;
  572. $this->connection->logQueries(true);
  573. $this->connection->logger($logger);
  574. $st = $this->connection->prepare('SELECT 1');
  575. $this->assertInstanceOf('\Cake\Database\Log\LoggingStatement', $st);
  576. $this->assertSame($logger, $st->logger());
  577. $this->connection->logQueries(false);
  578. $st = $this->connection->prepare('SELECT 1');
  579. $this->assertNotInstanceOf('\Cake\Database\Log\LoggingStatement', $st);
  580. }
  581. /**
  582. * Tests that log() function logs to the configured query logger
  583. *
  584. * @return void
  585. */
  586. public function testLogFunction() {
  587. $logger = $this->getMock('\Cake\Database\Log\QueryLogger');
  588. $this->connection->logger($logger);
  589. $logger->expects($this->once())->method('log')
  590. ->with($this->logicalAnd(
  591. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  592. $this->attributeEqualTo('query', 'SELECT 1')
  593. ));
  594. $this->connection->log('SELECT 1');
  595. }
  596. /**
  597. * Tests that begin and rollback are also logged
  598. *
  599. * @return void
  600. */
  601. public function testLogBeginRollbackTransaction() {
  602. $connection = $this
  603. ->getMockBuilder('\Cake\Database\Connection')
  604. ->setMethods(['connect'])
  605. ->disableOriginalConstructor()
  606. ->getMock();
  607. $connection->logQueries(true);
  608. $driver = $this->getMockFormDriver();
  609. $connection->driver($driver);
  610. $logger = $this->getMock('\Cake\Database\Log\QueryLogger');
  611. $connection->logger($logger);
  612. $logger->expects($this->at(0))->method('log')
  613. ->with($this->logicalAnd(
  614. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  615. $this->attributeEqualTo('query', 'BEGIN')
  616. ));
  617. $logger->expects($this->at(1))->method('log')
  618. ->with($this->logicalAnd(
  619. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  620. $this->attributeEqualTo('query', 'ROLLBACK')
  621. ));
  622. $connection->begin();
  623. $connection->begin(); //This one will not be logged
  624. $connection->rollback();
  625. }
  626. /**
  627. * Tests that commits are logged
  628. *
  629. * @return void
  630. */
  631. public function testLogCommitTransaction() {
  632. $driver = $this->getMockFormDriver();
  633. $connection = $this->getMock(
  634. '\Cake\Database\Connection',
  635. ['connect'],
  636. [['driver' => $driver]]
  637. );
  638. $logger = $this->getMock('\Cake\Database\Log\QueryLogger');
  639. $connection->logger($logger);
  640. $logger->expects($this->at(1))->method('log')
  641. ->with($this->logicalAnd(
  642. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  643. $this->attributeEqualTo('query', 'COMMIT')
  644. ));
  645. $connection->logQueries(true);
  646. $connection->begin();
  647. $connection->commit();
  648. }
  649. /**
  650. * Tests that the transactional method will start and commit a transaction
  651. * around some arbitrary function passed as argument
  652. *
  653. * @return void
  654. */
  655. public function testTransactionalSuccess() {
  656. $driver = $this->getMockFormDriver();
  657. $connection = $this->getMock(
  658. '\Cake\Database\Connection',
  659. ['connect', 'commit', 'begin'],
  660. [['driver' => $driver]]
  661. );
  662. $connection->expects($this->at(0))->method('begin');
  663. $connection->expects($this->at(1))->method('commit');
  664. $result = $connection->transactional(function($conn) use ($connection) {
  665. $this->assertSame($connection, $conn);
  666. return 'thing';
  667. });
  668. $this->assertEquals('thing', $result);
  669. }
  670. /**
  671. * Tests that the transactional method will rollback the transaction if false
  672. * is returned from the callback
  673. *
  674. * @return void
  675. */
  676. public function testTransactionalFail() {
  677. $driver = $this->getMockFormDriver();
  678. $connection = $this->getMock(
  679. '\Cake\Database\Connection',
  680. ['connect', 'commit', 'begin', 'rollback'],
  681. [['driver' => $driver]]
  682. );
  683. $connection->expects($this->at(0))->method('begin');
  684. $connection->expects($this->at(1))->method('rollback');
  685. $connection->expects($this->never())->method('commit');
  686. $result = $connection->transactional(function($conn) use ($connection) {
  687. $this->assertSame($connection, $conn);
  688. return false;
  689. });
  690. $this->assertFalse($result);
  691. }
  692. /**
  693. * Tests that the transactional method will rollback the transaction
  694. * and throw the same exception if the callback raises one
  695. *
  696. * @expectedException \InvalidArgumentException
  697. * @return void
  698. * @throws \InvalidArgumentException
  699. */
  700. public function testTransactionalWithException() {
  701. $driver = $this->getMockFormDriver();
  702. $connection = $this->getMock(
  703. '\Cake\Database\Connection',
  704. ['connect', 'commit', 'begin', 'rollback'],
  705. [['driver' => $driver]]
  706. );
  707. $connection->expects($this->at(0))->method('begin');
  708. $connection->expects($this->at(1))->method('rollback');
  709. $connection->expects($this->never())->method('commit');
  710. $connection->transactional(function($conn) use ($connection) {
  711. $this->assertSame($connection, $conn);
  712. throw new \InvalidArgumentException;
  713. });
  714. }
  715. }