ConnectionTest.php 56 KB

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