ConnectionTest.php 25 KB

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