ConnectionTest.php 43 KB

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