ConnectionTest.php 32 KB

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