ConnectionTest.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  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\Database\Log\LoggingStatement;
  20. use Cake\Database\Log\QueryLogger;
  21. use Cake\Datasource\ConnectionManager;
  22. use Cake\TestSuite\TestCase;
  23. use ReflectionMethod;
  24. /**
  25. * Tests Connection class
  26. */
  27. class ConnectionTest extends TestCase
  28. {
  29. public $fixtures = ['core.things'];
  30. /**
  31. * Where the NestedTransactionRollbackException was created.
  32. *
  33. * @var int
  34. */
  35. protected $rollbackSourceLine = -1;
  36. /**
  37. * Internal states of nested transaction.
  38. *
  39. * @var array
  40. */
  41. protected $nestedTransactionStates = [];
  42. public function setUp()
  43. {
  44. parent::setUp();
  45. $this->connection = ConnectionManager::get('test');
  46. static::setAppNamespace();
  47. }
  48. public function tearDown()
  49. {
  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->getDriver());
  135. $connection = new Connection(['driver' => 'TestPlugin.TestDriver']);
  136. $this->assertInstanceOf('\TestPlugin\Database\Driver\TestDriver', $connection->getDriver());
  137. list(, $name) = namespaceSplit(get_class($this->connection->getDriver()));
  138. $connection = new Connection(['driver' => $name]);
  139. $this->assertInstanceOf(get_class($this->connection->getDriver()), $connection->getDriver());
  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::getConfig('test');
  150. $this->skipIf(isset($config['url']), 'Datasource has dsn, skipping.');
  151. $connection = new Connection(['database' => '/dev/nonexistent'] + ConnectionManager::getConfig('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 it is possible to use virtualized nested transaction
  448. * with early rollback algorithm
  449. *
  450. * @return void
  451. */
  452. public function testVirtualNestedTransaction()
  453. {
  454. //starting 3 virtual transaction
  455. $this->connection->begin();
  456. $this->connection->begin();
  457. $this->connection->begin();
  458. $this->connection->delete('things', ['id' => 1]);
  459. $result = $this->connection->execute('SELECT * FROM things');
  460. $this->assertCount(1, $result);
  461. $this->connection->commit();
  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 testVirtualNestedTransaction2()
  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->rollback();
  482. $result = $this->connection->execute('SELECT * FROM things');
  483. $this->assertCount(2, $result);
  484. }
  485. /**
  486. * Tests that it is possible to use virtualized nested transaction
  487. * with early rollback algorithm
  488. *
  489. * @return void
  490. */
  491. public function testVirtualNestedTransaction3()
  492. {
  493. //starting 3 virtual transaction
  494. $this->connection->begin();
  495. $this->connection->begin();
  496. $this->connection->begin();
  497. $this->connection->delete('things', ['id' => 1]);
  498. $result = $this->connection->execute('SELECT * FROM things');
  499. $this->assertCount(1, $result);
  500. $this->connection->commit();
  501. $this->connection->commit();
  502. $this->connection->commit();
  503. $result = $this->connection->execute('SELECT * FROM things');
  504. $this->assertCount(1, $result);
  505. }
  506. /**
  507. * Tests that it is possible to real use nested transactions
  508. *
  509. * @return void
  510. */
  511. public function testSavePoints()
  512. {
  513. $this->skipIf(!$this->connection->useSavePoints(true));
  514. $this->connection->begin();
  515. $this->connection->delete('things', ['id' => 1]);
  516. $result = $this->connection->execute('SELECT * FROM things');
  517. $this->assertCount(1, $result);
  518. $this->connection->begin();
  519. $this->connection->delete('things', ['id' => 2]);
  520. $result = $this->connection->execute('SELECT * FROM things');
  521. $this->assertCount(0, $result);
  522. $this->connection->rollback();
  523. $result = $this->connection->execute('SELECT * FROM things');
  524. $this->assertCount(1, $result);
  525. $this->connection->rollback();
  526. $result = $this->connection->execute('SELECT * FROM things');
  527. $this->assertCount(2, $result);
  528. }
  529. /**
  530. * Tests that it is possible to real use nested transactions
  531. *
  532. * @return void
  533. */
  534. public function testSavePoints2()
  535. {
  536. $this->skipIf(!$this->connection->useSavePoints(true));
  537. $this->connection->begin();
  538. $this->connection->delete('things', ['id' => 1]);
  539. $result = $this->connection->execute('SELECT * FROM things');
  540. $this->assertCount(1, $result);
  541. $this->connection->begin();
  542. $this->connection->delete('things', ['id' => 2]);
  543. $result = $this->connection->execute('SELECT * FROM things');
  544. $this->assertCount(0, $result);
  545. $this->connection->rollback();
  546. $result = $this->connection->execute('SELECT * FROM things');
  547. $this->assertCount(1, $result);
  548. $this->connection->commit();
  549. $result = $this->connection->execute('SELECT * FROM things');
  550. $this->assertCount(1, $result);
  551. }
  552. /**
  553. * Tests inTransaction()
  554. *
  555. * @return void
  556. */
  557. public function testInTransaction()
  558. {
  559. $this->connection->begin();
  560. $this->assertTrue($this->connection->inTransaction());
  561. $this->connection->begin();
  562. $this->assertTrue($this->connection->inTransaction());
  563. $this->connection->commit();
  564. $this->assertTrue($this->connection->inTransaction());
  565. $this->connection->commit();
  566. $this->assertFalse($this->connection->inTransaction());
  567. $this->connection->begin();
  568. $this->assertTrue($this->connection->inTransaction());
  569. $this->connection->begin();
  570. $this->connection->rollback();
  571. $this->assertFalse($this->connection->inTransaction());
  572. }
  573. /**
  574. * Tests inTransaction() with save points
  575. *
  576. * @return void
  577. */
  578. public function testInTransactionWithSavePoints()
  579. {
  580. $this->skipIf(
  581. $this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver,
  582. 'SQLServer fails when this test is included.'
  583. );
  584. $this->skipIf(!$this->connection->useSavePoints(true));
  585. $this->connection->begin();
  586. $this->assertTrue($this->connection->inTransaction());
  587. $this->connection->begin();
  588. $this->assertTrue($this->connection->inTransaction());
  589. $this->connection->commit();
  590. $this->assertTrue($this->connection->inTransaction());
  591. $this->connection->commit();
  592. $this->assertFalse($this->connection->inTransaction());
  593. $this->connection->begin();
  594. $this->assertTrue($this->connection->inTransaction());
  595. $this->connection->begin();
  596. $this->connection->rollback();
  597. $this->assertTrue($this->connection->inTransaction());
  598. $this->connection->rollback();
  599. $this->assertFalse($this->connection->inTransaction());
  600. }
  601. /**
  602. * Tests connection can quote values to be safely used in query strings
  603. *
  604. * @return void
  605. */
  606. public function testQuote()
  607. {
  608. $this->skipIf(!$this->connection->supportsQuoting());
  609. $expected = "'2012-01-01'";
  610. $result = $this->connection->quote(new \DateTime('2012-01-01'), 'date');
  611. $this->assertEquals($expected, $result);
  612. $expected = "'1'";
  613. $result = $this->connection->quote(1, 'string');
  614. $this->assertEquals($expected, $result);
  615. $expected = "'hello'";
  616. $result = $this->connection->quote('hello', 'string');
  617. $this->assertEquals($expected, $result);
  618. }
  619. /**
  620. * Tests identifier quoting
  621. *
  622. * @return void
  623. */
  624. public function testQuoteIdentifier()
  625. {
  626. $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlite')
  627. ->setMethods(['enabled'])
  628. ->getMock();
  629. $driver->expects($this->once())
  630. ->method('enabled')
  631. ->will($this->returnValue(true));
  632. $connection = new Connection(['driver' => $driver]);
  633. $result = $connection->quoteIdentifier('name');
  634. $expected = '"name"';
  635. $this->assertEquals($expected, $result);
  636. $result = $connection->quoteIdentifier('Model.*');
  637. $expected = '"Model".*';
  638. $this->assertEquals($expected, $result);
  639. $result = $connection->quoteIdentifier('MTD()');
  640. $expected = 'MTD()';
  641. $this->assertEquals($expected, $result);
  642. $result = $connection->quoteIdentifier('(sm)');
  643. $expected = '(sm)';
  644. $this->assertEquals($expected, $result);
  645. $result = $connection->quoteIdentifier('name AS x');
  646. $expected = '"name" AS "x"';
  647. $this->assertEquals($expected, $result);
  648. $result = $connection->quoteIdentifier('Model.name AS x');
  649. $expected = '"Model"."name" AS "x"';
  650. $this->assertEquals($expected, $result);
  651. $result = $connection->quoteIdentifier('Function(Something.foo)');
  652. $expected = 'Function("Something"."foo")';
  653. $this->assertEquals($expected, $result);
  654. $result = $connection->quoteIdentifier('Function(SubFunction(Something.foo))');
  655. $expected = 'Function(SubFunction("Something"."foo"))';
  656. $this->assertEquals($expected, $result);
  657. $result = $connection->quoteIdentifier('Function(Something.foo) AS x');
  658. $expected = 'Function("Something"."foo") AS "x"';
  659. $this->assertEquals($expected, $result);
  660. $result = $connection->quoteIdentifier('name-with-minus');
  661. $expected = '"name-with-minus"';
  662. $this->assertEquals($expected, $result);
  663. $result = $connection->quoteIdentifier('my-name');
  664. $expected = '"my-name"';
  665. $this->assertEquals($expected, $result);
  666. $result = $connection->quoteIdentifier('Foo-Model.*');
  667. $expected = '"Foo-Model".*';
  668. $this->assertEquals($expected, $result);
  669. $result = $connection->quoteIdentifier('Team.P%');
  670. $expected = '"Team"."P%"';
  671. $this->assertEquals($expected, $result);
  672. $result = $connection->quoteIdentifier('Team.G/G');
  673. $expected = '"Team"."G/G"';
  674. $result = $connection->quoteIdentifier('Model.name as y');
  675. $expected = '"Model"."name" AS "y"';
  676. $this->assertEquals($expected, $result);
  677. }
  678. /**
  679. * Tests default return vale for logger() function
  680. *
  681. * @return void
  682. */
  683. public function testLoggerDefault()
  684. {
  685. $logger = $this->connection->logger();
  686. $this->assertInstanceOf('Cake\Database\Log\QueryLogger', $logger);
  687. $this->assertSame($logger, $this->connection->logger());
  688. }
  689. /**
  690. * Tests that a custom logger object can be set
  691. *
  692. * @return void
  693. */
  694. public function testSetLogger()
  695. {
  696. $logger = new QueryLogger;
  697. $this->connection->logger($logger);
  698. $this->assertSame($logger, $this->connection->logger());
  699. }
  700. /**
  701. * Tests setting and getting the logger object
  702. *
  703. * @return void
  704. */
  705. public function testGetAndSetLogger()
  706. {
  707. $logger = new QueryLogger();
  708. $this->connection->setLogger($logger);
  709. $this->assertSame($logger, $this->connection->getLogger());
  710. }
  711. /**
  712. * Tests that statements are decorated with a logger when logQueries is set to true
  713. *
  714. * @return void
  715. */
  716. public function testLoggerDecorator()
  717. {
  718. $logger = new QueryLogger;
  719. $this->connection->logQueries(true);
  720. $this->connection->logger($logger);
  721. $st = $this->connection->prepare('SELECT 1');
  722. $this->assertInstanceOf(LoggingStatement::class, $st);
  723. $this->assertSame($logger, $st->logger());
  724. $this->connection->logQueries(false);
  725. $st = $this->connection->prepare('SELECT 1');
  726. $this->assertNotInstanceOf('\Cake\Database\Log\LoggingStatement', $st);
  727. }
  728. /**
  729. * test logQueries method
  730. *
  731. * @return void
  732. */
  733. public function testLogQueries()
  734. {
  735. $this->connection->logQueries(true);
  736. $this->assertTrue($this->connection->logQueries());
  737. $this->connection->logQueries(false);
  738. $this->assertFalse($this->connection->logQueries());
  739. }
  740. /**
  741. * Tests that log() function logs to the configured query logger
  742. *
  743. * @return void
  744. */
  745. public function testLogFunction()
  746. {
  747. $logger = $this->getMockBuilder(QueryLogger::class)->getMock();
  748. $this->connection->logger($logger);
  749. $logger->expects($this->once())->method('log')
  750. ->with($this->logicalAnd(
  751. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  752. $this->attributeEqualTo('query', 'SELECT 1')
  753. ));
  754. $this->connection->log('SELECT 1');
  755. }
  756. /**
  757. * Tests that begin and rollback are also logged
  758. *
  759. * @return void
  760. */
  761. public function testLogBeginRollbackTransaction()
  762. {
  763. $connection = $this
  764. ->getMockBuilder(Connection::class)
  765. ->setMethods(['connect'])
  766. ->disableOriginalConstructor()
  767. ->getMock();
  768. $connection->logQueries(true);
  769. $driver = $this->getMockFormDriver();
  770. $connection->driver($driver);
  771. $logger = $this->getMockBuilder(QueryLogger::class)->getMock();
  772. $connection->logger($logger);
  773. $logger->expects($this->at(0))->method('log')
  774. ->with($this->logicalAnd(
  775. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  776. $this->attributeEqualTo('query', 'BEGIN')
  777. ));
  778. $logger->expects($this->at(1))->method('log')
  779. ->with($this->logicalAnd(
  780. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  781. $this->attributeEqualTo('query', 'ROLLBACK')
  782. ));
  783. $connection->begin();
  784. $connection->begin(); //This one will not be logged
  785. $connection->rollback();
  786. }
  787. /**
  788. * Tests that commits are logged
  789. *
  790. * @return void
  791. */
  792. public function testLogCommitTransaction()
  793. {
  794. $driver = $this->getMockFormDriver();
  795. $connection = $this->getMockBuilder(Connection::class)
  796. ->setMethods(['connect'])
  797. ->setConstructorArgs([['driver' => $driver]])
  798. ->getMock();
  799. $logger = $this->getMockBuilder(QueryLogger::class)->getMock();
  800. $connection->logger($logger);
  801. $logger->expects($this->at(1))->method('log')
  802. ->with($this->logicalAnd(
  803. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  804. $this->attributeEqualTo('query', 'COMMIT')
  805. ));
  806. $connection->logQueries(true);
  807. $connection->begin();
  808. $connection->commit();
  809. }
  810. /**
  811. * Tests that the transactional method will start and commit a transaction
  812. * around some arbitrary function passed as argument
  813. *
  814. * @return void
  815. */
  816. public function testTransactionalSuccess()
  817. {
  818. $driver = $this->getMockFormDriver();
  819. $connection = $this->getMockBuilder(Connection::class)
  820. ->setMethods(['connect', 'commit', 'begin'])
  821. ->setConstructorArgs([['driver' => $driver]])
  822. ->getMock();
  823. $connection->expects($this->at(0))->method('begin');
  824. $connection->expects($this->at(1))->method('commit');
  825. $result = $connection->transactional(function ($conn) use ($connection) {
  826. $this->assertSame($connection, $conn);
  827. return 'thing';
  828. });
  829. $this->assertEquals('thing', $result);
  830. }
  831. /**
  832. * Tests that the transactional method will rollback the transaction if false
  833. * is returned from the callback
  834. *
  835. * @return void
  836. */
  837. public function testTransactionalFail()
  838. {
  839. $driver = $this->getMockFormDriver();
  840. $connection = $this->getMockBuilder(Connection::class)
  841. ->setMethods(['connect', 'commit', 'begin', 'rollback'])
  842. ->setConstructorArgs([['driver' => $driver]])
  843. ->getMock();
  844. $connection->expects($this->at(0))->method('begin');
  845. $connection->expects($this->at(1))->method('rollback');
  846. $connection->expects($this->never())->method('commit');
  847. $result = $connection->transactional(function ($conn) use ($connection) {
  848. $this->assertSame($connection, $conn);
  849. return false;
  850. });
  851. $this->assertFalse($result);
  852. }
  853. /**
  854. * Tests that the transactional method will rollback the transaction
  855. * and throw the same exception if the callback raises one
  856. *
  857. * @expectedException \InvalidArgumentException
  858. * @return void
  859. * @throws \InvalidArgumentException
  860. */
  861. public function testTransactionalWithException()
  862. {
  863. $driver = $this->getMockFormDriver();
  864. $connection = $this->getMockBuilder(Connection::class)
  865. ->setMethods(['connect', 'commit', 'begin', 'rollback'])
  866. ->setConstructorArgs([['driver' => $driver]])
  867. ->getMock();
  868. $connection->expects($this->at(0))->method('begin');
  869. $connection->expects($this->at(1))->method('rollback');
  870. $connection->expects($this->never())->method('commit');
  871. $connection->transactional(function ($conn) use ($connection) {
  872. $this->assertSame($connection, $conn);
  873. throw new \InvalidArgumentException;
  874. });
  875. }
  876. /**
  877. * Tests it is possible to set a schema collection object
  878. *
  879. * @return void
  880. */
  881. public function testSchemaCollection()
  882. {
  883. $driver = $this->getMockFormDriver();
  884. $connection = $this->getMockBuilder(Connection::class)
  885. ->setMethods(['connect'])
  886. ->setConstructorArgs([['driver' => $driver]])
  887. ->getMock();
  888. $schema = $connection->schemaCollection();
  889. $this->assertInstanceOf('Cake\Database\Schema\Collection', $schema);
  890. $schema = $this->getMockBuilder('Cake\Database\Schema\Collection')
  891. ->setConstructorArgs([$connection])
  892. ->getMock();
  893. $connection->schemaCollection($schema);
  894. $this->assertSame($schema, $connection->schemaCollection());
  895. }
  896. /**
  897. * Tests that allowed nesting of commit/rollback operations doesn't
  898. * throw any exceptions.
  899. *
  900. * @return void
  901. */
  902. public function testNestedTransactionRollbackExceptionNotThrown()
  903. {
  904. $this->connection->transactional(function () {
  905. $this->connection->transactional(function () {
  906. return true;
  907. });
  908. return true;
  909. });
  910. $this->assertFalse($this->connection->inTransaction());
  911. $this->connection->transactional(function () {
  912. $this->connection->transactional(function () {
  913. return true;
  914. });
  915. return false;
  916. });
  917. $this->assertFalse($this->connection->inTransaction());
  918. $this->connection->transactional(function () {
  919. $this->connection->transactional(function () {
  920. return false;
  921. });
  922. return false;
  923. });
  924. $this->assertFalse($this->connection->inTransaction());
  925. }
  926. /**
  927. * Tests that not allowed nesting of commit/rollback operations throws
  928. * a NestedTransactionRollbackException.
  929. *
  930. * @return void
  931. */
  932. public function testNestedTransactionRollbackExceptionThrown()
  933. {
  934. $this->rollbackSourceLine = -1;
  935. $e = null;
  936. try {
  937. $this->connection->transactional(function () {
  938. $this->connection->transactional(function () {
  939. return false;
  940. });
  941. $this->rollbackSourceLine = __LINE__ - 1;
  942. return true;
  943. });
  944. $this->fail('NestedTransactionRollbackException should be thrown');
  945. } catch (NestedTransactionRollbackException $e) {
  946. }
  947. $trace = $e->getTrace();
  948. $this->assertEquals(__FILE__, $trace[1]['file']);
  949. $this->assertEquals($this->rollbackSourceLine, $trace[1]['line']);
  950. }
  951. /**
  952. * Tests more detail about that not allowed nesting of rollback/commit
  953. * operations throws a NestedTransactionRollbackException.
  954. *
  955. * @return void
  956. */
  957. public function testNestedTransactionStates()
  958. {
  959. $this->rollbackSourceLine = -1;
  960. $this->nestedTransactionStates = [];
  961. $e = null;
  962. try {
  963. $this->connection->transactional(function () {
  964. $this->pushNestedTransactionState();
  965. $this->connection->transactional(function () {
  966. return true;
  967. });
  968. $this->connection->transactional(function () {
  969. $this->pushNestedTransactionState();
  970. $this->connection->transactional(function () {
  971. return false;
  972. });
  973. $this->rollbackSourceLine = __LINE__ - 1;
  974. $this->pushNestedTransactionState();
  975. return true;
  976. });
  977. $this->connection->transactional(function () {
  978. return false;
  979. });
  980. $this->pushNestedTransactionState();
  981. return true;
  982. });
  983. $this->fail('NestedTransactionRollbackException should be thrown');
  984. } catch (NestedTransactionRollbackException $e) {
  985. }
  986. $this->pushNestedTransactionState();
  987. $this->assertSame([false, false, true, true, false], $this->nestedTransactionStates);
  988. $this->assertFalse($this->connection->inTransaction());
  989. $trace = $e->getTrace();
  990. $this->assertEquals(__FILE__, $trace[1]['file']);
  991. $this->assertEquals($this->rollbackSourceLine, $trace[1]['line']);
  992. }
  993. /**
  994. * Helper method to trace nested transaction states.
  995. *
  996. * @return void
  997. */
  998. public function pushNestedTransactionState()
  999. {
  1000. $method = new ReflectionMethod($this->connection, 'wasNestedTransactionRolledback');
  1001. $method->setAccessible(true);
  1002. $this->nestedTransactionStates[] = $method->invoke($this->connection);
  1003. }
  1004. }