ConnectionTest.php 38 KB

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