ConnectionTest.php 39 KB

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