CommonTableExpressionQueryTests.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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\QueryTests;
  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->autoQuote = $this->connection->getDriver()->isAutoQuotingEnabled();
  51. $this->skipIf(
  52. !$this->connection->getDriver()->supportsCTEs(),
  53. 'The current driver does not support common table expressions.'
  54. );
  55. }
  56. public function tearDown(): void
  57. {
  58. parent::tearDown();
  59. unset($this->connection);
  60. }
  61. /**
  62. * Tests with() sql generation.
  63. *
  64. * @return void
  65. */
  66. public function testWithCte()
  67. {
  68. $query = $this->connection->newQuery()
  69. ->with(new CommonTableExpression('cte', function () {
  70. return $this->connection->newQuery()->select(['col' => 1]);
  71. }))
  72. ->select('col')
  73. ->from('cte');
  74. $this->assertRegExpSql(
  75. 'WITH <cte> AS \(SELECT 1 AS <col>\) SELECT <col> FROM <cte>',
  76. $query->sql(new ValueBinder()),
  77. !$this->autoQuote
  78. );
  79. $expected = [
  80. [
  81. 'col' => '1',
  82. ],
  83. ];
  84. $result = $query->execute();
  85. $this->assertEquals($expected, $result->fetchAll('assoc'));
  86. $result->closeCursor();
  87. }
  88. /**
  89. * Tests calling with() with overwrite clears other CTEs.
  90. *
  91. * @return void
  92. */
  93. public function testWithCteOverwrite()
  94. {
  95. $query = $this->connection->newQuery()
  96. ->with(new CommonTableExpression('cte', function () {
  97. return $this->connection->newQuery()->select(['col' => '1']);
  98. }))
  99. ->select('col')
  100. ->from('cte');
  101. $this->assertEqualsSql(
  102. 'WITH cte AS (SELECT 1 AS col) SELECT col FROM cte',
  103. $query->sql(new ValueBinder())
  104. );
  105. $query
  106. ->with(new CommonTableExpression('cte2', $this->connection->newQuery()), true)
  107. ->from('cte2', true);
  108. $this->assertEqualsSql(
  109. 'WITH cte2 AS () SELECT col FROM cte2',
  110. $query->sql(new ValueBinder())
  111. );
  112. }
  113. /**
  114. * Tests recursive CTE.
  115. *
  116. * @return void
  117. */
  118. public function testWithRecursiveCte()
  119. {
  120. $query = $this->connection->newQuery()
  121. ->with(function (CommonTableExpression $cte, Query $query) {
  122. $anchorQuery = $query->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
  301. ->select('articles.id')
  302. ->from('articles')
  303. ->where(['articles.id !=' => 1]);
  304. return $cte
  305. ->name('cte')
  306. ->query($cteQuery);
  307. })
  308. ->update('articles')
  309. ->set('published', 'N')
  310. ->where(function (QueryExpression $exp, Query $query) {
  311. return $exp->in(
  312. 'articles.id',
  313. $query
  314. ->getConnection()
  315. ->newQuery()
  316. ->select('cte.id')
  317. ->from('cte')
  318. );
  319. });
  320. $this->assertEqualsSql(
  321. 'WITH cte AS (SELECT articles.id FROM articles WHERE articles.id != :c0) ' .
  322. 'UPDATE articles SET published = :c1 WHERE id IN (SELECT cte.id FROM cte)',
  323. $query->sql(new ValueBinder())
  324. );
  325. // run update
  326. $query->execute()->closeCursor();
  327. // test updated state
  328. $result = $this->connection->newQuery()
  329. ->select(['count' => 'COUNT(*)'])
  330. ->from('articles')
  331. ->where(['published' => 'Y'])
  332. ->execute();
  333. $this->assertEquals(['count' => '1'], $result->fetch('assoc'));
  334. $result->closeCursor();
  335. }
  336. /**
  337. * Tests deleting from CTE.
  338. *
  339. * @return void
  340. */
  341. public function testWithInDeleteQuery()
  342. {
  343. $this->loadFixtures('Articles');
  344. // test initial state
  345. $result = $this->connection
  346. ->newQuery()
  347. ->select(['count' => 'COUNT(*)'])
  348. ->from('articles')
  349. ->execute();
  350. $this->assertEquals(['count' => '3'], $result->fetch('assoc'));
  351. $result->closeCursor();
  352. $query = $this->connection->newQuery()
  353. ->with(function (CommonTableExpression $cte, Query $query) {
  354. $query->select('articles.id')
  355. ->from('articles')
  356. ->where(['articles.id !=' => 1]);
  357. return $cte
  358. ->name('cte')
  359. ->query($query);
  360. })
  361. ->delete()
  362. ->from(['a' => 'articles'])
  363. ->where(function (QueryExpression $exp, Query $query) {
  364. return $exp->in(
  365. 'a.id',
  366. $query
  367. ->getConnection()
  368. ->newQuery()
  369. ->select('cte.id')
  370. ->from('cte')
  371. );
  372. });
  373. $this->assertEqualsSql(
  374. 'WITH cte AS (SELECT articles.id FROM articles WHERE articles.id != :c0) ' .
  375. 'DELETE FROM articles WHERE id IN (SELECT cte.id FROM cte)',
  376. $query->sql(new ValueBinder())
  377. );
  378. // run delete
  379. $query->execute()->closeCursor();
  380. $expected = [
  381. 'id' => '1',
  382. 'author_id' => '1',
  383. 'title' => 'First Article',
  384. 'body' => 'First Article Body',
  385. 'published' => 'Y',
  386. ];
  387. // test updated state
  388. $result = $this->connection->newQuery()
  389. ->select('*')
  390. ->from('articles')
  391. ->execute();
  392. $this->assertEquals($expected, $result->fetch('assoc'));
  393. $result->closeCursor();
  394. }
  395. }