ConnectionTest.php 33 KB

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