ConnectionTest.php 37 KB

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