ConnectionTest.php 43 KB

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