ConnectionTest.php 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365
  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->disableSavePoints();
  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|\PHPUnit_Framework_MockObject_MockObject
  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'], ['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'], ['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'], ['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'], ['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. $this->assertEquals($expected, $result);
  745. $result = $connection->quoteIdentifier('Model.name as y');
  746. $expected = '"Model"."name" AS "y"';
  747. $this->assertEquals($expected, $result);
  748. $result = $connection->quoteIdentifier('nämé');
  749. $expected = '"nämé"';
  750. $this->assertEquals($expected, $result);
  751. $result = $connection->quoteIdentifier('aßa.nämé');
  752. $expected = '"aßa"."nämé"';
  753. $this->assertEquals($expected, $result);
  754. $result = $connection->quoteIdentifier('aßa.*');
  755. $expected = '"aßa".*';
  756. $this->assertEquals($expected, $result);
  757. $result = $connection->quoteIdentifier('Modeß.nämé as y');
  758. $expected = '"Modeß"."nämé" AS "y"';
  759. $this->assertEquals($expected, $result);
  760. $result = $connection->quoteIdentifier('Model.näme Datum as y');
  761. $expected = '"Model"."näme Datum" AS "y"';
  762. $this->assertEquals($expected, $result);
  763. }
  764. /**
  765. * Tests default return vale for logger() function
  766. *
  767. * @return void
  768. */
  769. public function testGetLoggerDefault()
  770. {
  771. $logger = $this->connection->getLogger();
  772. $this->assertInstanceOf('Cake\Database\Log\QueryLogger', $logger);
  773. $this->assertSame($logger, $this->connection->getLogger());
  774. }
  775. /**
  776. * Tests that a custom logger object can be set
  777. *
  778. * @group deprecated
  779. * @return void
  780. */
  781. public function testSetLogger()
  782. {
  783. $this->deprecated(function () {
  784. $logger = new QueryLogger();
  785. $this->connection->logger($logger);
  786. $this->assertSame($logger, $this->connection->logger());
  787. });
  788. }
  789. /**
  790. * Tests setting and getting the logger object
  791. *
  792. * @return void
  793. */
  794. public function testGetAndSetLogger()
  795. {
  796. $logger = new QueryLogger();
  797. $this->connection->setLogger($logger);
  798. $this->assertSame($logger, $this->connection->getLogger());
  799. }
  800. /**
  801. * Tests that statements are decorated with a logger when logQueries is set to true
  802. *
  803. * @return void
  804. */
  805. public function testLoggerDecorator()
  806. {
  807. $logger = new QueryLogger();
  808. $this->connection->enableQueryLogging(true);
  809. $this->connection->setLogger($logger);
  810. $st = $this->connection->prepare('SELECT 1');
  811. $this->assertInstanceOf(LoggingStatement::class, $st);
  812. $this->assertSame($logger, $st->getLogger());
  813. $this->connection->enableQueryLogging(false);
  814. $st = $this->connection->prepare('SELECT 1');
  815. $this->assertNotInstanceOf('\Cake\Database\Log\LoggingStatement', $st);
  816. }
  817. /**
  818. * test logQueries method
  819. *
  820. * @deprecated
  821. * @return void
  822. */
  823. public function testLogQueries()
  824. {
  825. $this->deprecated(function () {
  826. $this->connection->logQueries(true);
  827. $this->assertTrue($this->connection->logQueries());
  828. $this->connection->logQueries(false);
  829. $this->assertFalse($this->connection->logQueries());
  830. });
  831. }
  832. /**
  833. * test enableQueryLogging method
  834. *
  835. * @return void
  836. */
  837. public function testEnableQueryLogging()
  838. {
  839. $this->connection->enableQueryLogging(true);
  840. $this->assertTrue($this->connection->isQueryLoggingEnabled());
  841. $this->connection->disableQueryLogging();
  842. $this->assertFalse($this->connection->isQueryLoggingEnabled());
  843. }
  844. /**
  845. * Tests that log() function logs to the configured query logger
  846. *
  847. * @return void
  848. */
  849. public function testLogFunction()
  850. {
  851. $logger = $this->getMockBuilder(QueryLogger::class)->getMock();
  852. $this->connection->setLogger($logger);
  853. $logger->expects($this->once())->method('log')
  854. ->with($this->logicalAnd(
  855. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  856. $this->attributeEqualTo('query', 'SELECT 1')
  857. ));
  858. $this->connection->log('SELECT 1');
  859. }
  860. /**
  861. * Tests that begin and rollback are also logged
  862. *
  863. * @return void
  864. */
  865. public function testLogBeginRollbackTransaction()
  866. {
  867. $connection = $this
  868. ->getMockBuilder(Connection::class)
  869. ->setMethods(['connect'])
  870. ->disableOriginalConstructor()
  871. ->getMock();
  872. $connection->enableQueryLogging(true);
  873. $driver = $this->getMockFormDriver();
  874. $connection->setDriver($driver);
  875. $logger = $this->getMockBuilder(QueryLogger::class)->getMock();
  876. $connection->setLogger($logger);
  877. $logger->expects($this->at(0))->method('log')
  878. ->with($this->logicalAnd(
  879. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  880. $this->attributeEqualTo('query', 'BEGIN')
  881. ));
  882. $logger->expects($this->at(1))->method('log')
  883. ->with($this->logicalAnd(
  884. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  885. $this->attributeEqualTo('query', 'ROLLBACK')
  886. ));
  887. $connection->begin();
  888. $connection->begin(); //This one will not be logged
  889. $connection->rollback();
  890. }
  891. /**
  892. * Tests that commits are logged
  893. *
  894. * @return void
  895. */
  896. public function testLogCommitTransaction()
  897. {
  898. $driver = $this->getMockFormDriver();
  899. $connection = $this->getMockBuilder(Connection::class)
  900. ->setMethods(['connect'])
  901. ->setConstructorArgs([['driver' => $driver]])
  902. ->getMock();
  903. $logger = $this->getMockBuilder(QueryLogger::class)->getMock();
  904. $connection->setLogger($logger);
  905. $logger->expects($this->at(1))->method('log')
  906. ->with($this->logicalAnd(
  907. $this->isInstanceOf('\Cake\Database\Log\LoggedQuery'),
  908. $this->attributeEqualTo('query', 'COMMIT')
  909. ));
  910. $connection->enableQueryLogging(true);
  911. $connection->begin();
  912. $connection->commit();
  913. }
  914. /**
  915. * Tests that the transactional method will start and commit a transaction
  916. * around some arbitrary function passed as argument
  917. *
  918. * @return void
  919. */
  920. public function testTransactionalSuccess()
  921. {
  922. $driver = $this->getMockFormDriver();
  923. $connection = $this->getMockBuilder(Connection::class)
  924. ->setMethods(['connect', 'commit', 'begin'])
  925. ->setConstructorArgs([['driver' => $driver]])
  926. ->getMock();
  927. $connection->expects($this->at(0))->method('begin');
  928. $connection->expects($this->at(1))->method('commit');
  929. $result = $connection->transactional(function ($conn) use ($connection) {
  930. $this->assertSame($connection, $conn);
  931. return 'thing';
  932. });
  933. $this->assertEquals('thing', $result);
  934. }
  935. /**
  936. * Tests that the transactional method will rollback the transaction if false
  937. * is returned from the callback
  938. *
  939. * @return void
  940. */
  941. public function testTransactionalFail()
  942. {
  943. $driver = $this->getMockFormDriver();
  944. $connection = $this->getMockBuilder(Connection::class)
  945. ->setMethods(['connect', 'commit', 'begin', 'rollback'])
  946. ->setConstructorArgs([['driver' => $driver]])
  947. ->getMock();
  948. $connection->expects($this->at(0))->method('begin');
  949. $connection->expects($this->at(1))->method('rollback');
  950. $connection->expects($this->never())->method('commit');
  951. $result = $connection->transactional(function ($conn) use ($connection) {
  952. $this->assertSame($connection, $conn);
  953. return false;
  954. });
  955. $this->assertFalse($result);
  956. }
  957. /**
  958. * Tests that the transactional method will rollback the transaction
  959. * and throw the same exception if the callback raises one
  960. *
  961. * @return void
  962. * @throws \InvalidArgumentException
  963. */
  964. public function testTransactionalWithException()
  965. {
  966. $this->expectException(\InvalidArgumentException::class);
  967. $driver = $this->getMockFormDriver();
  968. $connection = $this->getMockBuilder(Connection::class)
  969. ->setMethods(['connect', 'commit', 'begin', 'rollback'])
  970. ->setConstructorArgs([['driver' => $driver]])
  971. ->getMock();
  972. $connection->expects($this->at(0))->method('begin');
  973. $connection->expects($this->at(1))->method('rollback');
  974. $connection->expects($this->never())->method('commit');
  975. $connection->transactional(function ($conn) use ($connection) {
  976. $this->assertSame($connection, $conn);
  977. throw new \InvalidArgumentException();
  978. });
  979. }
  980. /**
  981. * Tests it is possible to set a schema collection object
  982. *
  983. * @return void
  984. */
  985. public function testSetSchemaCollection()
  986. {
  987. $driver = $this->getMockFormDriver();
  988. $connection = $this->getMockBuilder(Connection::class)
  989. ->setMethods(['connect'])
  990. ->setConstructorArgs([['driver' => $driver]])
  991. ->getMock();
  992. $schema = $connection->getSchemaCollection();
  993. $this->assertInstanceOf('Cake\Database\Schema\Collection', $schema);
  994. $schema = $this->getMockBuilder('Cake\Database\Schema\Collection')
  995. ->setConstructorArgs([$connection])
  996. ->getMock();
  997. $connection->setSchemaCollection($schema);
  998. $this->assertSame($schema, $connection->getSchemaCollection());
  999. }
  1000. /**
  1001. * Tests it is possible to set a schema collection object
  1002. *
  1003. * @group deprecated
  1004. * @return void
  1005. */
  1006. public function testSchemaCollection()
  1007. {
  1008. $this->deprecated(function () {
  1009. $driver = $this->getMockFormDriver();
  1010. $connection = $this->getMockBuilder(Connection::class)
  1011. ->setMethods(['connect'])
  1012. ->setConstructorArgs([['driver' => $driver]])
  1013. ->getMock();
  1014. $schema = $connection->schemaCollection();
  1015. $this->assertInstanceOf('Cake\Database\Schema\Collection', $schema);
  1016. $schema = $this->getMockBuilder('Cake\Database\Schema\Collection')
  1017. ->setConstructorArgs([$connection])
  1018. ->getMock();
  1019. $connection->schemaCollection($schema);
  1020. $this->assertSame($schema, $connection->schemaCollection());
  1021. });
  1022. }
  1023. /**
  1024. * Tests that allowed nesting of commit/rollback operations doesn't
  1025. * throw any exceptions.
  1026. *
  1027. * @return void
  1028. */
  1029. public function testNestedTransactionRollbackExceptionNotThrown()
  1030. {
  1031. $this->connection->transactional(function () {
  1032. $this->connection->transactional(function () {
  1033. return true;
  1034. });
  1035. return true;
  1036. });
  1037. $this->assertFalse($this->connection->inTransaction());
  1038. $this->connection->transactional(function () {
  1039. $this->connection->transactional(function () {
  1040. return true;
  1041. });
  1042. return false;
  1043. });
  1044. $this->assertFalse($this->connection->inTransaction());
  1045. $this->connection->transactional(function () {
  1046. $this->connection->transactional(function () {
  1047. return false;
  1048. });
  1049. return false;
  1050. });
  1051. $this->assertFalse($this->connection->inTransaction());
  1052. }
  1053. /**
  1054. * Tests that not allowed nesting of commit/rollback operations throws
  1055. * a NestedTransactionRollbackException.
  1056. *
  1057. * @return void
  1058. */
  1059. public function testNestedTransactionRollbackExceptionThrown()
  1060. {
  1061. $this->rollbackSourceLine = -1;
  1062. $e = null;
  1063. try {
  1064. $this->connection->transactional(function () {
  1065. $this->connection->transactional(function () {
  1066. return false;
  1067. });
  1068. $this->rollbackSourceLine = __LINE__ - 1;
  1069. return true;
  1070. });
  1071. $this->fail('NestedTransactionRollbackException should be thrown');
  1072. } catch (NestedTransactionRollbackException $e) {
  1073. }
  1074. $trace = $e->getTrace();
  1075. $this->assertEquals(__FILE__, $trace[1]['file']);
  1076. $this->assertEquals($this->rollbackSourceLine, $trace[1]['line']);
  1077. }
  1078. /**
  1079. * Tests more detail about that not allowed nesting of rollback/commit
  1080. * operations throws a NestedTransactionRollbackException.
  1081. *
  1082. * @return void
  1083. */
  1084. public function testNestedTransactionStates()
  1085. {
  1086. $this->rollbackSourceLine = -1;
  1087. $this->nestedTransactionStates = [];
  1088. $e = null;
  1089. try {
  1090. $this->connection->transactional(function () {
  1091. $this->pushNestedTransactionState();
  1092. $this->connection->transactional(function () {
  1093. return true;
  1094. });
  1095. $this->connection->transactional(function () {
  1096. $this->pushNestedTransactionState();
  1097. $this->connection->transactional(function () {
  1098. return false;
  1099. });
  1100. $this->rollbackSourceLine = __LINE__ - 1;
  1101. $this->pushNestedTransactionState();
  1102. return true;
  1103. });
  1104. $this->connection->transactional(function () {
  1105. return false;
  1106. });
  1107. $this->pushNestedTransactionState();
  1108. return true;
  1109. });
  1110. $this->fail('NestedTransactionRollbackException should be thrown');
  1111. } catch (NestedTransactionRollbackException $e) {
  1112. }
  1113. $this->pushNestedTransactionState();
  1114. $this->assertSame([false, false, true, true, false], $this->nestedTransactionStates);
  1115. $this->assertFalse($this->connection->inTransaction());
  1116. $trace = $e->getTrace();
  1117. $this->assertEquals(__FILE__, $trace[1]['file']);
  1118. $this->assertEquals($this->rollbackSourceLine, $trace[1]['line']);
  1119. }
  1120. /**
  1121. * Helper method to trace nested transaction states.
  1122. *
  1123. * @return void
  1124. */
  1125. public function pushNestedTransactionState()
  1126. {
  1127. $method = new ReflectionMethod($this->connection, 'wasNestedTransactionRolledback');
  1128. $method->setAccessible(true);
  1129. $this->nestedTransactionStates[] = $method->invoke($this->connection);
  1130. }
  1131. /**
  1132. * Tests that the connection is restablished whenever it is interrupted
  1133. * after having used the connection at least once.
  1134. *
  1135. * @return void
  1136. */
  1137. public function testAutomaticReconnect()
  1138. {
  1139. $conn = clone $this->connection;
  1140. $statement = $conn->query('SELECT 1');
  1141. $statement->execute();
  1142. $statement->closeCursor();
  1143. $prop = new ReflectionProperty($conn, '_driver');
  1144. $prop->setAccessible(true);
  1145. $oldDriver = $prop->getValue($conn);
  1146. $newDriver = $this->getMockBuilder('Cake\Database\Driver')->getMock();
  1147. $prop->setValue($conn, $newDriver);
  1148. $newDriver->expects($this->at(0))
  1149. ->method('prepare')
  1150. ->will($this->throwException(new Exception('server gone away')));
  1151. $newDriver->expects($this->at(1))->method('disconnect');
  1152. $newDriver->expects($this->at(2))->method('connect');
  1153. $newDriver->expects($this->at(3))
  1154. ->method('prepare')
  1155. ->will($this->returnValue($statement));
  1156. $res = $conn->query('SELECT 1');
  1157. $this->assertInstanceOf(StatementInterface::class, $res);
  1158. }
  1159. /**
  1160. * Tests that the connection is not restablished whenever it is interrupted
  1161. * inside a transaction.
  1162. *
  1163. * @return void
  1164. */
  1165. public function testNoAutomaticReconnect()
  1166. {
  1167. $conn = clone $this->connection;
  1168. $statement = $conn->query('SELECT 1');
  1169. $statement->execute();
  1170. $statement->closeCursor();
  1171. $conn->begin();
  1172. $prop = new ReflectionProperty($conn, '_driver');
  1173. $prop->setAccessible(true);
  1174. $oldDriver = $prop->getValue($conn);
  1175. $newDriver = $this->getMockBuilder('Cake\Database\Driver')->getMock();
  1176. $prop->setValue($conn, $newDriver);
  1177. $newDriver->expects($this->once())
  1178. ->method('prepare')
  1179. ->will($this->throwException(new Exception('server gone away')));
  1180. $this->expectException(Exception::class);
  1181. $conn->query('SELECT 1');
  1182. }
  1183. }