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.');
249 * Tests that countQuery properly removes fields and expressions.
251 public function testCountQueryFieldRemovals() {
252 // countQuery should remove all fields and expressions, so this can be
253 // tested by adding a non-existent field and expression: if it ends
254 // up in the query, an error will be thrown. If not, it will return the
255 // number of records, which in this case happens to be 4 (there are four
256 // records in the {test} table).
257 $query = db_select('test');
258 $query->fields('test', ['fail']);
259 $this->assertEqual(4, $query->countQuery()->execute()->fetchField(), 'Count Query removed fields');
261 $query = db_select('test');
262 $query->addExpression('fail');
263 $this->assertEqual(4, $query->countQuery()->execute()->fetchField(), 'Count Query removed expressions');
267 * Tests that we can generate a count query from a query with distinct.
269 public function testCountQueryDistinct() {
270 $query = db_select('test_task');
271 $query->addField('test_task', 'task');
274 $count = $query->countQuery()->execute()->fetchField();
276 $this->assertEqual($count, 6, 'Counted the correct number of records.');
280 * Tests that we can generate a count query from a query with GROUP BY.
282 public function testCountQueryGroupBy() {
283 $query = db_select('test_task');
284 $query->addField('test_task', 'pid');
285 $query->groupBy('pid');
287 $count = $query->countQuery()->execute()->fetchField();
289 $this->assertEqual($count, 3, 'Counted the correct number of records.');
291 // Use a column alias as, without one, the query can succeed for the wrong
293 $query = db_select('test_task');
294 $query->addField('test_task', 'pid', 'pid_alias');
295 $query->addExpression('COUNT(test_task.task)', 'count');
296 $query->groupBy('pid_alias');
297 $query->orderBy('pid_alias', 'asc');
299 $count = $query->countQuery()->execute()->fetchField();
301 $this->assertEqual($count, 3, 'Counted the correct number of records.');
305 * Confirms that we can properly nest conditional clauses.
307 public function testNestedConditions() {
308 // This query should translate to:
309 // "SELECT job FROM {test} WHERE name = 'Paul' AND (age = 26 OR age = 27)"
310 // That should find only one record. Yes it's a non-optimal way of writing
311 // that query but that's not the point!
312 $query = db_select('test');
313 $query->addField('test', 'job');
314 $query->condition('name', 'Paul');
315 $query->condition((new Condition('OR'))->condition('age', 26)->condition('age', 27));
317 $job = $query->execute()->fetchField();
318 $this->assertEqual($job, 'Songwriter', 'Correct data retrieved.');
322 * Confirms we can join on a single table twice with a dynamic alias.
324 public function testJoinTwice() {
325 $query = db_select('test')->fields('test');
326 $alias = $query->join('test', 'test', 'test.job = %alias.job');
327 $query->addField($alias, 'name', 'othername');
328 $query->addField($alias, 'job', 'otherjob');
329 $query->where("$alias.name <> test.name");
330 $crowded_job = $query->execute()->fetch();
331 $this->assertEqual($crowded_job->job, $crowded_job->otherjob, 'Correctly joined same table twice.');
332 $this->assertNotEqual($crowded_job->name, $crowded_job->othername, 'Correctly joined same table twice.');
336 * Tests that we can join on a query.
338 public function testJoinSubquery() {
339 $this->installSchema('system', 'sequences');
341 $account = User::create([
342 'name' => $this->randomMachineName(),
343 'mail' => $this->randomMachineName() . '@example.com',
346 $query = db_select('test_task', 'tt', ['target' => 'replica']);
347 $query->addExpression('tt.pid + 1', 'abc');
348 $query->condition('priority', 1, '>');
349 $query->condition('priority', 100, '<');
351 $subquery = db_select('test', 'tp');
352 $subquery->join('test_one_blob', 'tpb', 'tp.id = tpb.id');
353 $subquery->join('node', 'n', 'tp.id = n.nid');
354 $subquery->addTag('node_access');
355 $subquery->addMetaData('account', $account);
356 $subquery->addField('tp', 'id');
357 $subquery->condition('age', 5, '>');
358 $subquery->condition('age', 500, '<');
360 $query->leftJoin($subquery, 'sq', 'tt.pid = sq.id');
361 $query->join('test_one_blob', 'tb3', 'tt.pid = tb3.id');
363 // Construct the query string.
364 // This is the same sequence that SelectQuery::execute() goes through.
365 $query->preExecute();
366 $query->getArguments();
367 $str = (string) $query;
369 // Verify that the string only has one copy of condition placeholder 0.
370 $pos = strpos($str, 'db_condition_placeholder_0', 0);
371 $pos2 = strpos($str, 'db_condition_placeholder_0', $pos + 1);
372 $this->assertFalse($pos2, 'Condition placeholder is not repeated.');
376 * Tests that rowCount() throws exception on SELECT query.
378 public function testSelectWithRowCount() {
379 $query = db_select('test');
380 $query->addField('test', 'name');
381 $result = $query->execute();
386 catch (RowCountException $e) {
389 $this->assertTrue($exception, 'Exception was thrown');
393 * Test that join conditions can use Condition objects.
395 public function testJoinConditionObject() {
396 // Same test as testDefaultJoin, but with a Condition object.
397 $query = db_select('test_task', 't');
398 $join_cond = (new Condition('AND'))->where('t.pid = p.id');
399 $people_alias = $query->join('test', 'p', $join_cond);
400 $name_field = $query->addField($people_alias, 'name', 'name');
401 $query->addField('t', 'task', 'task');
402 $priority_field = $query->addField('t', 'priority', 'priority');
404 $query->orderBy($priority_field);
405 $result = $query->execute();
409 foreach ($result as $record) {
411 $this->assertTrue($record->$priority_field >= $last_priority, 'Results returned in correct order.');
412 $this->assertNotEqual($record->$name_field, 'Ringo', 'Taskless person not selected.');
413 $last_priority = $record->$priority_field;
416 $this->assertEqual($num_records, 7, 'Returned the correct number of rows.');
418 // Test a condition object that creates placeholders.
421 $join_cond = (new Condition('AND'))
422 ->condition('t1.name', $t1_name)
423 ->condition('t2.name', $t2_name);
424 $query = db_select('test', 't1');
425 $query->innerJoin('test', 't2', $join_cond);
426 $query->addField('t1', 'name', 't1_name');
427 $query->addField('t2', 'name', 't2_name');
429 $num_records = $query->countQuery()->execute()->fetchField();
430 $this->assertEqual($num_records, 1, 'Query expected to return 1 row. Actual: ' . $num_records);
431 if ($num_records == 1) {
432 $record = $query->execute()->fetchObject();
433 $this->assertEqual($record->t1_name, $t1_name, 'Query expected to retrieve name ' . $t1_name . ' from table t1. Actual: ' . $record->t1_name);
434 $this->assertEqual($record->t2_name, $t2_name, 'Query expected to retrieve name ' . $t2_name . ' from table t2. Actual: ' . $record->t2_name);