ConnectionTest.php 31 KB

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