ConnectionTest.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  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. $result = $this->connection->execute('SELECT title, body FROM things');
  254. $row = $result->fetch('assoc');
  255. $this->assertEquals('a title', $row['title']);
  256. $this->assertEquals('a body', $row['body']);
  257. $row = $result->fetch('assoc');
  258. $result->closeCursor();
  259. $this->assertEquals('another title', $row['title']);
  260. $this->assertEquals('another body', $row['body']);
  261. }
  262. /**
  263. * Tests that it is possible to pass PDO constants to the underlying statement
  264. * object for using alternate fetch types
  265. *
  266. * @return void
  267. */
  268. public function testStatementFetchObject()
  269. {
  270. $result = $this->connection->execute('SELECT title, body FROM things');
  271. $row = $result->fetch(\PDO::FETCH_OBJ);
  272. $this->assertEquals('a title', $row->title);
  273. $this->assertEquals('a body', $row->body);
  274. }
  275. /**
  276. * Tests rows can be updated without specifying any conditions nor types
  277. *
  278. * @return void
  279. */
  280. public function testUpdateWithoutConditionsNorTypes()
  281. {
  282. $title = 'changed the title!';
  283. $body = 'changed the body!';
  284. $this->connection->update('things', ['title' => $title, 'body' => $body]);
  285. $result = $this->connection->execute('SELECT * FROM things WHERE title = ? AND body = ?', [$title, $body]);
  286. $this->assertCount(2, $result);
  287. $result->closeCursor();
  288. }
  289. /**
  290. * Tests it is possible to use key => value conditions for update
  291. *
  292. * @return void
  293. */
  294. public function testUpdateWithConditionsNoTypes()
  295. {
  296. $title = 'changed the title!';
  297. $body = 'changed the body!';
  298. $this->connection->update('things', ['title' => $title, 'body' => $body], ['id' => 2]);
  299. $result = $this->connection->execute('SELECT * FROM things WHERE title = ? AND body = ?', [$title, $body]);
  300. $this->assertCount(1, $result);
  301. $result->closeCursor();
  302. }
  303. /**
  304. * Tests it is possible to use key => value and string conditions for update
  305. *
  306. * @return void
  307. */
  308. public function testUpdateWithConditionsCombinedNoTypes()
  309. {
  310. $title = 'changed the title!';
  311. $body = 'changed the body!';
  312. $this->connection->update('things', ['title' => $title, 'body' => $body], ['id' => 2, 'body is not null']);
  313. $result = $this->connection->execute('SELECT * FROM things WHERE title = ? AND body = ?', [$title, $body]);
  314. $this->assertCount(1, $result);
  315. $result->closeCursor();
  316. }
  317. /**
  318. * Tests you can bind types to update values
  319. *
  320. * @return void
  321. */
  322. public function testUpdateWithTypes()
  323. {
  324. $title = 'changed the title!';
  325. $body = new \DateTime('2012-01-01');
  326. $values = compact('title', 'body');
  327. $this->connection->update('things', $values, [], ['body' => 'date']);
  328. $result = $this->connection->execute('SELECT * FROM things WHERE title = :title AND body = :body', $values, ['body' => 'date']);
  329. $this->assertCount(2, $result);
  330. $row = $result->fetch('assoc');
  331. $this->assertEquals('2012-01-01', $row['body']);
  332. $row = $result->fetch('assoc');
  333. $this->assertEquals('2012-01-01', $row['body']);
  334. $result->closeCursor();
  335. }
  336. /**
  337. * Tests you can bind types to update values
  338. *
  339. * @return void
  340. */
  341. public function testUpdateWithConditionsAndTypes()
  342. {
  343. $title = 'changed the title!';
  344. $body = new \DateTime('2012-01-01');
  345. $values = compact('title', 'body');
  346. $this->connection->update('things', $values, ['id' => '1-string-parsed-as-int'], ['body' => 'date', 'id' => 'integer']);
  347. $result = $this->connection->execute('SELECT * FROM things WHERE title = :title AND body = :body', $values, ['body' => 'date']);
  348. $this->assertCount(1, $result);
  349. $row = $result->fetch('assoc');
  350. $this->assertEquals('2012-01-01', $row['body']);
  351. $result->closeCursor();
  352. }
  353. /**
  354. * Tests delete from table with no conditions
  355. *
  356. * @return void
  357. */
  358. public function testDeleteNoConditions()
  359. {
  360. $this->connection->delete('things');
  361. $result = $this->connection->execute('SELECT * FROM things');
  362. $this->assertCount(0, $result);
  363. $result->closeCursor();
  364. }
  365. /**
  366. * Tests delete from table with conditions
  367. * @return void
  368. */
  369. public function testDeleteWithConditions()
  370. {
  371. $this->connection->delete('things', ['id' => '1-rest-is-ommited'], ['id' => 'integer']);
  372. $result = $this->connection->execute('SELECT * FROM things');
  373. $this->assertCount(1, $result);
  374. $result->closeCursor();
  375. $this->connection->delete('things', ['id' => '1-rest-is-ommited'], ['id' => 'integer']);
  376. $result = $this->connection->execute('SELECT * FROM things');
  377. $this->assertCount(1, $result);
  378. $result->closeCursor();
  379. $this->connection->delete('things', ['id' => '2-rest-is-ommited'], ['id' => 'integer']);
  380. $result = $this->connection->execute('SELECT * FROM things');
  381. $this->assertCount(0, $result);
  382. $result->closeCursor();
  383. }
  384. /**
  385. * Tests that it is possible to use simple database transactions
  386. *
  387. * @return void
  388. */
  389. public function testSimpleTransactions()
  390. {
  391. $this->connection->begin();
  392. $this->connection->delete('things', ['id' => 1]);
  393. $this->connection->rollback();
  394. $result = $this->connection->execute('SELECT * FROM things');
  395. $this->assertCount(2, $result);
  396. $result->closeCursor();
  397. $this->connection->begin();
  398. $this->connection->delete('things', ['id' => 1]);
  399. $this->connection->commit();
  400. $result = $this->connection->execute('SELECT * FROM things');
  401. $this->assertCount(1, $result);
  402. }
  403. /**
  404. * Tests that it is possible to use virtualized nested transaction
  405. * with early rollback algorithm
  406. *
  407. * @return void
  408. */
  409. public function testVirtualNestedTrasanction()
  410. {
  411. //starting 3 virtual transaction
  412. $this->connection->begin();
  413. $this->connection->begin();
  414. $this->connection->begin();
  415. $this->connection->delete('things', ['id' => 1]);
  416. $result = $this->connection->execute('SELECT * FROM things');
  417. $this->assertCount(1, $result);
  418. $this->connection->commit();
  419. $this->connection->rollback();
  420. $result = $this->connection->execute('SELECT * FROM things');
  421. $this->assertCount(2, $result);
  422. }
  423. /**
  424. * Tests that it is possible to use virtualized nested transaction
  425. * with early rollback algorithm
  426. *
  427. * @return void
  428. */
  429. public function testVirtualNestedTrasanction2()
  430. {
  431. //starting 3 virtual transaction
  432. $this->connection->begin();
  433. $this->connection->begin();
  434. $this->connection->begin();
  435. $this->connection->delete('things', ['id' => 1]);
  436. $result = $this->connection->execute('SELECT * FROM things');
  437. $this->assertCount(1, $result);
  438. $this->connection->rollback();
  439. $result = $this->connection->execute('SELECT * FROM things');
  440. $this->assertCount(2, $result);
  441. }
  442. /**
  443. * Tests that it is possible to use virtualized nested transaction
  444. * with early rollback algorithm
  445. *
  446. * @return void
  447. */
  448. public function testVirtualNestedTrasanction3()
  449. {
  450. //starting 3 virtual transaction
  451. $this->connection->begin();
  452. $this->connection->begin();
  453. $this->connection->begin();
  454. $this->connection->delete('things', ['id' => 1]);
  455. $result = $this->connection->execute('SELECT * FROM things');
  456. $this->assertCount(1, $result);
  457. $this->connection->commit();
  458. $this->connection->commit();
  459. $this->connection->commit();
  460. $result = $this->connection->execute('SELECT * FROM things');
  461. $this->assertCount(1, $result);
  462. }
  463. /**
  464. * Tests that it is possible to real use nested transactions
  465. *
  466. * @return void
  467. */
  468. public function testSavePoints()
  469. {
  470. $this->skipIf(!$this->connection->useSavePoints(true));
  471. $this->connection->begin();
  472. $this->connection->delete('things', ['id' => 1]);
  473. $result = $this->connection->execute('SELECT * FROM things');
  474. $this->assertCount(1, $result);
  475. $this->connection->begin();
  476. $this->connection->delete('things', ['id' => 2]);
  477. $result = $this->connection->execute('SELECT * FROM things');
  478. $this->assertCount(0, $result);
  479. $this->connection->rollback();
  480. $result = $this->connection->execute('SELECT * FROM things');
  481. $this->assertCount(1, $result);
  482. $this->connection->rollback();
  483. $result = $this->connection->execute('SELECT * FROM things');
  484. $this->assertCount(2, $result);
  485. }
  486. /**
  487. * Tests that it is possible to real use nested transactions
  488. *
  489. * @return void
  490. */
  491. public function testSavePoints2()
  492. {
  493. $this->skipIf(!$this->connection->useSavePoints(true));
  494. $this->connection->begin();
  495. $this->connection->delete('things', ['id' => 1]);
  496. $result = $this->connection->execute('SELECT * FROM things');
  497. $this->assertCount(1, $result);
  498. $this->connection->begin();
  499. $this->connection->delete('things', ['id' => 2]);
  500. $result = $this->connection->execute('SELECT * FROM things');
  501. $this->assertCount(0, $result);
  502. $this->connection->rollback();
  503. $result = $this->connection->execute('SELECT * FROM things');
  504. $this->assertCount(1, $result);
  505. $this->connection->commit();
  506. $result = $this->connection->execute('SELECT * FROM things');
  507. $this->assertCount(1, $result);
  508. }
  509. /**
  510. * Tests connection can quote values to be safely used in query strings
  511. *
  512. * @return void
  513. */
  514. public function testQuote()
  515. {
  516. $this->skipIf(!$this->connection->supportsQuoting());
  517. $expected = "'2012-01-01'";
  518. $result = $this->connection->quote(new \DateTime('2012-01-01'), 'date');
  519. $this->assertEquals($expected, $result);
  520. $expected = "'1'";
  521. $result = $this->connection->quote(1, 'string');
  522. $this->assertEquals($expected, $result);
  523. $expected = "'hello'";
  524. $result = $this->connection->quote('hello', 'string');
  525. $this->assertEquals($expected, $result);
  526. }
  527. /**
  528. * Tests identifier quoting
  529. *
  530. * @return void
  531. */
  532. public function testQuoteIdentifier()
  533. {
  534. $driver = $this->getMock('Cake\Database\Driver\Sqlite', ['enabled']);
  535. $driver->expects($this->once())
  536. ->method('enabled')
  537. ->will($this->returnValue(true));
  538. $connection = new Connection(['driver' => $driver]);
  539. $result = $connection->quoteIdentifier('name');
  540. $expected = '"name"';
  541. $this->assertEquals($expected, $result);
  542. $result = $connection->quoteIdentifier('Model.*');
  543. $expected = '"Model".*';
  544. $this->assertEquals($expected, $result);
  545. $result = $connection->quoteIdentifier('MTD()');
  546. $expected = 'MTD()';
  547. $this->assertEquals($expected, $result);
  548. $result = $connection->quoteIdentifier('(sm)');
  549. $expected = '(sm)';
  550. $this->assertEquals($expected, $result);
  551. $result = $connection->quoteIdentifier('name AS x');
  552. $expected = '"name" AS "x"';
  553. $this->assertEquals($expected, $result);
  554. $result = $connection->quoteIdentifier('Model.name AS x');
  555. $expected = '"Model"."name" AS "x"';
  556. $this->assertEquals($expected, $result);
  557. $result = $connection->quoteIdentifier('Function(Something.foo)');
  558. $expected = 'Function("Something"."foo")';
  559. $this->assertEquals($expected, $result);
  560. $result = $connection->quoteIdentifier('Function(SubFunction(Something.foo))');
  561. $expected = 'Function(SubFunction("Something"."foo"))';
  562. $this->assertEquals($expected, $result);
  563. $result = $connection->quoteIdentifier('Function(Something.foo) AS x');
  564. $expected = 'Function("Something"."foo") AS "x"';
  565. $this->assertEquals($expected, $result);
  566. $result = $connection->quoteIdentifier('name-with-minus');
  567. $expected = '"name-with-minus"';
  568. $this->assertEquals($expected, $result);
  569. $result = $connection->quoteIdentifier('my-name');
  570. $expected = '"my-name"';
  571. $this->assertEquals($expected, $result);
  572. $result = $connection->quoteIdentifier('Foo-Model.*');
  573. $expected = '"Foo-Model".*';
  574. $this->assertEquals($expected, $result);
  575. $result = $connection->quoteIdentifier('Team.P%');
  576. $expected = '"Team"."P%"';
  577. $this->assertEquals($expected, $result);
  578. $result = $connection->quoteIdentifier('Team.G/G');
  579. $expected = '"Team"."G/G"';
  580. $result = $connection->quoteIdentifier('Model.name as y');
  581. $expected = '"Model"."name" AS "y"';
  582. $this->assertEquals($expected, $result);
  583. }
  584. /**
  585. * Tests default return vale for logger() function
  586. *
  587. * @return void
  588. */
  589. public function testLoggerDefault()
  590. {
  591. $logger = $this->connection->logger();
  592. $this->assertInstanceOf('Cake\Database\Log\QueryLogger', $logger);
  593. $this->assertSame($logger, $this->connection->logger());
  594. }
  595. /**
  596. * Tests that a custom logger object can be set
  597. *
  598. * @return void
  599. */
  600. public function testSetLogger()
  601. {
  602. $logger = new \Cake\Database\Log\QueryLogger;
  603. $this->connection->logger($logger);
  604. $this->assertSame($logger, $this->connection->logger());
  605. }
  606. /**
  607. * Tests that statements are decorated with a logger when logQueries is set to true
  608. *
  609. * @return void
  610. */
  611. public function testLoggerDecorator()
  612. {
  613. $logger = new \Cake\Database\Log\QueryLogger;
  614. $this->connection->logQueries(true);
  615. $this->connection->logger($logger);
  616. $st = $this->connection->prepare('SELECT 1');
  617. $this->assertInstanceOf('Cake\Database\Log\LoggingStatement', $st);
  618. $this->assertSame($logger, $st->logger());
  619. $this->connection->logQueries(false);
  620. $st = $this->connection->prepare('SELECT 1');
  621. $this->assertNotInstanceOf('\Cake\Database\Log\LoggingStatement', $st);
  622. }
  623. /**
  624. * test logQueries method
  625. *
  626. * @return void
  627. */
  628. public function testLogQueries()
  629. {
  630. $this->connection->logQueries(true);
  631. $this->assertTrue($this->connection->logQueries());
  632. $this->connection->logQueries(false);
  633. $this->assertFalse($this->connection->logQueries());
  634. }
  635. /**
  636. * Tests that log() function logs to the configured query logger
  637. *
  638. * @return void
  639. */
  640. public function testLogFunction()
  641. {
  642. $logger = $this->getMock('\Cake\Database\Log\QueryLogger');
  643. $this->connection->logger($logger);
  644. $logger->expects($this->once())->method('log')
  645. ->with($this->logicalAnd(
  646. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  647. $this->attributeEqualTo('query', 'SELECT 1')
  648. ));
  649. $this->connection->log('SELECT 1');
  650. }
  651. /**
  652. * Tests that begin and rollback are also logged
  653. *
  654. * @return void
  655. */
  656. public function testLogBeginRollbackTransaction()
  657. {
  658. $connection = $this
  659. ->getMockBuilder('\Cake\Database\Connection')
  660. ->setMethods(['connect'])
  661. ->disableOriginalConstructor()
  662. ->getMock();
  663. $connection->logQueries(true);
  664. $driver = $this->getMockFormDriver();
  665. $connection->driver($driver);
  666. $logger = $this->getMock('\Cake\Database\Log\QueryLogger');
  667. $connection->logger($logger);
  668. $logger->expects($this->at(0))->method('log')
  669. ->with($this->logicalAnd(
  670. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  671. $this->attributeEqualTo('query', 'BEGIN')
  672. ));
  673. $logger->expects($this->at(1))->method('log')
  674. ->with($this->logicalAnd(
  675. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  676. $this->attributeEqualTo('query', 'ROLLBACK')
  677. ));
  678. $connection->begin();
  679. $connection->begin(); //This one will not be logged
  680. $connection->rollback();
  681. }
  682. /**
  683. * Tests that commits are logged
  684. *
  685. * @return void
  686. */
  687. public function testLogCommitTransaction()
  688. {
  689. $driver = $this->getMockFormDriver();
  690. $connection = $this->getMock(
  691. '\Cake\Database\Connection',
  692. ['connect'],
  693. [['driver' => $driver]]
  694. );
  695. $logger = $this->getMock('\Cake\Database\Log\QueryLogger');
  696. $connection->logger($logger);
  697. $logger->expects($this->at(1))->method('log')
  698. ->with($this->logicalAnd(
  699. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  700. $this->attributeEqualTo('query', 'COMMIT')
  701. ));
  702. $connection->logQueries(true);
  703. $connection->begin();
  704. $connection->commit();
  705. }
  706. /**
  707. * Tests that the transactional method will start and commit a transaction
  708. * around some arbitrary function passed as argument
  709. *
  710. * @return void
  711. */
  712. public function testTransactionalSuccess()
  713. {
  714. $driver = $this->getMockFormDriver();
  715. $connection = $this->getMock(
  716. '\Cake\Database\Connection',
  717. ['connect', 'commit', 'begin'],
  718. [['driver' => $driver]]
  719. );
  720. $connection->expects($this->at(0))->method('begin');
  721. $connection->expects($this->at(1))->method('commit');
  722. $result = $connection->transactional(function ($conn) use ($connection) {
  723. $this->assertSame($connection, $conn);
  724. return 'thing';
  725. });
  726. $this->assertEquals('thing', $result);
  727. }
  728. /**
  729. * Tests that the transactional method will rollback the transaction if false
  730. * is returned from the callback
  731. *
  732. * @return void
  733. */
  734. public function testTransactionalFail()
  735. {
  736. $driver = $this->getMockFormDriver();
  737. $connection = $this->getMock(
  738. '\Cake\Database\Connection',
  739. ['connect', 'commit', 'begin', 'rollback'],
  740. [['driver' => $driver]]
  741. );
  742. $connection->expects($this->at(0))->method('begin');
  743. $connection->expects($this->at(1))->method('rollback');
  744. $connection->expects($this->never())->method('commit');
  745. $result = $connection->transactional(function ($conn) use ($connection) {
  746. $this->assertSame($connection, $conn);
  747. return false;
  748. });
  749. $this->assertFalse($result);
  750. }
  751. /**
  752. * Tests that the transactional method will rollback the transaction
  753. * and throw the same exception if the callback raises one
  754. *
  755. * @expectedException \InvalidArgumentException
  756. * @return void
  757. * @throws \InvalidArgumentException
  758. */
  759. public function testTransactionalWithException()
  760. {
  761. $driver = $this->getMockFormDriver();
  762. $connection = $this->getMock(
  763. '\Cake\Database\Connection',
  764. ['connect', 'commit', 'begin', 'rollback'],
  765. [['driver' => $driver]]
  766. );
  767. $connection->expects($this->at(0))->method('begin');
  768. $connection->expects($this->at(1))->method('rollback');
  769. $connection->expects($this->never())->method('commit');
  770. $connection->transactional(function ($conn) use ($connection) {
  771. $this->assertSame($connection, $conn);
  772. throw new \InvalidArgumentException;
  773. });
  774. }
  775. /**
  776. * Tests it is possible to set a schema collection object
  777. *
  778. * @return void
  779. */
  780. public function testSchemaCollection()
  781. {
  782. $driver = $this->getMockFormDriver();
  783. $connection = $this->getMock(
  784. '\Cake\Database\Connection',
  785. ['connect'],
  786. [['driver' => $driver]]
  787. );
  788. $schema = $connection->schemaCollection();
  789. $this->assertInstanceOf('Cake\Database\Schema\Collection', $schema);
  790. $schema = $this->getMock('Cake\Database\Schema\Collection', [], [$connection]);
  791. $connection->schemaCollection($schema);
  792. $this->assertSame($schema, $connection->schemaCollection());
  793. }
  794. }