ConnectionTest.php 24 KB

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