ConnectionTest.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  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 MIT License (http://www.opensource.org/licenses/mit-license.php)
  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 function setUp() {
  25. parent::setUp();
  26. $this->connection = ConnectionManager::get('test');
  27. }
  28. public function tearDown() {
  29. parent::tearDown();
  30. $this->connection->execute('DROP TABLE IF EXISTS things');
  31. $this->connection->useSavePoints(false);
  32. unset($this->connection);
  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['dsn']), 'Datasource has dsn, skipping.');
  106. $connection = new Connection(['database' => '_probably_not_there_'] + 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. $sql = "SELECT ? = '2012-01-01', ? = '2000-01-01 10:10:10', ? = 2";
  162. $params = [new \DateTime('2012-01-01 10:10:10'), '2000-01-01 10:10:10', 2.1];
  163. $statement = $this->connection->execute($sql, $params, ['date', 'string', 'integer']);
  164. $result = $statement->fetch();
  165. $statement->closeCursor();
  166. $this->assertEquals($result, array_filter($result));
  167. }
  168. /**
  169. * Tests that passing a unknown value to a query throws an exception
  170. *
  171. * @expectedException \InvalidArgumentException
  172. * @return void
  173. **/
  174. public function testExecuteWithMissingType() {
  175. $sql = 'SELECT ?';
  176. $statement = $this->connection->execute($sql, [new \DateTime('2012-01-01')], ['bar']);
  177. }
  178. /**
  179. * Tests executing a query with no params also works
  180. *
  181. * @return void
  182. **/
  183. public function testExecuteWithNoParams() {
  184. $sql = 'SELECT 1';
  185. $statement = $this->connection->execute($sql);
  186. $result = $statement->fetch();
  187. $this->assertCount(1, $result);
  188. $this->assertEquals([1], $result);
  189. $statement->closeCursor();
  190. }
  191. /**
  192. * Tests it is possible to insert data into a table using matching types by key name
  193. *
  194. * @return void
  195. **/
  196. public function testInsertWithMatchingTypes() {
  197. $table = 'CREATE TEMPORARY TABLE things(id int, title varchar(20), body varchar(50))';
  198. $this->connection->execute($table);
  199. $data = ['id' => '1', 'title' => 'a title', 'body' => 'a body'];
  200. $result = $this->connection->insert(
  201. 'things',
  202. $data,
  203. ['id' => 'integer', 'title' => 'string', 'body' => 'string']
  204. );
  205. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  206. $result = $this->connection->execute('SELECT * from things');
  207. $this->assertCount(1, $result);
  208. $row = $result->fetch('assoc');
  209. $this->assertEquals($data, $row);
  210. $result->closeCursor();
  211. }
  212. /**
  213. * Tests it is possible to insert data into a table using matching types by array position
  214. *
  215. * @return void
  216. **/
  217. public function testInsertWithPositionalTypes() {
  218. $table = 'CREATE TEMPORARY TABLE things(id int, title varchar(20), body varchar(50))';
  219. $this->connection->execute($table);
  220. $data = ['id' => '1', 'title' => 'a title', 'body' => 'a body'];
  221. $result = $this->connection->insert(
  222. 'things',
  223. $data,
  224. ['integer', 'string', 'string']
  225. );
  226. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  227. $result = $this->connection->execute('SELECT * from things');
  228. $this->assertCount(1, $result);
  229. $row = $result->fetch('assoc');
  230. $this->assertEquals($data, $row);
  231. $result->closeCursor();
  232. }
  233. /**
  234. * Auxiliary function to insert a couple rows in a newly created table
  235. *
  236. * @return void
  237. **/
  238. protected function _insertTwoRecords() {
  239. $table = 'CREATE TEMPORARY TABLE things(id int, title varchar(20), body varchar(50))';
  240. $this->connection->execute($table);
  241. $data = ['id' => '1', 'title' => 'a title', 'body' => 'a body'];
  242. $result = $this->connection->insert(
  243. 'things',
  244. $data,
  245. ['id' => 'integer', 'title' => 'string', 'body' => 'string']
  246. );
  247. $result->bindValue(1, '2', 'integer');
  248. $result->bindValue(2, 'another title');
  249. $result->bindValue(3, 'another body');
  250. $result->execute();
  251. }
  252. /**
  253. * Tests an statement class can be reused for multiple executions
  254. *
  255. * @return void
  256. **/
  257. public function testStatementReusing() {
  258. $this->_insertTwoRecords();
  259. $total = $this->connection->execute('SELECT COUNT(*) AS total FROM things');
  260. $result = $total->fetch('assoc');
  261. $this->assertEquals(2, $result['total']);
  262. $total->closeCursor();
  263. $result = $this->connection->execute('SELECT title, body FROM things');
  264. $row = $result->fetch('assoc');
  265. $this->assertEquals('a title', $row['title']);
  266. $this->assertEquals('a body', $row['body']);
  267. $row = $result->fetch('assoc');
  268. $result->closeCursor();
  269. $this->assertEquals('another title', $row['title']);
  270. $this->assertEquals('another body', $row['body']);
  271. }
  272. /**
  273. * Tests rows can be updated without specifying any conditions nor types
  274. *
  275. * @return void
  276. **/
  277. public function testUpdateWithoutConditionsNorTypes() {
  278. $this->_insertTwoRecords();
  279. $title = 'changed the title!';
  280. $body = 'changed the body!';
  281. $this->connection->update('things', ['title' => $title, 'body' => $body]);
  282. $result = $this->connection->execute('SELECT * FROM things WHERE title = ? AND body = ?', [$title, $body]);
  283. $this->assertCount(2, $result);
  284. $result->closeCursor();
  285. }
  286. /**
  287. * Tests it is possible to use key => value conditions for update
  288. *
  289. * @return void
  290. **/
  291. public function testUpdateWithConditionsNoTypes() {
  292. $this->_insertTwoRecords();
  293. $title = 'changed the title!';
  294. $body = 'changed the body!';
  295. $this->connection->update('things', ['title' => $title, 'body' => $body], ['id' => 2]);
  296. $result = $this->connection->execute('SELECT * FROM things WHERE title = ? AND body = ?', [$title, $body]);
  297. $this->assertCount(1, $result);
  298. $result->closeCursor();
  299. }
  300. /**
  301. * Tests it is possible to use key => value and string conditions for update
  302. *
  303. * @return void
  304. **/
  305. public function testUpdateWithConditionsCombinedNoTypes() {
  306. $this->_insertTwoRecords();
  307. $title = 'changed the title!';
  308. $body = 'changed the body!';
  309. $this->connection->update('things', ['title' => $title, 'body' => $body], ['id' => 2, 'body is not null']);
  310. $result = $this->connection->execute('SELECT * FROM things WHERE title = ? AND body = ?', [$title, $body]);
  311. $this->assertCount(1, $result);
  312. $result->closeCursor();
  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. $result->closeCursor();
  332. }
  333. /**
  334. * Tests you can bind types to update values
  335. *
  336. * @return void
  337. **/
  338. public function testUpdateWithConditionsAndTypes() {
  339. $this->_insertTwoRecords();
  340. $title = 'changed the title!';
  341. $body = new \DateTime('2012-01-01');
  342. $values = compact('title', 'body');
  343. $this->connection->update('things', $values, ['id' => '1-string-parsed-as-int'], ['body' => 'date', 'id' => 'integer']);
  344. $result = $this->connection->execute('SELECT * FROM things WHERE title = :title AND body = :body', $values, ['body' => 'date']);
  345. $this->assertCount(1, $result);
  346. $row = $result->fetch('assoc');
  347. $this->assertEquals('2012-01-01', $row['body']);
  348. $result->closeCursor();
  349. }
  350. /**
  351. * Tests delete from table with no conditions
  352. *
  353. * @return void
  354. **/
  355. public function testDeleteNoConditions() {
  356. $this->_insertTwoRecords();
  357. $this->connection->delete('things');
  358. $result = $this->connection->execute('SELECT * FROM things');
  359. $this->assertCount(0, $result);
  360. }
  361. /**
  362. * Tests delete from table with conditions
  363. * @return void
  364. **/
  365. public function testDeleteWithConditions() {
  366. $this->_insertTwoRecords();
  367. $this->connection->delete('things', ['id' => '1-rest-is-ommited'], ['id' => 'integer']);
  368. $result = $this->connection->execute('SELECT * FROM things');
  369. $this->assertCount(1, $result);
  370. $this->connection->delete('things', ['id' => '1-rest-is-ommited'], ['id' => 'integer']);
  371. $result = $this->connection->execute('SELECT * FROM things');
  372. $this->assertCount(1, $result);
  373. $this->connection->delete('things', ['id' => '2-rest-is-ommited'], ['id' => 'integer']);
  374. $result = $this->connection->execute('SELECT * FROM things');
  375. $this->assertCount(0, $result);
  376. }
  377. /**
  378. * Tests that it is possible to use simple database transactions
  379. *
  380. * @return void
  381. **/
  382. public function testSimpleTransactions() {
  383. $this->_insertTwoRecords();
  384. $this->connection->begin();
  385. $this->connection->delete('things', ['id' => 1]);
  386. $this->connection->rollback();
  387. $result = $this->connection->execute('SELECT * FROM things');
  388. $this->assertCount(2, $result);
  389. $this->connection->begin();
  390. $this->connection->delete('things', ['id' => 1]);
  391. $this->connection->commit();
  392. $result = $this->connection->execute('SELECT * FROM things');
  393. $this->assertCount(1, $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 testVirtualNestedTrasanction() {
  402. $this->_insertTwoRecords();
  403. //starting 3 virtual transaction
  404. $this->connection->begin();
  405. $this->connection->begin();
  406. $this->connection->begin();
  407. $this->connection->delete('things', ['id' => 1]);
  408. $result = $this->connection->execute('SELECT * FROM things');
  409. $this->assertCount(1, $result);
  410. $this->connection->commit();
  411. $this->connection->rollback();
  412. $result = $this->connection->execute('SELECT * FROM things');
  413. $this->assertCount(2, $result);
  414. }
  415. /**
  416. * Tests that it is possible to use virtualized nested transaction
  417. * with early rollback algorithm
  418. *
  419. * @return void
  420. **/
  421. public function testVirtualNestedTrasanction2() {
  422. $this->_insertTwoRecords();
  423. //starting 3 virtual transaction
  424. $this->connection->begin();
  425. $this->connection->begin();
  426. $this->connection->begin();
  427. $this->connection->delete('things', ['id' => 1]);
  428. $result = $this->connection->execute('SELECT * FROM things');
  429. $this->assertCount(1, $result);
  430. $this->connection->rollback();
  431. $result = $this->connection->execute('SELECT * FROM things');
  432. $this->assertCount(2, $result);
  433. }
  434. /**
  435. * Tests that it is possible to use virtualized nested transaction
  436. * with early rollback algorithm
  437. *
  438. * @return void
  439. **/
  440. public function testVirtualNestedTrasanction3() {
  441. $this->_insertTwoRecords();
  442. //starting 3 virtual transaction
  443. $this->connection->begin();
  444. $this->connection->begin();
  445. $this->connection->begin();
  446. $this->connection->delete('things', ['id' => 1]);
  447. $result = $this->connection->execute('SELECT * FROM things');
  448. $this->assertCount(1, $result);
  449. $this->connection->commit();
  450. $this->connection->commit();
  451. $this->connection->commit();
  452. $result = $this->connection->execute('SELECT * FROM things');
  453. $this->assertCount(1, $result);
  454. }
  455. /**
  456. * Tests that it is possible to real use nested transactions
  457. *
  458. * @return void
  459. **/
  460. public function testSavePoints() {
  461. $this->skipIf(!$this->connection->useSavePoints(true));
  462. $this->_insertTwoRecords();
  463. $this->connection->begin();
  464. $this->connection->delete('things', ['id' => 1]);
  465. $result = $this->connection->execute('SELECT * FROM things');
  466. $this->assertCount(1, $result);
  467. $this->connection->begin();
  468. $this->connection->delete('things', ['id' => 2]);
  469. $result = $this->connection->execute('SELECT * FROM things');
  470. $this->assertCount(0, $result);
  471. $this->connection->rollback();
  472. $result = $this->connection->execute('SELECT * FROM things');
  473. $this->assertCount(1, $result);
  474. $this->connection->rollback();
  475. $result = $this->connection->execute('SELECT * FROM things');
  476. $this->assertCount(2, $result);
  477. }
  478. /**
  479. * Tests that it is possible to real use nested transactions
  480. *
  481. * @return void
  482. **/
  483. public function testSavePoints2() {
  484. $this->skipIf(!$this->connection->useSavePoints(true));
  485. $this->_insertTwoRecords();
  486. $this->connection->begin();
  487. $this->connection->delete('things', ['id' => 1]);
  488. $result = $this->connection->execute('SELECT * FROM things');
  489. $this->assertCount(1, $result);
  490. $this->connection->begin();
  491. $this->connection->delete('things', ['id' => 2]);
  492. $result = $this->connection->execute('SELECT * FROM things');
  493. $this->assertCount(0, $result);
  494. $this->connection->rollback();
  495. $result = $this->connection->execute('SELECT * FROM things');
  496. $this->assertCount(1, $result);
  497. $this->connection->commit();
  498. $result = $this->connection->execute('SELECT * FROM things');
  499. $this->assertCount(1, $result);
  500. }
  501. /**
  502. * Tests connection can quote values to be safely used in query strings
  503. *
  504. * @return void
  505. **/
  506. public function testQuote() {
  507. $this->skipIf(!$this->connection->supportsQuoting());
  508. $expected = "'2012-01-01'";
  509. $result = $this->connection->quote(new \DateTime('2012-01-01'), 'date');
  510. $this->assertEquals($expected, $result);
  511. $expected = "'1'";
  512. $result = $this->connection->quote(1, 'string');
  513. $this->assertEquals($expected, $result);
  514. $expected = "'hello'";
  515. $result = $this->connection->quote('hello', 'string');
  516. $this->assertEquals($expected, $result);
  517. }
  518. /**
  519. * Tests identifier quoting
  520. *
  521. * @return void
  522. */
  523. public function testQuoteIdentifier() {
  524. $driver = $this->getMock('Cake\Database\Driver\Sqlite', ['enabled']);
  525. $driver->expects($this->once())
  526. ->method('enabled')
  527. ->will($this->returnValue(true));
  528. $connection = new Connection(['driver' => $driver]);
  529. $result = $connection->quoteIdentifier('name');
  530. $expected = '"name"';
  531. $this->assertEquals($expected, $result);
  532. $result = $connection->quoteIdentifier('Model.*');
  533. $expected = '"Model".*';
  534. $this->assertEquals($expected, $result);
  535. $result = $connection->quoteIdentifier('MTD()');
  536. $expected = 'MTD()';
  537. $this->assertEquals($expected, $result);
  538. $result = $connection->quoteIdentifier('(sm)');
  539. $expected = '(sm)';
  540. $this->assertEquals($expected, $result);
  541. $result = $connection->quoteIdentifier('name AS x');
  542. $expected = '"name" AS "x"';
  543. $this->assertEquals($expected, $result);
  544. $result = $connection->quoteIdentifier('Model.name AS x');
  545. $expected = '"Model"."name" AS "x"';
  546. $this->assertEquals($expected, $result);
  547. $result = $connection->quoteIdentifier('Function(Something.foo)');
  548. $expected = 'Function("Something"."foo")';
  549. $this->assertEquals($expected, $result);
  550. $result = $connection->quoteIdentifier('Function(SubFunction(Something.foo))');
  551. $expected = 'Function(SubFunction("Something"."foo"))';
  552. $this->assertEquals($expected, $result);
  553. $result = $connection->quoteIdentifier('Function(Something.foo) AS x');
  554. $expected = 'Function("Something"."foo") AS "x"';
  555. $this->assertEquals($expected, $result);
  556. $result = $connection->quoteIdentifier('name-with-minus');
  557. $expected = '"name-with-minus"';
  558. $this->assertEquals($expected, $result);
  559. $result = $connection->quoteIdentifier('my-name');
  560. $expected = '"my-name"';
  561. $this->assertEquals($expected, $result);
  562. $result = $connection->quoteIdentifier('Foo-Model.*');
  563. $expected = '"Foo-Model".*';
  564. $this->assertEquals($expected, $result);
  565. $result = $connection->quoteIdentifier('Team.P%');
  566. $expected = '"Team"."P%"';
  567. $this->assertEquals($expected, $result);
  568. $result = $connection->quoteIdentifier('Team.G/G');
  569. $expected = '"Team"."G/G"';
  570. $result = $connection->quoteIdentifier('Model.name as y');
  571. $expected = '"Model"."name" AS "y"';
  572. $this->assertEquals($expected, $result);
  573. }
  574. /**
  575. * Tests default return vale for logger() function
  576. *
  577. * @return void
  578. */
  579. public function testLoggerDefault() {
  580. $logger = $this->connection->logger();
  581. $this->assertInstanceOf('\Cake\Database\Log\QueryLogger', $logger);
  582. $this->assertSame($logger, $this->connection->logger());
  583. }
  584. /**
  585. * Tests that a custom logger object can be set
  586. *
  587. * @return void
  588. */
  589. public function testSetLogger() {
  590. $logger = new \Cake\Database\Log\QueryLogger;
  591. $this->connection->logger($logger);
  592. $this->assertSame($logger, $this->connection->logger());
  593. }
  594. /**
  595. * Tests that statements are decorated with a logger when logQueries is set to true
  596. *
  597. * @return void
  598. */
  599. public function testLoggerDecorator() {
  600. $logger = new \Cake\Database\Log\QueryLogger;
  601. $this->connection->logQueries(true);
  602. $this->connection->logger($logger);
  603. $st = $this->connection->prepare('SELECT 1');
  604. $this->assertInstanceOf('\Cake\Database\Log\LoggingStatement', $st);
  605. $this->assertSame($logger, $st->logger());
  606. $this->connection->logQueries(false);
  607. $st = $this->connection->prepare('SELECT 1');
  608. $this->assertNotInstanceOf('\Cake\Database\Log\LoggingStatement', $st);
  609. }
  610. /**
  611. * Tests that log() function logs to the configured query logger
  612. *
  613. * @return void
  614. */
  615. public function testLogFunction() {
  616. $logger = $this->getMock('\Cake\Database\Log\QueryLogger');
  617. $this->connection->logger($logger);
  618. $logger->expects($this->once())->method('log')
  619. ->with($this->logicalAnd(
  620. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  621. $this->attributeEqualTo('query', 'SELECT 1')
  622. ));
  623. $this->connection->log('SELECT 1');
  624. }
  625. /**
  626. * Tests that begin and rollback are also logged
  627. *
  628. * @return void
  629. */
  630. public function testLogBeginRollbackTransaction() {
  631. $connection = $this
  632. ->getMockBuilder('\Cake\Database\Connection')
  633. ->setMethods(['connect'])
  634. ->disableOriginalConstructor()
  635. ->getMock();
  636. $connection->logQueries(true);
  637. $driver = $this->getMockFormDriver();
  638. $connection->driver($driver);
  639. $logger = $this->getMock('\Cake\Database\Log\QueryLogger');
  640. $connection->logger($logger);
  641. $logger->expects($this->at(0))->method('log')
  642. ->with($this->logicalAnd(
  643. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  644. $this->attributeEqualTo('query', 'BEGIN')
  645. ));
  646. $logger->expects($this->at(1))->method('log')
  647. ->with($this->logicalAnd(
  648. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  649. $this->attributeEqualTo('query', 'ROLLBACK')
  650. ));
  651. $connection->begin();
  652. $connection->begin(); //This one will not be logged
  653. $connection->rollback();
  654. }
  655. /**
  656. * Tests that commits are logged
  657. *
  658. * @return void
  659. */
  660. public function testLogCommitTransaction() {
  661. $driver = $this->getMockFormDriver();
  662. $connection = $this->getMock(
  663. '\Cake\Database\Connection',
  664. ['connect'],
  665. [['driver' => $driver]]
  666. );
  667. $logger = $this->getMock('\Cake\Database\Log\QueryLogger');
  668. $connection->logger($logger);
  669. $logger->expects($this->at(1))->method('log')
  670. ->with($this->logicalAnd(
  671. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  672. $this->attributeEqualTo('query', 'COMMIT')
  673. ));
  674. $connection->logQueries(true);
  675. $connection->begin();
  676. $connection->commit();
  677. }
  678. /**
  679. * Tests that the transactional method will start and commit a transaction
  680. * around some arbitrary function passed as argument
  681. *
  682. * @return void
  683. */
  684. public function testTransactionalSuccess() {
  685. $driver = $this->getMockFormDriver();
  686. $connection = $this->getMock(
  687. '\Cake\Database\Connection',
  688. ['connect', 'commit', 'begin'],
  689. [['driver' => $driver]]
  690. );
  691. $connection->expects($this->at(0))->method('begin');
  692. $connection->expects($this->at(1))->method('commit');
  693. $result = $connection->transactional(function($conn) use ($connection) {
  694. $this->assertSame($connection, $conn);
  695. return 'thing';
  696. });
  697. $this->assertEquals('thing', $result);
  698. }
  699. /**
  700. * Tests that the transactional method will rollback the transaction if false
  701. * is returned from the callback
  702. *
  703. * @return void
  704. */
  705. public function testTransactionalFail() {
  706. $driver = $this->getMockFormDriver();
  707. $connection = $this->getMock(
  708. '\Cake\Database\Connection',
  709. ['connect', 'commit', 'begin', 'rollback'],
  710. [['driver' => $driver]]
  711. );
  712. $connection->expects($this->at(0))->method('begin');
  713. $connection->expects($this->at(1))->method('rollback');
  714. $connection->expects($this->never())->method('commit');
  715. $result = $connection->transactional(function($conn) use ($connection) {
  716. $this->assertSame($connection, $conn);
  717. return false;
  718. });
  719. $this->assertFalse($result);
  720. }
  721. /**
  722. * Tests that the transactional method will rollback the transaction
  723. * and throw the same exception if the callback raises one
  724. *
  725. * @expectedException \InvalidArgumentException
  726. * @return void
  727. * @throws \InvalidArgumentException
  728. */
  729. public function testTransactionalWithException() {
  730. $driver = $this->getMockFormDriver();
  731. $connection = $this->getMock(
  732. '\Cake\Database\Connection',
  733. ['connect', 'commit', 'begin', 'rollback'],
  734. [['driver' => $driver]]
  735. );
  736. $connection->expects($this->at(0))->method('begin');
  737. $connection->expects($this->at(1))->method('rollback');
  738. $connection->expects($this->never())->method('commit');
  739. $connection->transactional(function($conn) use ($connection) {
  740. $this->assertSame($connection, $conn);
  741. throw new \InvalidArgumentException;
  742. });
  743. }
  744. }