Version 1
[yaffs-website] / web / core / tests / Drupal / KernelTests / Core / Database / SelectComplexTest.php
1 <?php
2
3 namespace Drupal\KernelTests\Core\Database;
4
5 use Drupal\Core\Database\Database;
6 use Drupal\Core\Database\RowCountException;
7 use Drupal\user\Entity\User;
8
9 /**
10  * Tests the Select query builder with more complex queries.
11  *
12  * @group Database
13  */
14 class SelectComplexTest extends DatabaseTestBase {
15
16   /**
17    * Modules to enable.
18    *
19    * @var array
20    */
21   public static $modules = ['system', 'user', 'node_access_test', 'field'];
22
23   /**
24    * Tests simple JOIN statements.
25    */
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');
32
33     $query->orderBy($priority_field);
34     $result = $query->execute();
35
36     $num_records = 0;
37     $last_priority = 0;
38     foreach ($result as $record) {
39       $num_records++;
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;
43     }
44
45     $this->assertEqual($num_records, 7, 'Returned the correct number of rows.');
46   }
47
48   /**
49    * Tests LEFT OUTER joins.
50    */
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');
57
58     $query->orderBy($name_field);
59     $result = $query->execute();
60
61     $num_records = 0;
62     $last_name = 0;
63
64     foreach ($result as $record) {
65       $num_records++;
66       $this->assertTrue(strcmp($record->$name_field, $last_name) >= 0, 'Results returned in correct order.');
67     }
68
69     $this->assertEqual($num_records, 8, 'Returned the correct number of rows.');
70   }
71
72   /**
73    * Tests GROUP BY clauses.
74    */
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();
82
83     $num_records = 0;
84     $last_count = 0;
85     $records = [];
86     foreach ($result as $record) {
87       $num_records++;
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;
91     }
92
93     $correct_results = [
94       'eat' => 1,
95       'sleep' => 2,
96       'code' => 1,
97       'found new band' => 1,
98       'perform at superbowl' => 1,
99     ];
100
101     foreach ($correct_results as $task => $count) {
102       $this->assertEqual($records[$task], $count, format_string("Correct number of '@task' records found.", ['@task' => $task]));
103     }
104
105     $this->assertEqual($num_records, 6, 'Returned the correct number of total rows.');
106   }
107
108   /**
109    * Tests GROUP BY and HAVING clauses together.
110    */
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();
119
120     $num_records = 0;
121     $last_count = 0;
122     $records = [];
123     foreach ($result as $record) {
124       $num_records++;
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;
129     }
130
131     $correct_results = [
132       'sleep' => 2,
133     ];
134
135     foreach ($correct_results as $task => $count) {
136       $this->assertEqual($records[$task], $count, format_string("Correct number of '@task' records found.", ['@task' => $task]));
137     }
138
139     $this->assertEqual($num_records, 1, 'Returned the correct number of total rows.');
140   }
141
142   /**
143    * Tests range queries.
144    *
145    * The SQL clause varies with the database.
146    */
147   public function testRange() {
148     $query = db_select('test');
149     $query->addField('test', 'name');
150     $query->addField('test', 'age', 'age');
151     $query->range(0, 2);
152     $query_result = $query->countQuery()->execute()->fetchField();
153
154     $this->assertEqual($query_result, 2, 'Returned the correct number of rows.');
155   }
156
157   /**
158    * Test whether the range property of a select clause can be undone.
159    */
160   public function testRangeUndo() {
161     $query = db_select('test');
162     $name_field = $query->addField('test', 'name');
163     $age_field = $query->addField('test', 'age', 'age');
164     $query->range(0, 2);
165     $query->range(NULL, NULL);
166     $query_result = $query->countQuery()->execute()->fetchField();
167
168     $this->assertEqual($query_result, 4, 'Returned the correct number of rows.');
169   }
170
171   /**
172    * Tests distinct queries.
173    */
174   public function testDistinct() {
175     $query = db_select('test_task');
176     $query->addField('test_task', 'task');
177     $query->distinct();
178     $query_result = $query->countQuery()->execute()->fetchField();
179
180     $this->assertEqual($query_result, 6, 'Returned the correct number of rows.');
181   }
182
183   /**
184    * Tests that we can generate a count query from a built query.
185    */
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');
191
192     $count = $query->countQuery()->execute()->fetchField();
193
194     $this->assertEqual($count, 4, 'Counted the correct number of records.');
195
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.');
201   }
202
203   /**
204    * Tests having queries.
205    */
206   public function testHavingCountQuery() {
207     $query = db_select('test')
208       ->extend('Drupal\Core\Database\Query\PagerSelectExtender')
209       ->groupBy('age')
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.');
215   }
216
217   /**
218    * Tests that countQuery removes 'all_fields' statements and ordering clauses.
219    */
220   public function testCountQueryRemovals() {
221     $query = db_select('test');
222     $query->fields('test');
223     $query->orderBy('name');
224     $count = $query->countQuery();
225
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.');
231
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.');
240
241     // Make sure that the count query works.
242     $count = $count->execute()->fetchField();
243
244     $this->assertEqual($count, 4, 'Counted the correct number of records.');
245   }
246
247
248   /**
249    * Tests that countQuery properly removes fields and expressions.
250    */
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');
260
261     $query = db_select('test');
262     $query->addExpression('fail');
263     $this->assertEqual(4, $query->countQuery()->execute()->fetchField(), 'Count Query removed expressions');
264   }
265
266   /**
267    * Tests that we can generate a count query from a query with distinct.
268    */
269   public function testCountQueryDistinct() {
270     $query = db_select('test_task');
271     $query->addField('test_task', 'task');
272     $query->distinct();
273
274     $count = $query->countQuery()->execute()->fetchField();
275
276     $this->assertEqual($count, 6, 'Counted the correct number of records.');
277   }
278
279   /**
280    * Tests that we can generate a count query from a query with GROUP BY.
281    */
282   public function testCountQueryGroupBy() {
283     $query = db_select('test_task');
284     $query->addField('test_task', 'pid');
285     $query->groupBy('pid');
286
287     $count = $query->countQuery()->execute()->fetchField();
288
289     $this->assertEqual($count, 3, 'Counted the correct number of records.');
290
291     // Use a column alias as, without one, the query can succeed for the wrong
292     // reason.
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');
298
299     $count = $query->countQuery()->execute()->fetchField();
300
301     $this->assertEqual($count, 3, 'Counted the correct number of records.');
302   }
303
304   /**
305    * Confirms that we can properly nest conditional clauses.
306    */
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));
316
317     $job = $query->execute()->fetchField();
318     $this->assertEqual($job, 'Songwriter', 'Correct data retrieved.');
319   }
320
321   /**
322    * Confirms we can join on a single table twice with a dynamic alias.
323    */
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.');
333   }
334
335   /**
336    * Tests that we can join on a query.
337    */
338   public function testJoinSubquery() {
339     $this->installSchema('system', 'sequences');
340
341     $account = User::create([
342       'name' => $this->randomMachineName(),
343       'mail' => $this->randomMachineName() . '@example.com',
344     ]);
345
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, '<');
350
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, '<');
359
360     $query->leftJoin($subquery, 'sq', 'tt.pid = sq.id');
361     $query->join('test_one_blob', 'tb3', 'tt.pid = tb3.id');
362
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;
368
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.');
373   }
374
375   /**
376    * Tests that rowCount() throws exception on SELECT query.
377    */
378   public function testSelectWithRowCount() {
379     $query = db_select('test');
380     $query->addField('test', 'name');
381     $result = $query->execute();
382     try {
383       $result->rowCount();
384       $exception = FALSE;
385     }
386     catch (RowCountException $e) {
387       $exception = TRUE;
388     }
389     $this->assertTrue($exception, 'Exception was thrown');
390   }
391
392   /**
393    * Test that join conditions can use Condition objects.
394    */
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');
403
404     $query->orderBy($priority_field);
405     $result = $query->execute();
406
407     $num_records = 0;
408     $last_priority = 0;
409     foreach ($result as $record) {
410       $num_records++;
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;
414     }
415
416     $this->assertEqual($num_records, 7, 'Returned the correct number of rows.');
417
418     // Test a condition object that creates placeholders.
419     $t1_name = 'John';
420     $t2_name = 'George';
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');
428
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);
435     }
436   }
437
438 }