ConnectionTest.php 25 KB

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