ConnectionTest.php 32 KB

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