SelectComplexTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. <?php
  2. namespace Drupal\KernelTests\Core\Database;
  3. use Drupal\Component\Render\FormattableMarkup;
  4. use Drupal\Core\Database\Database;
  5. use Drupal\Core\Database\Query\Condition;
  6. use Drupal\Core\Database\RowCountException;
  7. use Drupal\user\Entity\User;
  8. /**
  9. * Tests the Select query builder with more complex queries.
  10. *
  11. * @group Database
  12. */
  13. class SelectComplexTest extends DatabaseTestBase {
  14. /**
  15. * Modules to enable.
  16. *
  17. * @var array
  18. */
  19. public static $modules = ['system', 'user', 'node_access_test', 'field'];
  20. /**
  21. * Tests simple JOIN statements.
  22. */
  23. public function testDefaultJoin() {
  24. $query = $this->connection->select('test_task', 't');
  25. $people_alias = $query->join('test', 'p', 't.pid = p.id');
  26. $name_field = $query->addField($people_alias, 'name', 'name');
  27. $query->addField('t', 'task', 'task');
  28. $priority_field = $query->addField('t', 'priority', 'priority');
  29. $query->orderBy($priority_field);
  30. $result = $query->execute();
  31. $num_records = 0;
  32. $last_priority = 0;
  33. foreach ($result as $record) {
  34. $num_records++;
  35. $this->assertTrue($record->$priority_field >= $last_priority, 'Results returned in correct order.');
  36. $this->assertNotEqual($record->$name_field, 'Ringo', 'Taskless person not selected.');
  37. $last_priority = $record->$priority_field;
  38. }
  39. $this->assertEqual($num_records, 7, 'Returned the correct number of rows.');
  40. }
  41. /**
  42. * Tests LEFT OUTER joins.
  43. */
  44. public function testLeftOuterJoin() {
  45. $query = $this->connection->select('test', 'p');
  46. $people_alias = $query->leftJoin('test_task', 't', 't.pid = p.id');
  47. $name_field = $query->addField('p', 'name', 'name');
  48. $query->addField($people_alias, 'task', 'task');
  49. $query->addField($people_alias, 'priority', 'priority');
  50. $query->orderBy($name_field);
  51. $result = $query->execute();
  52. $num_records = 0;
  53. $last_name = 0;
  54. foreach ($result as $record) {
  55. $num_records++;
  56. $this->assertTrue(strcmp($record->$name_field, $last_name) >= 0, 'Results returned in correct order.');
  57. }
  58. $this->assertEqual($num_records, 8, 'Returned the correct number of rows.');
  59. }
  60. /**
  61. * Tests GROUP BY clauses.
  62. */
  63. public function testGroupBy() {
  64. $query = $this->connection->select('test_task', 't');
  65. $count_field = $query->addExpression('COUNT(task)', 'num');
  66. $task_field = $query->addField('t', 'task');
  67. $query->orderBy($count_field);
  68. $query->groupBy($task_field);
  69. $result = $query->execute();
  70. $num_records = 0;
  71. $last_count = 0;
  72. $records = [];
  73. foreach ($result as $record) {
  74. $num_records++;
  75. $this->assertTrue($record->$count_field >= $last_count, 'Results returned in correct order.');
  76. $last_count = $record->$count_field;
  77. $records[$record->$task_field] = $record->$count_field;
  78. }
  79. $correct_results = [
  80. 'eat' => 1,
  81. 'sleep' => 2,
  82. 'code' => 1,
  83. 'found new band' => 1,
  84. 'perform at superbowl' => 1,
  85. ];
  86. foreach ($correct_results as $task => $count) {
  87. $this->assertEqual($records[$task], $count, new FormattableMarkup("Correct number of '@task' records found.", ['@task' => $task]));
  88. }
  89. $this->assertEqual($num_records, 6, 'Returned the correct number of total rows.');
  90. }
  91. /**
  92. * Tests GROUP BY and HAVING clauses together.
  93. */
  94. public function testGroupByAndHaving() {
  95. $query = $this->connection->select('test_task', 't');
  96. $count_field = $query->addExpression('COUNT(task)', 'num');
  97. $task_field = $query->addField('t', 'task');
  98. $query->orderBy($count_field);
  99. $query->groupBy($task_field);
  100. $query->having('COUNT(task) >= 2');
  101. $result = $query->execute();
  102. $num_records = 0;
  103. $last_count = 0;
  104. $records = [];
  105. foreach ($result as $record) {
  106. $num_records++;
  107. $this->assertTrue($record->$count_field >= 2, 'Record has the minimum count.');
  108. $this->assertTrue($record->$count_field >= $last_count, 'Results returned in correct order.');
  109. $last_count = $record->$count_field;
  110. $records[$record->$task_field] = $record->$count_field;
  111. }
  112. $correct_results = [
  113. 'sleep' => 2,
  114. ];
  115. foreach ($correct_results as $task => $count) {
  116. $this->assertEqual($records[$task], $count, new FormattableMarkup("Correct number of '@task' records found.", ['@task' => $task]));
  117. }
  118. $this->assertEqual($num_records, 1, 'Returned the correct number of total rows.');
  119. }
  120. /**
  121. * Tests range queries.
  122. *
  123. * The SQL clause varies with the database.
  124. */
  125. public function testRange() {
  126. $query = $this->connection->select('test');
  127. $query->addField('test', 'name');
  128. $query->addField('test', 'age', 'age');
  129. $query->range(0, 2);
  130. $query_result = $query->countQuery()->execute()->fetchField();
  131. $this->assertEqual($query_result, 2, 'Returned the correct number of rows.');
  132. }
  133. /**
  134. * Test whether the range property of a select clause can be undone.
  135. */
  136. public function testRangeUndo() {
  137. $query = $this->connection->select('test');
  138. $query->addField('test', 'name');
  139. $query->addField('test', 'age', 'age');
  140. $query->range(0, 2);
  141. $query->range(NULL, NULL);
  142. $query_result = $query->countQuery()->execute()->fetchField();
  143. $this->assertEqual($query_result, 4, 'Returned the correct number of rows.');
  144. }
  145. /**
  146. * Tests distinct queries.
  147. */
  148. public function testDistinct() {
  149. $query = $this->connection->select('test_task');
  150. $query->addField('test_task', 'task');
  151. $query->distinct();
  152. $query_result = $query->countQuery()->execute()->fetchField();
  153. $this->assertEqual($query_result, 6, 'Returned the correct number of rows.');
  154. }
  155. /**
  156. * Tests that we can generate a count query from a built query.
  157. */
  158. public function testCountQuery() {
  159. $query = $this->connection->select('test');
  160. $name_field = $query->addField('test', 'name');
  161. $age_field = $query->addField('test', 'age', 'age');
  162. $query->orderBy('name');
  163. $count = $query->countQuery()->execute()->fetchField();
  164. $this->assertEqual($count, 4, 'Counted the correct number of records.');
  165. // Now make sure we didn't break the original query! We should still have
  166. // all of the fields we asked for.
  167. $record = $query->execute()->fetch();
  168. $this->assertEqual($record->$name_field, 'George', 'Correct data retrieved.');
  169. $this->assertEqual($record->$age_field, 27, 'Correct data retrieved.');
  170. }
  171. /**
  172. * Tests having queries.
  173. */
  174. public function testHavingCountQuery() {
  175. $query = $this->connection->select('test')
  176. ->extend('Drupal\Core\Database\Query\PagerSelectExtender')
  177. ->groupBy('age')
  178. ->having('age + 1 > 0');
  179. $query->addField('test', 'age');
  180. $query->addExpression('age + 1');
  181. $count = count($query->execute()->fetchCol());
  182. $this->assertEqual($count, 4, 'Counted the correct number of records.');
  183. }
  184. /**
  185. * Tests that countQuery removes 'all_fields' statements and ordering clauses.
  186. */
  187. public function testCountQueryRemovals() {
  188. $query = $this->connection->select('test');
  189. $query->fields('test');
  190. $query->orderBy('name');
  191. $count = $query->countQuery();
  192. // Check that the 'all_fields' statement is handled properly.
  193. $tables = $query->getTables();
  194. $this->assertEqual($tables['test']['all_fields'], 1, 'Query correctly sets \'all_fields\' statement.');
  195. $tables = $count->getTables();
  196. $this->assertFalse(isset($tables['test']['all_fields']), 'Count query correctly unsets \'all_fields\' statement.');
  197. // Check that the ordering clause is handled properly.
  198. $orderby = $query->getOrderBy();
  199. // The orderby string is different for PostgreSQL.
  200. // @see Drupal\Core\Database\Driver\pgsql\Select::orderBy()
  201. $db_type = Database::getConnection()->databaseType();
  202. $this->assertEqual($orderby['name'], ($db_type == 'pgsql' ? 'ASC NULLS FIRST' : 'ASC'), 'Query correctly sets ordering clause.');
  203. $orderby = $count->getOrderBy();
  204. $this->assertFalse(isset($orderby['name']), 'Count query correctly unsets ordering clause.');
  205. // Make sure that the count query works.
  206. $count = $count->execute()->fetchField();
  207. $this->assertEqual($count, 4, 'Counted the correct number of records.');
  208. }
  209. /**
  210. * Tests that countQuery properly removes fields and expressions.
  211. */
  212. public function testCountQueryFieldRemovals() {
  213. // countQuery should remove all fields and expressions, so this can be
  214. // tested by adding a non-existent field and expression: if it ends
  215. // up in the query, an error will be thrown. If not, it will return the
  216. // number of records, which in this case happens to be 4 (there are four
  217. // records in the {test} table).
  218. $query = $this->connection->select('test');
  219. $query->fields('test', ['fail']);
  220. $this->assertEqual(4, $query->countQuery()->execute()->fetchField(), 'Count Query removed fields');
  221. $query = $this->connection->select('test');
  222. $query->addExpression('fail');
  223. $this->assertEqual(4, $query->countQuery()->execute()->fetchField(), 'Count Query removed expressions');
  224. }
  225. /**
  226. * Tests that we can generate a count query from a query with distinct.
  227. */
  228. public function testCountQueryDistinct() {
  229. $query = $this->connection->select('test_task');
  230. $query->addField('test_task', 'task');
  231. $query->distinct();
  232. $count = $query->countQuery()->execute()->fetchField();
  233. $this->assertEqual($count, 6, 'Counted the correct number of records.');
  234. }
  235. /**
  236. * Tests that we can generate a count query from a query with GROUP BY.
  237. */
  238. public function testCountQueryGroupBy() {
  239. $query = $this->connection->select('test_task');
  240. $query->addField('test_task', 'pid');
  241. $query->groupBy('pid');
  242. $count = $query->countQuery()->execute()->fetchField();
  243. $this->assertEqual($count, 3, 'Counted the correct number of records.');
  244. // Use a column alias as, without one, the query can succeed for the wrong
  245. // reason.
  246. $query = $this->connection->select('test_task');
  247. $query->addField('test_task', 'pid', 'pid_alias');
  248. $query->addExpression('COUNT(test_task.task)', 'count');
  249. $query->groupBy('pid_alias');
  250. $query->orderBy('pid_alias', 'asc');
  251. $count = $query->countQuery()->execute()->fetchField();
  252. $this->assertEqual($count, 3, 'Counted the correct number of records.');
  253. }
  254. /**
  255. * Confirms that we can properly nest conditional clauses.
  256. */
  257. public function testNestedConditions() {
  258. // This query should translate to:
  259. // "SELECT job FROM {test} WHERE name = 'Paul' AND (age = 26 OR age = 27)"
  260. // That should find only one record. Yes it's a non-optimal way of writing
  261. // that query but that's not the point!
  262. $query = $this->connection->select('test');
  263. $query->addField('test', 'job');
  264. $query->condition('name', 'Paul');
  265. $query->condition((new Condition('OR'))->condition('age', 26)->condition('age', 27));
  266. $job = $query->execute()->fetchField();
  267. $this->assertEqual($job, 'Songwriter', 'Correct data retrieved.');
  268. }
  269. /**
  270. * Confirms we can join on a single table twice with a dynamic alias.
  271. */
  272. public function testJoinTwice() {
  273. $query = $this->connection->select('test')->fields('test');
  274. $alias = $query->join('test', 'test', 'test.job = %alias.job');
  275. $query->addField($alias, 'name', 'othername');
  276. $query->addField($alias, 'job', 'otherjob');
  277. $query->where("$alias.name <> test.name");
  278. $crowded_job = $query->execute()->fetch();
  279. $this->assertEqual($crowded_job->job, $crowded_job->otherjob, 'Correctly joined same table twice.');
  280. $this->assertNotEqual($crowded_job->name, $crowded_job->othername, 'Correctly joined same table twice.');
  281. }
  282. /**
  283. * Tests that we can join on a query.
  284. */
  285. public function testJoinSubquery() {
  286. $this->installSchema('system', 'sequences');
  287. $account = User::create([
  288. 'name' => $this->randomMachineName(),
  289. 'mail' => $this->randomMachineName() . '@example.com',
  290. ]);
  291. $query = Database::getConnection('replica')->select('test_task', 'tt');
  292. $query->addExpression('tt.pid + 1', 'abc');
  293. $query->condition('priority', 1, '>');
  294. $query->condition('priority', 100, '<');
  295. $subquery = $this->connection->select('test', 'tp');
  296. $subquery->join('test_one_blob', 'tpb', 'tp.id = tpb.id');
  297. $subquery->join('node', 'n', 'tp.id = n.nid');
  298. $subquery->addTag('node_access');
  299. $subquery->addMetaData('account', $account);
  300. $subquery->addField('tp', 'id');
  301. $subquery->condition('age', 5, '>');
  302. $subquery->condition('age', 500, '<');
  303. $query->leftJoin($subquery, 'sq', 'tt.pid = sq.id');
  304. $query->join('test_one_blob', 'tb3', 'tt.pid = tb3.id');
  305. // Construct the query string.
  306. // This is the same sequence that SelectQuery::execute() goes through.
  307. $query->preExecute();
  308. $query->getArguments();
  309. $str = (string) $query;
  310. // Verify that the string only has one copy of condition placeholder 0.
  311. $pos = strpos($str, 'db_condition_placeholder_0', 0);
  312. $pos2 = strpos($str, 'db_condition_placeholder_0', $pos + 1);
  313. $this->assertFalse($pos2, 'Condition placeholder is not repeated.');
  314. }
  315. /**
  316. * Tests that rowCount() throws exception on SELECT query.
  317. */
  318. public function testSelectWithRowCount() {
  319. $query = $this->connection->select('test');
  320. $query->addField('test', 'name');
  321. $result = $query->execute();
  322. try {
  323. $result->rowCount();
  324. $exception = FALSE;
  325. }
  326. catch (RowCountException $e) {
  327. $exception = TRUE;
  328. }
  329. $this->assertTrue($exception, 'Exception was thrown');
  330. }
  331. /**
  332. * Test that join conditions can use Condition objects.
  333. */
  334. public function testJoinConditionObject() {
  335. // Same test as testDefaultJoin, but with a Condition object.
  336. $query = $this->connection->select('test_task', 't');
  337. $join_cond = (new Condition('AND'))->where('t.pid = p.id');
  338. $people_alias = $query->join('test', 'p', $join_cond);
  339. $name_field = $query->addField($people_alias, 'name', 'name');
  340. $query->addField('t', 'task', 'task');
  341. $priority_field = $query->addField('t', 'priority', 'priority');
  342. $query->orderBy($priority_field);
  343. $result = $query->execute();
  344. $num_records = 0;
  345. $last_priority = 0;
  346. foreach ($result as $record) {
  347. $num_records++;
  348. $this->assertTrue($record->$priority_field >= $last_priority, 'Results returned in correct order.');
  349. $this->assertNotEqual($record->$name_field, 'Ringo', 'Taskless person not selected.');
  350. $last_priority = $record->$priority_field;
  351. }
  352. $this->assertEqual($num_records, 7, 'Returned the correct number of rows.');
  353. // Test a condition object that creates placeholders.
  354. $t1_name = 'John';
  355. $t2_name = 'George';
  356. $join_cond = (new Condition('AND'))
  357. ->condition('t1.name', $t1_name)
  358. ->condition('t2.name', $t2_name);
  359. $query = $this->connection->select('test', 't1');
  360. $query->innerJoin('test', 't2', $join_cond);
  361. $query->addField('t1', 'name', 't1_name');
  362. $query->addField('t2', 'name', 't2_name');
  363. $num_records = $query->countQuery()->execute()->fetchField();
  364. $this->assertEqual($num_records, 1, 'Query expected to return 1 row. Actual: ' . $num_records);
  365. if ($num_records == 1) {
  366. $record = $query->execute()->fetchObject();
  367. $this->assertEqual($record->t1_name, $t1_name, 'Query expected to retrieve name ' . $t1_name . ' from table t1. Actual: ' . $record->t1_name);
  368. $this->assertEqual($record->t2_name, $t2_name, 'Query expected to retrieve name ' . $t2_name . ' from table t2. Actual: ' . $record->t2_name);
  369. }
  370. }
  371. }