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