ConnectionTest.php 42 KB

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