ConnectionTest.php 44 KB

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