ConnectionTest.php 32 KB

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