PageRenderTime 57ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/TestCase/Database/ConnectionTest.php

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