ConnectionTest.php 43 KB

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