3 namespace Drupal\KernelTests\Core\Database;
5 use Drupal\Core\Database\Database;
6 use Drupal\Core\Database\RowCountException;
7 use Drupal\user\Entity\User;
10 * Tests the Select query builder with more complex queries.
14 class SelectComplexTest extends DatabaseTestBase {
21 public static $modules = ['system', 'user', 'node_access_test', 'field'];
24 * Tests simple JOIN statements.
26 public function testDefaultJoin() {
27 $query = db_select('test_task', 't');
28 $people_alias = $query->join('test', 'p', 't.pid = p.id');
29 $name_field = $query->addField($people_alias, 'name', 'name');
30 $query->addField('t', 'task', 'task');
31 $priority_field = $query->addField('t', 'priority', 'priority');
33 $query->orderBy($priority_field);
34 $result = $query->execute();
38 foreach ($result as $record) {
40 $this->assertTrue($record->$priority_field >= $last_priority, 'Results returned in correct order.');
41 $this->assertNotEqual($record->$name_field, 'Ringo', 'Taskless person not selected.');
42 $last_priority = $record->$priority_field;
45 $this->assertEqual($num_records, 7, 'Returned the correct number of rows.');
49 * Tests LEFT OUTER joins.
51 public function testLeftOuterJoin() {
52 $query = db_select('test', 'p');
53 $people_alias = $query->leftJoin('test_task', 't', 't.pid = p.id');
54 $name_field = $query->addField('p', 'name', 'name');
55 $query->addField($people_alias, 'task', 'task');
56 $query->addField($people_alias, 'priority', 'priority');
58 $query->orderBy($name_field);
59 $result = $query->execute();
64 foreach ($result as $record) {
66 $this->assertTrue(strcmp($record->$name_field, $last_name) >= 0, 'Results returned in correct order.');
69 $this->assertEqual($num_records, 8, 'Returned the correct number of rows.');
73 * Tests GROUP BY clauses.
75 public function testGroupBy() {
76 $query = db_select('test_task', 't');
77 $count_field = $query->addExpression('COUNT(task)', 'num');
78 $task_field = $query->addField('t', 'task');
79 $query->orderBy($count_field);
80 $query->groupBy($task_field);
81 $result = $query->execute();
86 foreach ($result as $record) {
88 $this->assertTrue($record->$count_field >= $last_count, 'Results returned in correct order.');
89 $last_count = $record->$count_field;
90 $records[$record->$task_field] = $record->$count_field;
97 'found new band' => 1,
98 'perform at superbowl' => 1,
101 foreach ($correct_results as $task => $count) {
102 $this->assertEqual($records[$task], $count, format_string("Correct number of '@task' records found.", ['@task' => $task]));
105 $this->assertEqual($num_records, 6, 'Returned the correct number of total rows.');
109 * Tests GROUP BY and HAVING clauses together.
111 public function testGroupByAndHaving() {
112 $query = db_select('test_task', 't');
113 $count_field = $query->addExpression('COUNT(task)', 'num');
114 $task_field = $query->addField('t', 'task');
115 $query->orderBy($count_field);
116 $query->groupBy($task_field);
117 $query->having('COUNT(task) >= 2');
118 $result = $query->execute();
123 foreach ($result as $record) {
125 $this->assertTrue($record->$count_field >= 2, 'Record has the minimum count.');
126 $this->assertTrue($record->$count_field >= $last_count, 'Results returned in correct order.');
127 $last_count = $record->$count_field;
128 $records[$record->$task_field] = $record->$count_field;
135 foreach ($correct_results as $task => $count) {
136 $this->assertEqual($records[$task], $count, format_string("Correct number of '@task' records found.", ['@task' => $task]));
139 $this->assertEqual($num_records, 1, 'Returned the correct number of total rows.');
143 * Tests range queries.
145 * The SQL clause varies with the database.
147 public function testRange() {
148 $query = db_select('test');
149 $query->addField('test', 'name');
150 $query->addField('test', 'age', 'age');
152 $query_result = $query->countQuery()->execute()->fetchField();
154 $this->assertEqual($query_result, 2, 'Returned the correct number of rows.');
158 * Test whether the range property of a select clause can be undone.
160 public function testRangeUndo() {
161 $query = db_select('test');
162 $name_field = $query->addField('test', 'name');
163 $age_field = $query->addField('test', 'age', 'age');
165 $query->range(NULL, NULL);
166 $query_result = $query->countQuery()->execute()->fetchField();
168 $this->assertEqual($query_result, 4, 'Returned the correct number of rows.');
172 * Tests distinct queries.
174 public function testDistinct() {
175 $query = db_select('test_task');
176 $query->addField('test_task', 'task');
178 $query_result = $query->countQuery()->execute()->fetchField();
180 $this->assertEqual($query_result, 6, 'Returned the correct number of rows.');
184 * Tests that we can generate a count query from a built query.
186 public function testCountQuery() {
187 $query = db_select('test');
188 $name_field = $query->addField('test', 'name');
189 $age_field = $query->addField('test', 'age', 'age');
190 $query->orderBy('name');
192 $count = $query->countQuery()->execute()->fetchField();
194 $this->assertEqual($count, 4, 'Counted the correct number of records.');
196 // Now make sure we didn't break the original query! We should still have
197 // all of the fields we asked for.
198 $record = $query->execute()->fetch();
199 $this->assertEqual($record->$name_field, 'George', 'Correct data retrieved.');
200 $this->assertEqual($record->$age_field, 27, 'Correct data retrieved.');
204 * Tests having queries.
206 public function testHavingCountQuery() {
207 $query = db_select('test')
208 ->extend('Drupal\Core\Database\Query\PagerSelectExtender')
210 ->having('age + 1 > 0');
211 $query->addField('test', 'age');
212 $query->addExpression('age + 1');
213 $count = count($query->execute()->fetchCol());
214 $this->assertEqual($count, 4, 'Counted the correct number of records.');
218 * Tests that countQuery removes 'all_fields' statements and ordering clauses.
220 public function testCountQueryRemovals() {
221 $query = db_select('test');
222 $query->fields('test');
223 $query->orderBy('name');
224 $count = $query->countQuery();
226 // Check that the 'all_fields' statement is handled properly.
227 $tables = $query->getTables();
228 $this->assertEqual($tables['test']['all_fields'], 1, 'Query correctly sets \'all_fields\' statement.');
229 $tables = $count->getTables();
230 $this->assertFalse(isset($tables['test']['all_fields']), 'Count query correctly unsets \'all_fields\' statement.');
232 // Check that the ordering clause is handled properly.
233 $orderby = $query->getOrderBy();
234 // The orderby string is different for PostgreSQL.
235 // @see Drupal\Core\Database\Driver\pgsql\Select::orderBy()
236 $db_type = Database::getConnection()->databaseType();
237 $this->assertEqual($orderby['name'], ($db_type == 'pgsql' ? 'ASC NULLS FIRST' : 'ASC'), 'Query correctly sets ordering clause.');
238 $orderby = $count->getOrderBy();
239 $this->assertFalse(isset($orderby['name']), 'Count query correctly unsets ordering clause.');
241 // Make sure that the count query works.
242 $count = $count->execute()->fetchField();
244 $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(db_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 = db_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 = db_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);