3 namespace Drupal\KernelTests\Core\Database;
5 use Drupal\Core\Database\Database;
6 use Drupal\Core\Database\Query\Condition;
7 use Drupal\Core\Database\RowCountException;
8 use Drupal\user\Entity\User;
11 * Tests the Select query builder with more complex queries.
15 class SelectComplexTest extends DatabaseTestBase {
22 public static $modules = ['system', 'user', 'node_access_test', 'field'];
25 * Tests simple JOIN statements.
27 public function testDefaultJoin() {
28 $query = db_select('test_task', 't');
29 $people_alias = $query->join('test', 'p', 't.pid = p.id');
30 $name_field = $query->addField($people_alias, 'name', 'name');
31 $query->addField('t', 'task', 'task');
32 $priority_field = $query->addField('t', 'priority', 'priority');
34 $query->orderBy($priority_field);
35 $result = $query->execute();
39 foreach ($result as $record) {
41 $this->assertTrue($record->$priority_field >= $last_priority, 'Results returned in correct order.');
42 $this->assertNotEqual($record->$name_field, 'Ringo', 'Taskless person not selected.');
43 $last_priority = $record->$priority_field;
46 $this->assertEqual($num_records, 7, 'Returned the correct number of rows.');
50 * Tests LEFT OUTER joins.
52 public function testLeftOuterJoin() {
53 $query = db_select('test', 'p');
54 $people_alias = $query->leftJoin('test_task', 't', 't.pid = p.id');
55 $name_field = $query->addField('p', 'name', 'name');
56 $query->addField($people_alias, 'task', 'task');
57 $query->addField($people_alias, 'priority', 'priority');
59 $query->orderBy($name_field);
60 $result = $query->execute();
65 foreach ($result as $record) {
67 $this->assertTrue(strcmp($record->$name_field, $last_name) >= 0, 'Results returned in correct order.');
70 $this->assertEqual($num_records, 8, 'Returned the correct number of rows.');
74 * Tests GROUP BY clauses.
76 public function testGroupBy() {
77 $query = db_select('test_task', 't');
78 $count_field = $query->addExpression('COUNT(task)', 'num');
79 $task_field = $query->addField('t', 'task');
80 $query->orderBy($count_field);
81 $query->groupBy($task_field);
82 $result = $query->execute();
87 foreach ($result as $record) {
89 $this->assertTrue($record->$count_field >= $last_count, 'Results returned in correct order.');
90 $last_count = $record->$count_field;
91 $records[$record->$task_field] = $record->$count_field;
98 'found new band' => 1,
99 'perform at superbowl' => 1,
102 foreach ($correct_results as $task => $count) {
103 $this->assertEqual($records[$task], $count, format_string("Correct number of '@task' records found.", ['@task' => $task]));
106 $this->assertEqual($num_records, 6, 'Returned the correct number of total rows.');
110 * Tests GROUP BY and HAVING clauses together.
112 public function testGroupByAndHaving() {
113 $query = db_select('test_task', 't');
114 $count_field = $query->addExpression('COUNT(task)', 'num');
115 $task_field = $query->addField('t', 'task');
116 $query->orderBy($count_field);
117 $query->groupBy($task_field);
118 $query->having('COUNT(task) >= 2');
119 $result = $query->execute();
124 foreach ($result as $record) {
126 $this->assertTrue($record->$count_field >= 2, 'Record has the minimum count.');
127 $this->assertTrue($record->$count_field >= $last_count, 'Results returned in correct order.');
128 $last_count = $record->$count_field;
129 $records[$record->$task_field] = $record->$count_field;
136 foreach ($correct_results as $task => $count) {
137 $this->assertEqual($records[$task], $count, format_string("Correct number of '@task' records found.", ['@task' => $task]));
140 $this->assertEqual($num_records, 1, 'Returned the correct number of total rows.');
144 * Tests range queries.
146 * The SQL clause varies with the database.
148 public function testRange() {
149 $query = db_select('test');
150 $query->addField('test', 'name');
151 $query->addField('test', 'age', 'age');
153 $query_result = $query->countQuery()->execute()->fetchField();
155 $this->assertEqual($query_result, 2, 'Returned the correct number of rows.');
159 * Test whether the range property of a select clause can be undone.
161 public function testRangeUndo() {
162 $query = db_select('test');
163 $name_field = $query->addField('test', 'name');
164 $age_field = $query->addField('test', 'age', 'age');
166 $query->range(NULL, NULL);
167 $query_result = $query->countQuery()->execute()->fetchField();
169 $this->assertEqual($query_result, 4, 'Returned the correct number of rows.');
173 * Tests distinct queries.
175 public function testDistinct() {
176 $query = db_select('test_task');
177 $query->addField('test_task', 'task');
179 $query_result = $query->countQuery()->execute()->fetchField();
181 $this->assertEqual($query_result, 6, 'Returned the correct number of rows.');
185 * Tests that we can generate a count query from a built query.
187 public function testCountQuery() {
188 $query = db_select('test');
189 $name_field = $query->addField('test', 'name');
190 $age_field = $query->addField('test', 'age', 'age');
191 $query->orderBy('name');
193 $count = $query->countQuery()->execute()->fetchField();
195 $this->assertEqual($count, 4, 'Counted the correct number of records.');
197 // Now make sure we didn't break the original query! We should still have
198 // all of the fields we asked for.
199 $record = $query->execute()->fetch();
200 $this->assertEqual($record->$name_field, 'George', 'Correct data retrieved.');
201 $this->assertEqual($record->$age_field, 27, 'Correct data retrieved.');
205 * Tests having queries.
207 public function testHavingCountQuery() {
208 $query = db_select('test')
209 ->extend('Drupal\Core\Database\Query\PagerSelectExtender')
211 ->having('age + 1 > 0');
212 $query->addField('test', 'age');
213 $query->addExpression('age + 1');
214 $count = count($query->execute()->fetchCol());
215 $this->assertEqual($count, 4, 'Counted the correct number of records.');
219 * Tests that countQuery removes 'all_fields' statements and ordering clauses.
221 public function testCountQueryRemovals() {
222 $query = db_select('test');
223 $query->fields('test');
224 $query->orderBy('name');
225 $count = $query->countQuery();
227 // Check that the 'all_fields' statement is handled properly.
228 $tables = $query->getTables();
229 $this->assertEqual($tables['test']['all_fields'], 1, 'Query correctly sets \'all_fields\' statement.');
230 $tables = $count->getTables();
231 $this->assertFalse(isset($tables['test']['all_fields']), 'Count query correctly unsets \'all_fields\' statement.');
233 // Check that the ordering clause is handled properly.
234 $orderby = $query->getOrderBy();
235 // The orderby string is different for PostgreSQL.
236 // @see Drupal\Core\Database\Driver\pgsql\Select::orderBy()
237 $db_type = Database::getConnection()->databaseType();
238 $this->assertEqual($orderby['name'], ($db_type == 'pgsql' ? 'ASC NULLS FIRST' : 'ASC'), 'Query correctly sets ordering clause.');
239 $orderby = $count->getOrderBy();
240 $this->assertFalse(isset($orderby['name']), 'Count query correctly unsets ordering clause.');
242 // Make sure that the count query works.
243 $count = $count->execute()->fetchField();
245 $this->assertEqual($count, 4, 'Counted the correct number of records.');
250 * Tests that countQuery properly removes fields and expressions.
252 public function testCountQueryFieldRemovals() {
253 // countQuery should remove all fields and expressions, so this can be
254 // tested by adding a non-existent field and expression: if it ends
255 // up in the query, an error will be thrown. If not, it will return the
256 // number of records, which in this case happens to be 4 (there are four
257 // records in the {test} table).
258 $query = db_select('test');
259 $query->fields('test', ['fail']);
260 $this->assertEqual(4, $query->countQuery()->execute()->fetchField(), 'Count Query removed fields');
262 $query = db_select('test');
263 $query->addExpression('fail');
264 $this->assertEqual(4, $query->countQuery()->execute()->fetchField(), 'Count Query removed expressions');
268 * Tests that we can generate a count query from a query with distinct.
270 public function testCountQueryDistinct() {
271 $query = db_select('test_task');
272 $query->addField('test_task', 'task');
275 $count = $query->countQuery()->execute()->fetchField();
277 $this->assertEqual($count, 6, 'Counted the correct number of records.');
281 * Tests that we can generate a count query from a query with GROUP BY.
283 public function testCountQueryGroupBy() {
284 $query = db_select('test_task');
285 $query->addField('test_task', 'pid');
286 $query->groupBy('pid');
288 $count = $query->countQuery()->execute()->fetchField();
290 $this->assertEqual($count, 3, 'Counted the correct number of records.');
292 // Use a column alias as, without one, the query can succeed for the wrong
294 $query = db_select('test_task');
295 $query->addField('test_task', 'pid', 'pid_alias');
296 $query->addExpression('COUNT(test_task.task)', 'count');
297 $query->groupBy('pid_alias');
298 $query->orderBy('pid_alias', 'asc');
300 $count = $query->countQuery()->execute()->fetchField();
302 $this->assertEqual($count, 3, 'Counted the correct number of records.');
306 * Confirms that we can properly nest conditional clauses.
308 public function testNestedConditions() {
309 // This query should translate to:
310 // "SELECT job FROM {test} WHERE name = 'Paul' AND (age = 26 OR age = 27)"
311 // That should find only one record. Yes it's a non-optimal way of writing
312 // that query but that's not the point!
313 $query = db_select('test');
314 $query->addField('test', 'job');
315 $query->condition('name', 'Paul');
316 $query->condition((new Condition('OR'))->condition('age', 26)->condition('age', 27));
318 $job = $query->execute()->fetchField();
319 $this->assertEqual($job, 'Songwriter', 'Correct data retrieved.');
323 * Confirms we can join on a single table twice with a dynamic alias.
325 public function testJoinTwice() {
326 $query = db_select('test')->fields('test');
327 $alias = $query->join('test', 'test', 'test.job = %alias.job');
328 $query->addField($alias, 'name', 'othername');
329 $query->addField($alias, 'job', 'otherjob');
330 $query->where("$alias.name <> test.name");
331 $crowded_job = $query->execute()->fetch();
332 $this->assertEqual($crowded_job->job, $crowded_job->otherjob, 'Correctly joined same table twice.');
333 $this->assertNotEqual($crowded_job->name, $crowded_job->othername, 'Correctly joined same table twice.');
337 * Tests that we can join on a query.
339 public function testJoinSubquery() {
340 $this->installSchema('system', 'sequences');
342 $account = User::create([
343 'name' => $this->randomMachineName(),
344 'mail' => $this->randomMachineName() . '@example.com',
347 $query = db_select('test_task', 'tt', ['target' => 'replica']);
348 $query->addExpression('tt.pid + 1', 'abc');
349 $query->condition('priority', 1, '>');
350 $query->condition('priority', 100, '<');
352 $subquery = db_select('test', 'tp');
353 $subquery->join('test_one_blob', 'tpb', 'tp.id = tpb.id');
354 $subquery->join('node', 'n', 'tp.id = n.nid');
355 $subquery->addTag('node_access');
356 $subquery->addMetaData('account', $account);
357 $subquery->addField('tp', 'id');
358 $subquery->condition('age', 5, '>');
359 $subquery->condition('age', 500, '<');
361 $query->leftJoin($subquery, 'sq', 'tt.pid = sq.id');
362 $query->join('test_one_blob', 'tb3', 'tt.pid = tb3.id');
364 // Construct the query string.
365 // This is the same sequence that SelectQuery::execute() goes through.
366 $query->preExecute();
367 $query->getArguments();
368 $str = (string) $query;
370 // Verify that the string only has one copy of condition placeholder 0.
371 $pos = strpos($str, 'db_condition_placeholder_0', 0);
372 $pos2 = strpos($str, 'db_condition_placeholder_0', $pos + 1);
373 $this->assertFalse($pos2, 'Condition placeholder is not repeated.');
377 * Tests that rowCount() throws exception on SELECT query.
379 public function testSelectWithRowCount() {
380 $query = db_select('test');
381 $query->addField('test', 'name');
382 $result = $query->execute();
387 catch (RowCountException $e) {
390 $this->assertTrue($exception, 'Exception was thrown');
394 * Test that join conditions can use Condition objects.
396 public function testJoinConditionObject() {
397 // Same test as testDefaultJoin, but with a Condition object.
398 $query = db_select('test_task', 't');
399 $join_cond = (new Condition('AND'))->where('t.pid = p.id');
400 $people_alias = $query->join('test', 'p', $join_cond);
401 $name_field = $query->addField($people_alias, 'name', 'name');
402 $query->addField('t', 'task', 'task');
403 $priority_field = $query->addField('t', 'priority', 'priority');
405 $query->orderBy($priority_field);
406 $result = $query->execute();
410 foreach ($result as $record) {
412 $this->assertTrue($record->$priority_field >= $last_priority, 'Results returned in correct order.');
413 $this->assertNotEqual($record->$name_field, 'Ringo', 'Taskless person not selected.');
414 $last_priority = $record->$priority_field;
417 $this->assertEqual($num_records, 7, 'Returned the correct number of rows.');
419 // Test a condition object that creates placeholders.
422 $join_cond = (new Condition('AND'))
423 ->condition('t1.name', $t1_name)
424 ->condition('t2.name', $t2_name);
425 $query = db_select('test', 't1');
426 $query->innerJoin('test', 't2', $join_cond);
427 $query->addField('t1', 'name', 't1_name');
428 $query->addField('t2', 'name', 't2_name');
430 $num_records = $query->countQuery()->execute()->fetchField();
431 $this->assertEqual($num_records, 1, 'Query expected to return 1 row. Actual: ' . $num_records);
432 if ($num_records == 1) {
433 $record = $query->execute()->fetchObject();
434 $this->assertEqual($record->t1_name, $t1_name, 'Query expected to retrieve name ' . $t1_name . ' from table t1. Actual: ' . $record->t1_name);
435 $this->assertEqual($record->t2_name, $t2_name, 'Query expected to retrieve name ' . $t2_name . ' from table t2. Actual: ' . $record->t2_name);