CommonTableExpressionQueryTests.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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.1.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Database;
  17. use Cake\Database\Driver\Mysql;
  18. use Cake\Database\Driver\Sqlite;
  19. use Cake\Database\Driver\Sqlserver;
  20. use Cake\Database\Expression\CommonTableExpression;
  21. use Cake\Database\Expression\QueryExpression;
  22. use Cake\Database\Query;
  23. use Cake\Database\ValueBinder;
  24. use Cake\Datasource\ConnectionManager;
  25. use Cake\TestSuite\TestCase;
  26. class CommonTableExpressionQueryTests extends TestCase
  27. {
  28. /**
  29. * @inheritDoc
  30. */
  31. protected $fixtures = [
  32. 'core.Articles',
  33. ];
  34. /**
  35. * @inheritDoc
  36. */
  37. public $autoFixtures = false;
  38. /**
  39. * @var \Cake\Database\Connection
  40. */
  41. protected $connection;
  42. /**
  43. * @var bool
  44. */
  45. protected $autoQuote;
  46. public function setUp(): void
  47. {
  48. parent::setUp();
  49. $this->connection = ConnectionManager::get('test');
  50. $this->skipIf(
  51. !$this->connection->getDriver()->supportsCTEs(),
  52. 'The current driver does not support common table expressions.'
  53. );
  54. }
  55. public function tearDown(): void
  56. {
  57. parent::tearDown();
  58. unset($this->connection);
  59. }
  60. /**
  61. * Tests with() sql generation.
  62. *
  63. * @return void
  64. */
  65. public function testWithCte()
  66. {
  67. $query = $this->connection->newQuery()
  68. ->with(new CommonTableExpression('cte', function () {
  69. return $this->connection->newQuery()->select(['col' => 1]);
  70. }))
  71. ->select('col')
  72. ->from('cte');
  73. $this->assertEqualsSql(
  74. 'WITH cte AS (SELECT 1 AS col) SELECT col FROM cte',
  75. $query->sql(new ValueBinder())
  76. );
  77. $expected = [
  78. [
  79. 'col' => '1',
  80. ],
  81. ];
  82. $result = $query->execute();
  83. $this->assertEquals($expected, $result->fetchAll('assoc'));
  84. $result->closeCursor();
  85. }
  86. /**
  87. * Tests calling with() with overwrite clears other CTEs.
  88. *
  89. * @return void
  90. */
  91. public function testWithCteOverwrite()
  92. {
  93. $query = $this->connection->newQuery()
  94. ->with(new CommonTableExpression('cte', function () {
  95. return $this->connection->newQuery()->select(['col' => '1']);
  96. }))
  97. ->select('col')
  98. ->from('cte');
  99. $this->assertEqualsSql(
  100. 'WITH cte AS (SELECT 1 AS col) SELECT col FROM cte',
  101. $query->sql(new ValueBinder())
  102. );
  103. $query
  104. ->with(new CommonTableExpression('cte2', $this->connection->newQuery()), true)
  105. ->from('cte2', true);
  106. $this->assertEqualsSql(
  107. 'WITH cte2 AS () SELECT col FROM cte2',
  108. $query->sql(new ValueBinder())
  109. );
  110. }
  111. /**
  112. * Tests recursive CTE.
  113. *
  114. * @return void
  115. */
  116. public function testWithRecursiveCte()
  117. {
  118. $query = $this->connection->newQuery()
  119. ->with(function (CommonTableExpression $cte, Query $query) {
  120. $anchorQuery = $query->getConnection()
  121. ->newQuery()
  122. ->select(1);
  123. $recursiveQuery = $query->getConnection()
  124. ->newQuery()
  125. ->select(function (Query $query) {
  126. return $query->newExpr('col + 1');
  127. })
  128. ->from('cte')
  129. ->where(['col !=' => 3], ['col' => 'integer']);
  130. $cteQuery = $anchorQuery->unionAll($recursiveQuery);
  131. return $cte
  132. ->name('cte')
  133. ->field(['col'])
  134. ->query($cteQuery)
  135. ->recursive();
  136. })
  137. ->select('col')
  138. ->from('cte');
  139. if ($this->connection->getDriver() instanceof Sqlserver) {
  140. $expectedSql =
  141. "WITH cte(col) AS " .
  142. "(SELECT 1\nUNION ALL SELECT (col + 1) FROM cte WHERE col != :c0) " .
  143. "SELECT col FROM cte";
  144. } elseif ($this->connection->getDriver() instanceof Sqlite) {
  145. $expectedSql =
  146. "WITH RECURSIVE cte(col) AS " .
  147. "(SELECT 1\nUNION ALL SELECT (col + 1) FROM cte WHERE col != :c0) " .
  148. "SELECT col FROM cte";
  149. } else {
  150. $expectedSql =
  151. "WITH RECURSIVE cte(col) AS " .
  152. "((SELECT 1)\nUNION ALL (SELECT (col + 1) FROM cte WHERE col != :c0)) " .
  153. "SELECT col FROM cte";
  154. }
  155. $this->assertEqualsSql(
  156. $expectedSql,
  157. $query->sql(new ValueBinder())
  158. );
  159. $expected = [
  160. [
  161. 'col' => '1',
  162. ],
  163. [
  164. 'col' => '2',
  165. ],
  166. [
  167. 'col' => '3',
  168. ],
  169. ];
  170. $result = $query->execute();
  171. $this->assertEquals($expected, $result->fetchAll('assoc'));
  172. $result->closeCursor();
  173. }
  174. /**
  175. * Test inserting from CTE.
  176. *
  177. * @return void
  178. */
  179. public function testWithInsertQuery()
  180. {
  181. $this->skipIf(
  182. ($this->connection->getDriver() instanceof Mysql),
  183. '`WITH ... INSERT INTO` syntax is not supported in MySQL.'
  184. );
  185. $this->loadFixtures('Articles');
  186. // test initial state
  187. $result = $this->connection->newQuery()
  188. ->select('*')
  189. ->from('articles')
  190. ->where(['id' => 4])
  191. ->execute();
  192. $this->assertFalse($result->fetch('assoc'));
  193. $result->closeCursor();
  194. $query = $this->connection
  195. ->newQuery()
  196. ->with(function (CommonTableExpression $cte, Query $query) {
  197. return $cte
  198. ->name('cte')
  199. ->field(['title', 'body'])
  200. ->query($query->newExpr("SELECT 'Fourth Article', 'Fourth Article Body'"));
  201. })
  202. ->insert(['title', 'body'])
  203. ->into('articles')
  204. ->values(
  205. $this->connection
  206. ->newQuery()
  207. ->select('*')
  208. ->from('cte')
  209. );
  210. $this->assertStartsWithSql(
  211. "WITH cte(title, body) AS (SELECT 'Fourth Article', 'Fourth Article Body') " .
  212. "INSERT INTO articles (title, body)",
  213. $query->sql(new ValueBinder())
  214. );
  215. // run insert
  216. $query->execute()->closeCursor();
  217. $expected = [
  218. 'id' => '4',
  219. 'author_id' => null,
  220. 'title' => 'Fourth Article',
  221. 'body' => 'Fourth Article Body',
  222. 'published' => 'N',
  223. ];
  224. // test updated state
  225. $result = $this->connection->newQuery()
  226. ->select('*')
  227. ->from('articles')
  228. ->where(['id' => 4])
  229. ->execute();
  230. $this->assertEquals($expected, $result->fetch('assoc'));
  231. $result->closeCursor();
  232. }
  233. /**
  234. * Tests inserting from CTE as values list.
  235. *
  236. * @return void
  237. */
  238. public function testWithInInsertWithValuesQuery()
  239. {
  240. $this->skipIf(
  241. ($this->connection->getDriver() instanceof Sqlserver),
  242. '`INSERT INTO ... WITH` syntax is not supported in SQL Server.'
  243. );
  244. $this->loadFixtures('Articles');
  245. $query = $this->connection->newQuery()
  246. ->insert(['title', 'body'])
  247. ->into('articles')
  248. ->values(
  249. $this->connection->newQuery()
  250. ->with(function (CommonTableExpression $cte, Query $query) {
  251. return $cte
  252. ->name('cte')
  253. ->field(['title', 'body'])
  254. ->query($query->newExpr("SELECT 'Fourth Article', 'Fourth Article Body'"));
  255. })
  256. ->select('*')
  257. ->from('cte')
  258. );
  259. $this->assertStartsWithSql(
  260. "INSERT INTO articles (title, body) " .
  261. "WITH cte(title, body) AS (SELECT 'Fourth Article', 'Fourth Article Body') SELECT * FROM cte",
  262. $query->sql(new ValueBinder())
  263. );
  264. // run insert
  265. $query->execute()->closeCursor();
  266. $expected = [
  267. 'id' => '4',
  268. 'author_id' => null,
  269. 'title' => 'Fourth Article',
  270. 'body' => 'Fourth Article Body',
  271. 'published' => 'N',
  272. ];
  273. // test updated state
  274. $result = $this->connection->newQuery()
  275. ->select('*')
  276. ->from('articles')
  277. ->where(['id' => 4])
  278. ->execute();
  279. $this->assertEquals($expected, $result->fetch('assoc'));
  280. $result->closeCursor();
  281. }
  282. /**
  283. * Tests updating from CTE.
  284. *
  285. * @return void
  286. */
  287. public function testWithInUpdateQuery()
  288. {
  289. $this->loadFixtures('Articles');
  290. // test initial state
  291. $result = $this->connection->newQuery()
  292. ->select(['count' => 'COUNT(*)'])
  293. ->from('articles')
  294. ->where(['published' => 'Y'])
  295. ->execute();
  296. $this->assertEquals(['count' => '3'], $result->fetch('assoc'));
  297. $result->closeCursor();
  298. $query = $this->connection->newQuery()
  299. ->with(function (CommonTableExpression $cte, Query $query) {
  300. $cteQuery = $query->getConnection()
  301. ->newQuery()
  302. ->select('articles.id')
  303. ->from('articles')
  304. ->where(['articles.id !=' => 1]);
  305. return $cte
  306. ->name('cte')
  307. ->query($cteQuery);
  308. })
  309. ->update('articles')
  310. ->set('published', 'N')
  311. ->where(function (QueryExpression $exp, Query $query) {
  312. return $exp->in(
  313. 'articles.id',
  314. $query
  315. ->getConnection()
  316. ->newQuery()
  317. ->select('cte.id')
  318. ->from('cte')
  319. );
  320. });
  321. $this->assertEqualsSql(
  322. "WITH cte AS (SELECT articles.id FROM articles WHERE articles.id != :c0) " .
  323. "UPDATE articles SET published = :c1 WHERE id IN (SELECT cte.id FROM cte)",
  324. $query->sql(new ValueBinder())
  325. );
  326. // run update
  327. $query->execute()->closeCursor();
  328. // test updated state
  329. $result = $this->connection->newQuery()
  330. ->select(['count' => 'COUNT(*)'])
  331. ->from('articles')
  332. ->where(['published' => 'Y'])
  333. ->execute();
  334. $this->assertEquals(['count' => '1'], $result->fetch('assoc'));
  335. $result->closeCursor();
  336. }
  337. /**
  338. * Tests deleting from CTE.
  339. *
  340. * @return void
  341. */
  342. public function testWithInDeleteQuery()
  343. {
  344. $this->loadFixtures('Articles');
  345. // test initial state
  346. $result = $this->connection
  347. ->newQuery()
  348. ->select(['count' => 'COUNT(*)'])
  349. ->from('articles')
  350. ->execute();
  351. $this->assertEquals(['count' => '3'], $result->fetch('assoc'));
  352. $result->closeCursor();
  353. $query = $this->connection->newQuery()
  354. ->with(function (CommonTableExpression $cte, Query $query) {
  355. $cteQuery = $query->getConnection()
  356. ->newQuery()
  357. ->select('articles.id')
  358. ->from('articles')
  359. ->where(['articles.id !=' => 1]);
  360. return $cte
  361. ->name('cte')
  362. ->query($cteQuery);
  363. })
  364. ->delete()
  365. ->from(['a' => 'articles'])
  366. ->where(function (QueryExpression $exp, Query $query) {
  367. return $exp->in(
  368. 'a.id',
  369. $query
  370. ->getConnection()
  371. ->newQuery()
  372. ->select('cte.id')
  373. ->from('cte')
  374. );
  375. });
  376. $this->assertEqualsSql(
  377. "WITH cte AS (SELECT articles.id FROM articles WHERE articles.id != :c0) " .
  378. "DELETE FROM articles WHERE id IN (SELECT cte.id FROM cte)",
  379. $query->sql(new ValueBinder())
  380. );
  381. // run delete
  382. $query->execute()->closeCursor();
  383. $expected = [
  384. 'id' => '1',
  385. 'author_id' => '1',
  386. 'title' => 'First Article',
  387. 'body' => 'First Article Body',
  388. 'published' => 'Y',
  389. ];
  390. // test updated state
  391. $result = $this->connection->newQuery()
  392. ->select('*')
  393. ->from('articles')
  394. ->execute();
  395. $this->assertEquals($expected, $result->fetch('assoc'));
  396. $result->closeCursor();
  397. }
  398. }