LoggingStatementTest.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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\Log;
  17. use Cake\Core\Configure;
  18. use Cake\Database\Connection;
  19. use Cake\Database\Driver;
  20. use Cake\Database\DriverInterface;
  21. use Cake\Database\Exception\DatabaseException;
  22. use Cake\Database\Log\LoggingStatement;
  23. use Cake\Database\Log\QueryLogger;
  24. use Cake\Database\StatementInterface;
  25. use Cake\Datasource\ConnectionInterface;
  26. use Cake\Log\Log;
  27. use Cake\TestSuite\TestCase;
  28. use DateTime;
  29. use TestApp\Error\Exception\MyPDOException;
  30. use TestApp\Error\Exception\MyPDOStringException;
  31. /**
  32. * Tests LoggingStatement class
  33. */
  34. class LoggingStatementTest extends TestCase
  35. {
  36. public function setUp(): void
  37. {
  38. parent::setUp();
  39. Log::setConfig('queries', [
  40. 'className' => 'Array',
  41. 'scopes' => ['queriesLog'],
  42. ]);
  43. }
  44. public function tearDown(): void
  45. {
  46. parent::tearDown();
  47. Log::drop('queries');
  48. Configure::delete('Error.convertStatementToDatabaseException');
  49. }
  50. /**
  51. * Tests that queries are logged when executed without params
  52. */
  53. public function testExecuteNoParams(): void
  54. {
  55. $inner = $this->getMockBuilder(StatementInterface::class)->getMock();
  56. $inner->method('rowCount')->will($this->returnValue(3));
  57. $inner->method('execute')->will($this->returnValue(true));
  58. $driver = $this->getMockBuilder(Driver::class)->getMock();
  59. $driver->expects($this->any())
  60. ->method('getRole')
  61. ->will($this->returnValue(Connection::ROLE_WRITE));
  62. $st = $this->getMockBuilder(LoggingStatement::class)
  63. ->onlyMethods(['__get'])
  64. ->setConstructorArgs([$inner, $driver])
  65. ->getMock();
  66. $st->expects($this->any())
  67. ->method('__get')
  68. ->willReturn('SELECT bar FROM foo');
  69. $st->setLogger(new QueryLogger(['connection' => 'test']));
  70. $st->execute();
  71. $st->fetchAll();
  72. $messages = Log::engine('queries')->read();
  73. $this->assertCount(1, $messages);
  74. $this->assertMatchesRegularExpression('/^debug: connection=test role=write duration=\d+ rows=3 SELECT bar FROM foo$/', $messages[0]);
  75. }
  76. /**
  77. * Tests that queries are logged when executed with params
  78. */
  79. public function testExecuteWithParams(): void
  80. {
  81. $inner = $this->getMockBuilder(StatementInterface::class)->getMock();
  82. $inner->method('rowCount')->will($this->returnValue(4));
  83. $inner->method('execute')->will($this->returnValue(true));
  84. $driver = $this->getMockBuilder(Driver::class)->getMock();
  85. $driver->expects($this->any())
  86. ->method('getRole')
  87. ->will($this->returnValue(Connection::ROLE_WRITE));
  88. $st = $this->getMockBuilder(LoggingStatement::class)
  89. ->onlyMethods(['__get'])
  90. ->setConstructorArgs([$inner, $driver])
  91. ->getMock();
  92. $st->expects($this->any())
  93. ->method('__get')
  94. ->willReturn('SELECT bar FROM foo WHERE x=:a AND y=:b');
  95. $st->setLogger(new QueryLogger(['connection' => 'test']));
  96. $st->execute(['a' => 1, 'b' => 2]);
  97. $st->fetchAll();
  98. $messages = Log::engine('queries')->read();
  99. $this->assertCount(1, $messages);
  100. $this->assertMatchesRegularExpression('/^debug: connection=test role=write duration=\d+ rows=4 SELECT bar FROM foo WHERE x=1 AND y=2$/', $messages[0]);
  101. }
  102. /**
  103. * Tests that queries are logged when executed with bound params
  104. */
  105. public function testExecuteWithBinding(): void
  106. {
  107. $inner = $this->getMockBuilder(StatementInterface::class)->getMock();
  108. $inner->method('rowCount')->will($this->returnValue(4));
  109. $inner->method('execute')->will($this->returnValue(true));
  110. $date = new DateTime('2013-01-01');
  111. $inner->expects($this->atLeast(2))
  112. ->method('bindValue')
  113. ->withConsecutive(['a', 1], ['b', $date]);
  114. $driver = $this->getMockBuilder('Cake\Database\Driver')->getMock();
  115. $st = $this->getMockBuilder(LoggingStatement::class)
  116. ->onlyMethods(['__get'])
  117. ->setConstructorArgs([$inner, $driver])
  118. ->getMock();
  119. $st->expects($this->any())
  120. ->method('__get')
  121. ->willReturn('SELECT bar FROM foo WHERE a=:a AND b=:b');
  122. $st->setLogger(new QueryLogger(['connection' => 'test']));
  123. $st->bindValue('a', 1);
  124. $st->bindValue('b', $date, 'date');
  125. $st->execute();
  126. $st->fetchAll();
  127. $st->bindValue('b', new DateTime('2014-01-01'), 'date');
  128. $st->execute();
  129. $st->fetchAll();
  130. $messages = Log::engine('queries')->read();
  131. $this->assertCount(2, $messages);
  132. $this->assertMatchesRegularExpression("/^debug: connection=test role= duration=\d+ rows=4 SELECT bar FROM foo WHERE a='1' AND b='2013-01-01'$/", $messages[0]);
  133. $this->assertMatchesRegularExpression("/^debug: connection=test role= duration=\d+ rows=4 SELECT bar FROM foo WHERE a='1' AND b='2014-01-01'$/", $messages[1]);
  134. }
  135. /**
  136. * Tests that queries are logged despite database errors
  137. */
  138. public function testExecuteWithError(): void
  139. {
  140. $this->skipIf(
  141. version_compare(PHP_VERSION, '8.2.0', '>='),
  142. 'Setting queryString on exceptions does not work on 8.2+'
  143. );
  144. $exception = new MyPDOException('This is bad');
  145. $inner = $this->getMockBuilder(StatementInterface::class)->getMock();
  146. $inner->expects($this->once())
  147. ->method('execute')
  148. ->will($this->throwException($exception));
  149. $driver = $this->getMockBuilder(Driver::class)->getMock();
  150. $driver->expects($this->any())
  151. ->method('getRole')
  152. ->will($this->returnValue(Connection::ROLE_WRITE));
  153. $st = $this->getMockBuilder(LoggingStatement::class)
  154. ->onlyMethods(['__get'])
  155. ->setConstructorArgs([$inner, $driver])
  156. ->getMock();
  157. $st->expects($this->any())
  158. ->method('__get')
  159. ->willReturn('SELECT bar FROM foo');
  160. $st->setLogger(new QueryLogger(['connection' => 'test']));
  161. $this->deprecated(function () use ($st) {
  162. try {
  163. $st->execute();
  164. } catch (MyPDOException $e) {
  165. $this->assertSame('This is bad', $e->getMessage());
  166. $this->assertSame($st->queryString, $e->queryString);
  167. }
  168. });
  169. $messages = Log::engine('queries')->read();
  170. $this->assertCount(1, $messages);
  171. $this->assertMatchesRegularExpression("/^debug: connection=test role=write duration=\d+ rows=0 SELECT bar FROM foo$/", $messages[0]);
  172. }
  173. /**
  174. * Tests that we do exception wrapping correctly.
  175. * The exception returns a string code like most PDOExceptions
  176. */
  177. public function testExecuteWithErrorWrapStatementStringCode(): void
  178. {
  179. Configure::write('Error.convertStatementToDatabaseException', true);
  180. $exception = new MyPDOStringException('This is bad', 1234);
  181. $inner = $this->getMockBuilder(StatementInterface::class)->getMock();
  182. $inner->expects($this->once())
  183. ->method('execute')
  184. ->will($this->throwException($exception));
  185. $driver = $this->getMockBuilder(Driver::class)->getMock();
  186. $driver->expects($this->any())
  187. ->method('getRole')
  188. ->will($this->returnValue(ConnectionInterface::ROLE_WRITE));
  189. $st = $this->getMockBuilder(LoggingStatement::class)
  190. ->onlyMethods(['__get'])
  191. ->setConstructorArgs([$inner, $driver])
  192. ->getMock();
  193. $st->expects($this->any())
  194. ->method('__get')
  195. ->willReturn('SELECT bar FROM foo');
  196. $st->setLogger(new QueryLogger(['connection' => 'test']));
  197. try {
  198. $st->execute();
  199. $this->fail('Exception not thrown');
  200. } catch (DatabaseException $e) {
  201. $attrs = $e->getAttributes();
  202. $this->assertSame('This is bad', $e->getMessage());
  203. $this->assertArrayHasKey('queryString', $attrs);
  204. $this->assertSame($st->queryString, $attrs['queryString']);
  205. }
  206. $messages = Log::engine('queries')->read();
  207. $this->assertCount(1, $messages);
  208. $this->assertMatchesRegularExpression("/^debug: connection=test role=write duration=\d+ rows=0 SELECT bar FROM foo$/", $messages[0]);
  209. }
  210. /**
  211. * Tests that we do exception wrapping correctly.
  212. * The exception returns an int code.
  213. */
  214. public function testExecuteWithErrorWrapStatementIntCode(): void
  215. {
  216. Configure::write('Error.convertStatementToDatabaseException', true);
  217. $exception = new MyPDOException('This is bad', 1234);
  218. $inner = $this->getMockBuilder(StatementInterface::class)->getMock();
  219. $inner->expects($this->once())
  220. ->method('execute')
  221. ->will($this->throwException($exception));
  222. $driver = $this->getMockBuilder(Driver::class)->getMock();
  223. $driver->expects($this->any())
  224. ->method('getRole')
  225. ->will($this->returnValue(ConnectionInterface::ROLE_WRITE));
  226. $st = $this->getMockBuilder(LoggingStatement::class)
  227. ->onlyMethods(['__get'])
  228. ->setConstructorArgs([$inner, $driver])
  229. ->getMock();
  230. $st->expects($this->any())
  231. ->method('__get')
  232. ->willReturn('SELECT bar FROM foo');
  233. $st->setLogger(new QueryLogger(['connection' => 'test']));
  234. try {
  235. $st->execute();
  236. $this->fail('Exception not thrown');
  237. } catch (DatabaseException $e) {
  238. $attrs = $e->getAttributes();
  239. $this->assertSame('This is bad', $e->getMessage());
  240. $this->assertArrayHasKey('queryString', $attrs);
  241. $this->assertSame($st->queryString, $attrs['queryString']);
  242. }
  243. $messages = Log::engine('queries')->read();
  244. $this->assertCount(1, $messages);
  245. $this->assertMatchesRegularExpression("/^debug: connection=test role=write duration=\d+ rows=0 SELECT bar FROM foo$/", $messages[0]);
  246. }
  247. /**
  248. * Tests setting and getting the logger
  249. */
  250. public function testSetAndGetLogger(): void
  251. {
  252. $logger = new QueryLogger(['connection' => 'test']);
  253. $st = new LoggingStatement(
  254. $this->getMockBuilder(StatementInterface::class)->getMock(),
  255. $this->getMockBuilder(DriverInterface::class)->getMock()
  256. );
  257. $st->setLogger($logger);
  258. $this->assertSame($logger, $st->getLogger());
  259. }
  260. }