ConnectionTest.php 37 KB

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