CaseExpressionQueryTest.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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 4.3.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Database\QueryTests;
  17. use Cake\Database\Driver\Postgres;
  18. use Cake\Database\Expression\QueryExpression;
  19. use Cake\Database\Query;
  20. use Cake\Database\Query\SelectQuery;
  21. use Cake\Database\Query\UpdateQuery;
  22. use Cake\Database\StatementInterface;
  23. use Cake\Database\TypeMap;
  24. use Cake\Datasource\ConnectionManager;
  25. use Cake\Test\Fixture\ArticlesFixture;
  26. use Cake\Test\Fixture\CommentsFixture;
  27. use Cake\Test\Fixture\ProductsFixture;
  28. use Cake\TestSuite\TestCase;
  29. class CaseExpressionQueryTest extends TestCase
  30. {
  31. protected array $fixtures = [
  32. ArticlesFixture::class,
  33. CommentsFixture::class,
  34. ProductsFixture::class,
  35. ];
  36. /**
  37. * @var \Cake\Database\Connection
  38. */
  39. protected $connection;
  40. /**
  41. * @var \Cake\Database\Query\SelectQuery
  42. */
  43. protected $query;
  44. public function setUp(): void
  45. {
  46. parent::setUp();
  47. $this->connection = ConnectionManager::get('test');
  48. $this->query = new SelectQuery($this->connection);
  49. }
  50. public function tearDown(): void
  51. {
  52. parent::tearDown();
  53. unset($this->query);
  54. unset($this->connection);
  55. }
  56. public function testSimpleCase(): void
  57. {
  58. $query = $this->query
  59. ->select(function (Query $query) {
  60. return [
  61. 'name',
  62. 'category_name' => $query->newExpr()
  63. ->case($query->identifier('products.category'))
  64. ->when(1)
  65. ->then('Touring')
  66. ->when(2)
  67. ->then('Urban')
  68. ->else('Other'),
  69. ];
  70. })
  71. ->from('products')
  72. ->orderByAsc('category')
  73. ->orderByAsc('name');
  74. $expected = [
  75. [
  76. 'name' => 'First product',
  77. 'category_name' => 'Touring',
  78. ],
  79. [
  80. 'name' => 'Second product',
  81. 'category_name' => 'Urban',
  82. ],
  83. [
  84. 'name' => 'Third product',
  85. 'category_name' => 'Other',
  86. ],
  87. ];
  88. $this->assertSame($expected, $query->execute()->fetchAll(StatementInterface::FETCH_TYPE_ASSOC));
  89. }
  90. public function testSearchedCase(): void
  91. {
  92. $typeMap = new TypeMap([
  93. 'price' => 'integer',
  94. ]);
  95. $query = $this->query
  96. ->select(function (Query $query) {
  97. return [
  98. 'name',
  99. 'price',
  100. 'price_range' => $query->newExpr()
  101. ->case()
  102. ->when(['price <' => 20])
  103. ->then('Under $20')
  104. ->when(['price >=' => 20, 'price <' => 30])
  105. ->then('Under $30')
  106. ->else('$30 and above'),
  107. ];
  108. })
  109. ->from('products')
  110. ->orderByAsc('price')
  111. ->orderByAsc('name')
  112. ->setSelectTypeMap($typeMap);
  113. $expected = [
  114. [
  115. 'name' => 'First product',
  116. 'price' => 10,
  117. 'price_range' => 'Under $20',
  118. ],
  119. [
  120. 'name' => 'Second product',
  121. 'price' => 20,
  122. 'price_range' => 'Under $30',
  123. ],
  124. [
  125. 'name' => 'Third product',
  126. 'price' => 30,
  127. 'price_range' => '$30 and above',
  128. ],
  129. ];
  130. $this->assertSame($expected, $query->execute()->fetchAll(StatementInterface::FETCH_TYPE_ASSOC));
  131. }
  132. public function testOrderByCase(): void
  133. {
  134. $typeMap = new TypeMap([
  135. 'article_id' => 'integer',
  136. 'user_id' => 'integer',
  137. ]);
  138. $query = $this->query
  139. ->select(['article_id', 'user_id'])
  140. ->from('comments')
  141. ->orderByAsc('comments.article_id')
  142. ->orderByDesc(function (QueryExpression $exp, Query $query) {
  143. return $query->newExpr()
  144. ->case($query->identifier('comments.article_id'))
  145. ->when(1)
  146. ->then($query->identifier('comments.user_id'));
  147. })
  148. ->orderByAsc(function (QueryExpression $exp, Query $query) {
  149. return $query->newExpr()
  150. ->case($query->identifier('comments.article_id'))
  151. ->when(2)
  152. ->then($query->identifier('comments.user_id'));
  153. })
  154. ->setSelectTypeMap($typeMap);
  155. $expected = [
  156. [
  157. 'article_id' => 1,
  158. 'user_id' => 4,
  159. ],
  160. [
  161. 'article_id' => 1,
  162. 'user_id' => 2,
  163. ],
  164. [
  165. 'article_id' => 1,
  166. 'user_id' => 1,
  167. ],
  168. [
  169. 'article_id' => 1,
  170. 'user_id' => 1,
  171. ],
  172. [
  173. 'article_id' => 2,
  174. 'user_id' => 1,
  175. ],
  176. [
  177. 'article_id' => 2,
  178. 'user_id' => 2,
  179. ],
  180. ];
  181. $this->assertSame($expected, $query->execute()->fetchAll(StatementInterface::FETCH_TYPE_ASSOC));
  182. }
  183. public function testHavingByCase(): void
  184. {
  185. $query = $this->query
  186. ->select(['articles.title'])
  187. ->from('articles')
  188. ->leftJoin('comments', ['comments.article_id = articles.id'])
  189. ->groupBy(['articles.id', 'articles.title'])
  190. ->having(function (QueryExpression $exp, Query $query) {
  191. $expression = $query->newExpr()
  192. ->case()
  193. ->when(['comments.published' => 'Y'])
  194. ->then(1);
  195. if ($query->getConnection()->getDriver() instanceof Postgres) {
  196. $expression = $query->func()->cast($expression, 'integer');
  197. }
  198. return $exp->gt(
  199. $query->func()->sum($expression),
  200. 2,
  201. 'integer'
  202. );
  203. });
  204. $expected = [
  205. [
  206. 'title' => 'First Article',
  207. ],
  208. ];
  209. $this->assertSame($expected, $query->execute()->fetchAll(StatementInterface::FETCH_TYPE_ASSOC));
  210. }
  211. public function testUpdateFromCase(): void
  212. {
  213. $query = $this->query
  214. ->select(['count' => $this->query->func()->count('*')])
  215. ->from('comments')
  216. ->where(['comments.published' => 'Y']);
  217. $this->assertSame(5, (int)$query->execute()->fetch()[0]);
  218. $query->where(['comments.published' => 'N'], [], true);
  219. $this->assertSame(1, (int)$query->execute()->fetch()[0]);
  220. $query = (new UpdateQuery($this->connection))
  221. ->update('comments')
  222. ->set([
  223. 'published' =>
  224. $this->query->newExpr()
  225. ->case()
  226. ->when(['published' => 'Y'])
  227. ->then('N')
  228. ->else('Y'),
  229. ])
  230. ->where(['1 = 1'])
  231. ->execute();
  232. $query = (new SelectQuery($this->connection))
  233. ->select(['count' => $this->query->func()->count('*')])
  234. ->from('comments')
  235. ->where(['comments.published' => 'Y']);
  236. $this->assertSame(1, (int)$query->execute()->fetch()[0]);
  237. $query->where(['comments.published' => 'N'], [], true);
  238. $this->assertSame(5, (int)$query->execute()->fetch()[0]);
  239. }
  240. public static function bindingValueDataProvider(): array
  241. {
  242. return [
  243. ['1', 3],
  244. ['2', 4],
  245. ];
  246. }
  247. /**
  248. * @dataProvider bindingValueDataProvider
  249. * @param string $when The `WHEN` value.
  250. * @param int $result The result value.
  251. */
  252. public function testBindValues(string $when, int $result): void
  253. {
  254. $value = '1';
  255. $then = '3';
  256. $else = '4';
  257. $typeMap = new TypeMap([
  258. 'val' => 'integer',
  259. ]);
  260. $query = $this->query
  261. ->select(function (Query $query) {
  262. return [
  263. 'val' => $query->newExpr()
  264. ->case($query->newExpr(':value'))
  265. ->when($query->newExpr(':when'))
  266. ->then($query->newExpr(':then'))
  267. ->else($query->newExpr(':else')),
  268. ];
  269. })
  270. ->from('products')
  271. ->bind(':value', $value, 'integer')
  272. ->bind(':when', $when, 'integer')
  273. ->bind(':then', $then, 'integer')
  274. ->bind(':else', $else, 'integer')
  275. ->setSelectTypeMap($typeMap);
  276. $expected = [
  277. 'val' => $result,
  278. ];
  279. $this->assertSame($expected, $query->execute()->fetch(StatementInterface::FETCH_TYPE_ASSOC));
  280. }
  281. }