Sql.php 59.5 KB
Newer Older
merlinofchaos's avatar
merlinofchaos committed
1
2
3
4
<?php

/**
 * @file
5
 * Definition of Drupal\views\Plugin\views\query\Sql.
merlinofchaos's avatar
merlinofchaos committed
6
7
 */

8
namespace Drupal\views\Plugin\views\query;
9

10
use Drupal\Component\Utility\NestedArray;
11
use Drupal\Core\Database\Database;
12
use Drupal\views\Plugin\views\display\DisplayPluginBase;
13
use Drupal\Core\Database\DatabaseExceptionWrapper;
14
use Drupal\views\Plugin\views\join\JoinPluginBase;
15
use Drupal\views\Plugin\views\HandlerBase;
16
use Drupal\Component\Annotation\Plugin;
17
use Drupal\Core\Annotation\Translation;
18
use Drupal\views\ViewExecutable;
19
use Drupal\views\Views;
20

21
/**
22
23
 * @todo.
 *
24
 * @Plugin(
aspilicious's avatar
aspilicious committed
25
 *   id = "views_query",
26
27
28
29
 *   title = @Translation("SQL Query"),
 *   help = @Translation("Query will be generated and run using the Drupal database API.")
 * )
 */
30
class Sql extends QueryPluginBase {
tim.plunkett's avatar
tim.plunkett committed
31

merlinofchaos's avatar
merlinofchaos committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
  /**
   * A list of tables in the order they should be added, keyed by alias.
   */
  var $table_queue = array();

  /**
   * Holds an array of tables and counts added so that we can create aliases
   */
  var $tables = array();

  /**
   * Holds an array of relationships, which are aliases of the primary
   * table that represent different ways to join the same table in.
   */
  var $relationships = array();

  /**
   * An array of sections of the WHERE query. Each section is in itself
   * an array of pieces and a flag as to whether or not it should be AND
   * or OR.
   */
  var $where = array();
  /**
   * An array of sections of the HAVING query. Each section is in itself
   * an array of pieces and a flag as to whether or not it should be AND
   * or OR.
   */
  var $having = array();
  /**
   * The default operator to use when connecting the WHERE groups. May be
   * AND or OR.
   */
  var $group_operator = 'AND';

  /**
   * A simple array of order by clauses.
   */
  var $orderby = array();

  /**
   * A simple array of group by clauses.
   */
  var $groupby = array();


  /**
   * An array of fields.
   */
  var $fields = array();

  /**
   * A flag as to whether or not to make the primary field distinct.
   */
  var $distinct = FALSE;

  var $has_aggregate = FALSE;

  /**
   * Should this query be optimized for counts, for example no sorts.
   */
  var $get_count_optimized = NULL;

94
95
96
  /**
   * An array mapping table aliases and field names to field aliases.
   */
97
  var $field_aliases = array();
merlinofchaos's avatar
merlinofchaos committed
98

99
100
101
  /**
   * Query tags which will be passed over to the dbtng query object.
   */
102
  var $tags = array();
merlinofchaos's avatar
merlinofchaos committed
103
104
105
106
107
108
109
110
111

  /**
   * Is the view marked as not distinct.
   *
   * @var bool
   */
  var $no_distinct;

  /**
112
   * Overrides \Drupal\views\Plugin\views\PluginBase::init().
merlinofchaos's avatar
merlinofchaos committed
113
   */
114
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
115
    parent::init($view, $display, $options);
116

117
118
    $base_table = $this->view->storage->get('base_table');
    $base_field = $this->view->storage->get('base_field');
merlinofchaos's avatar
merlinofchaos committed
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
    $this->relationships[$base_table] = array(
      'link' => NULL,
      'table' => $base_table,
      'alias' => $base_table,
      'base' => $base_table
    );

    // init the table queue with our primary table.
    $this->table_queue[$base_table] = array(
      'alias' => $base_table,
      'table' => $base_table,
      'relationship' => $base_table,
      'join' => NULL,
    );

    // init the tables with our primary table
    $this->tables[$base_table][$base_table] = array(
      'count' => 1,
      'alias' => $base_table,
    );

    $this->count_field = array(
      'table' => $base_table,
      'field' => $base_field,
      'alias' => $base_field,
      'count' => TRUE,
    );
  }

  /**
149
   * Set the view to be distinct (per base field).
merlinofchaos's avatar
merlinofchaos committed
150
151
152
153
   *
   * @param bool $value
   *   Should the view by distincted.
   */
154
  protected function setDistinct($value = TRUE) {
merlinofchaos's avatar
merlinofchaos committed
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
    if (!(isset($this->no_distinct) && $value)) {
      $this->distinct = $value;
    }
  }

  /**
   * Set what field the query will count() on for paging.
   */
  function set_count_field($table, $field, $alias = NULL) {
    if (empty($alias)) {
      $alias = $table . '_' . $field;
    }
    $this->count_field = array(
      'table' => $table,
      'field' => $field,
      'alias' => $alias,
      'count' => TRUE,
    );
  }

175
176
  protected function defineOptions() {
    $options = parent::defineOptions();
merlinofchaos's avatar
merlinofchaos committed
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
    $options['disable_sql_rewrite'] = array(
      'default' => FALSE,
      'translatable' => FALSE,
      'bool' => TRUE,
    );
    $options['distinct'] = array(
      'default' => FALSE,
      'bool' => TRUE,
    );
    $options['slave'] = array(
      'default' => FALSE,
      'bool' => TRUE,
    );
    $options['query_comment'] = array(
      'default' => '',
    );
    $options['query_tags'] = array(
      'default' => array(),
    );

    return $options;
  }

  /**
   * Add settings for the ui.
   */
203
204
  public function buildOptionsForm(&$form, &$form_state) {
    parent::buildOptionsForm($form, $form_state);
merlinofchaos's avatar
merlinofchaos committed
205
206
207
208
209
210

    $form['disable_sql_rewrite'] = array(
      '#title' => t('Disable SQL rewriting'),
      '#description' => t('Disabling SQL rewriting will disable node_access checks as well as other modules that implement hook_query_alter().'),
      '#type' => 'checkbox',
      '#default_value' => !empty($this->options['disable_sql_rewrite']),
211
      '#suffix' => '<div class="messages messages--warning sql-rewrite-warning js-hide">' . t('WARNING: Disabling SQL rewriting means that node access security is disabled. This may allow users to see data they should not be able to see if your view is misconfigured. Use this option only if you understand and accept this security risk.') . '</div>',
merlinofchaos's avatar
merlinofchaos committed
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
    );
    $form['distinct'] = array(
      '#type' => 'checkbox',
      '#title' => t('Distinct'),
      '#description' => t('This will make the view display only distinct items. If there are multiple identical items, each will be displayed only once. You can use this to try and remove duplicates from a view, though it does not always work. Note that this can slow queries down, so use it with caution.'),
      '#default_value' => !empty($this->options['distinct']),
    );
    $form['slave'] = array(
      '#type' => 'checkbox',
      '#title' => t('Use Slave Server'),
      '#description' => t('This will make the query attempt to connect to a slave server if available.  If no slave server is defined or available, it will fall back to the default server.'),
      '#default_value' => !empty($this->options['slave']),
    );
    $form['query_comment'] = array(
      '#type' => 'textfield',
      '#title' => t('Query Comment'),
      '#description' => t('If set, this comment will be embedded in the query and passed to the SQL server. This can be helpful for logging or debugging.'),
      '#default_value' => $this->options['query_comment'],
    );
    $form['query_tags'] = array(
      '#type' => 'textfield',
      '#title' => t('Query Tags'),
      '#description' => t('If set, these tags will be appended to the query and can be used to identify the query in a module. This can be helpful for altering queries.'),
      '#default_value' => implode(', ', $this->options['query_tags']),
      '#element_validate' => array('views_element_validate_tags'),
    );
  }

  /**
   * Special submit handling.
   */
243
  public function submitOptionsForm(&$form, &$form_state) {
merlinofchaos's avatar
merlinofchaos committed
244
    $element = array('#parents' => array('query', 'options', 'query_tags'));
245
    $value = explode(',', NestedArray::getValue($form_state['values'], $element['#parents']));
merlinofchaos's avatar
merlinofchaos committed
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
    $value = array_filter(array_map('trim', $value));
    form_set_value($element, $value, $form_state);
  }

  /**
   * A relationship is an alternative endpoint to a series of table
   * joins. Relationships must be aliases of the primary table and
   * they must join either to the primary table or to a pre-existing
   * relationship.
   *
   * An example of a relationship would be a nodereference table.
   * If you have a nodereference named 'book_parent' which links to a
   * parent node, you could set up a relationship 'node_book_parent'
   * to 'node'. Then, anything that links to 'node' can link to
   * 'node_book_parent' instead, thus allowing all properties of
   * both nodes to be available in the query.
   *
   * @param $alias
   *   What this relationship will be called, and is also the alias
   *   for the table.
266
   * @param Drupal\views\Plugin\views\join\JoinPluginBase $join
267
   *   A Join object (or derived object) to join the alias in.
merlinofchaos's avatar
merlinofchaos committed
268
269
270
271
272
273
274
275
276
277
   * @param $base
   *   The name of the 'base' table this relationship represents; this
   *   tells the join search which path to attempt to use when finding
   *   the path to this relationship.
   * @param $link_point
   *   If this relationship links to something other than the primary
   *   table, specify that table here. For example, a 'track' node
   *   might have a relationship to an 'album' node, which might
   *   have a relationship to an 'artist' node.
   */
278
  public function addRelationship($alias, JoinPluginBase $join, $base, $link_point = NULL) {
merlinofchaos's avatar
merlinofchaos committed
279
    if (empty($link_point)) {
280
      $link_point = $this->view->storage->get('base_table');
merlinofchaos's avatar
merlinofchaos committed
281
282
283
284
285
286
287
288
289
290
291
292
293
294
    }
    elseif (!array_key_exists($link_point, $this->relationships)) {
      return FALSE;
    }

    // Make sure $alias isn't already used; if it, start adding stuff.
    $alias_base = $alias;
    $count = 1;
    while (!empty($this->relationships[$alias])) {
      $alias = $alias_base . '_' . $count++;
    }

    // Make sure this join is adjusted for our relationship.
    if ($link_point && isset($this->relationships[$link_point])) {
295
      $join = $this->adjustJoin($join, $link_point);
merlinofchaos's avatar
merlinofchaos committed
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
    }

    // Add the table directly to the queue to avoid accidentally marking
    // it.
    $this->table_queue[$alias] = array(
      'table' => $join->table,
      'num' => 1,
      'alias' => $alias,
      'join' => $join,
      'relationship' => $link_point,
    );

    $this->relationships[$alias] = array(
      'link' => $link_point,
      'table' => $join->table,
      'base' => $base,
    );

314
    $this->tables[$this->view->storage->get('base_table')][$alias] = array(
merlinofchaos's avatar
merlinofchaos committed
315
316
317
318
319
320
321
322
323
324
325
326
      'count' => 1,
      'alias' => $alias,
    );

    return $alias;
  }

  /**
   * Add a table to the query, ensuring the path exists.
   *
   * This function will test to ensure that the path back to the primary
   * table is valid and exists; if you do not wish for this testing to
327
   * occur, use $query->queueTable() instead.
merlinofchaos's avatar
merlinofchaos committed
328
329
330
331
332
333
334
335
336
337
   *
   * @param $table
   *   The name of the table to add. It needs to exist in the global table
   *   array.
   * @param $relationship
   *   An alias of a table; if this is set, the path back to this table will
   *   be tested prior to adding the table, making sure that all intermediary
   *   tables exist and are properly aliased. If set to NULL the path to
   *   the primary table will be ensured. If the path cannot be made, the
   *   table will NOT be added.
338
   * @param Drupal\views\Plugin\views\join\JoinPluginBase $join
merlinofchaos's avatar
merlinofchaos committed
339
340
341
342
343
344
345
346
347
348
349
350
351
   *   In some join configurations this table may actually join back through
   *   a different method; this is most likely to be used when tracing
   *   a hierarchy path. (node->parent->parent2->parent3). This parameter
   *   will specify how this table joins if it is not the default.
   * @param $alias
   *   A specific alias to use, rather than the default alias.
   *
   * @return $alias
   *   The alias of the table; this alias can be used to access information
   *   about the table and should always be used to refer to the table when
   *   adding parts to the query. Or FALSE if the table was not able to be
   *   added.
   */
352
  public function addTable($table, $relationship = NULL, JoinPluginBase $join = NULL, $alias = NULL) {
353
    if (!$this->ensurePath($table, $relationship, $join)) {
merlinofchaos's avatar
merlinofchaos committed
354
355
356
357
      return FALSE;
    }

    if ($join && $relationship) {
358
      $join = $this->adjustJoin($join, $relationship);
merlinofchaos's avatar
merlinofchaos committed
359
360
    }

361
    return $this->queueTable($table, $relationship, $join, $alias);
merlinofchaos's avatar
merlinofchaos committed
362
363
364
365
366
  }

  /**
   * Add a table to the query without ensuring the path.
   *
367
   * This is a pretty internal function to Views and addTable() or
368
   * ensureTable() should be used instead of this one, unless you are
merlinofchaos's avatar
merlinofchaos committed
369
370
371
372
373
374
375
376
   * absolutely sure this is what you want.
   *
   * @param $table
   *   The name of the table to add. It needs to exist in the global table
   *   array.
   * @param $relationship
   *   The primary table alias this table is related to. If not set, the
   *   primary table will be used.
377
   * @param Drupal\views\Plugin\views\join\JoinPluginBase $join
merlinofchaos's avatar
merlinofchaos committed
378
379
380
381
382
383
384
385
386
387
388
389
390
   *   In some join configurations this table may actually join back through
   *   a different method; this is most likely to be used when tracing
   *   a hierarchy path. (node->parent->parent2->parent3). This parameter
   *   will specify how this table joins if it is not the default.
   * @param $alias
   *   A specific alias to use, rather than the default alias.
   *
   * @return $alias
   *   The alias of the table; this alias can be used to access information
   *   about the table and should always be used to refer to the table when
   *   adding parts to the query. Or FALSE if the table was not able to be
   *   added.
   */
391
  public function queueTable($table, $relationship = NULL, JoinPluginBase $join = NULL, $alias = NULL) {
merlinofchaos's avatar
merlinofchaos committed
392
393
394
395
396
397
    // If the alias is set, make sure it doesn't already exist.
    if (isset($this->table_queue[$alias])) {
      return $alias;
    }

    if (empty($relationship)) {
398
      $relationship = $this->view->storage->get('base_table');
merlinofchaos's avatar
merlinofchaos committed
399
400
401
402
403
404
405
    }

    if (!array_key_exists($relationship, $this->relationships)) {
      return FALSE;
    }

    if (!$alias && $join && $relationship && !empty($join->adjusted) && $table != $join->table) {
406
      if ($relationship == $this->view->storage->get('base_table')) {
merlinofchaos's avatar
merlinofchaos committed
407
408
409
410
411
412
413
414
415
416
417
418
419
        $alias = $table;
      }
      else {
        $alias = $relationship . '_' . $table;
      }
    }

    // Check this again to make sure we don't blow up existing aliases for already
    // adjusted joins.
    if (isset($this->table_queue[$alias])) {
      return $alias;
    }

420
    $alias = $this->markTable($table, $relationship, $alias);
merlinofchaos's avatar
merlinofchaos committed
421
422
423
424
425
426
427
428
429

    // If no alias is specified, give it the default.
    if (!isset($alias)) {
      $alias = $this->tables[$relationship][$table]['alias'] . $this->tables[$relationship][$table]['count'];
    }

    // If this is a relationship based table, add a marker with
    // the relationship as a primary table for the alias.
    if ($table != $alias) {
430
      $this->markTable($alias, $this->view->storage->get('base_table'), $alias);
merlinofchaos's avatar
merlinofchaos committed
431
432
433
434
    }

    // If no join is specified, pull it from the table data.
    if (!isset($join)) {
435
      $join = $this->getJoinData($table, $this->relationships[$relationship]['base']);
merlinofchaos's avatar
merlinofchaos committed
436
437
438
439
      if (empty($join)) {
        return FALSE;
      }

440
      $join = $this->adjustJoin($join, $relationship);
merlinofchaos's avatar
merlinofchaos committed
441
442
443
444
445
446
447
448
449
450
451
452
453
    }

    $this->table_queue[$alias] = array(
      'table' => $table,
      'num' => $this->tables[$relationship][$table]['count'],
      'alias' => $alias,
      'join' => $join,
      'relationship' => $relationship,
    );

    return $alias;
  }

454
  protected function markTable($table, $relationship, $alias) {
merlinofchaos's avatar
merlinofchaos committed
455
456
457
458
    // Mark that this table has been added.
    if (empty($this->tables[$relationship][$table])) {
      if (!isset($alias)) {
        $alias = '';
459
        if ($relationship != $this->view->storage->get('base_table')) {
merlinofchaos's avatar
merlinofchaos committed
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
          // double underscore will help prevent accidental name
          // space collisions.
          $alias = $relationship . '__';
        }
        $alias .= $table;
      }
      $this->tables[$relationship][$table] = array(
        'count' => 1,
        'alias' => $alias,
      );
    }
    else {
      $this->tables[$relationship][$table]['count']++;
    }

    return $alias;
  }

  /**
   * Ensure a table exists in the queue; if it already exists it won't
   * do anything, but if it doesn't it will add the table queue. It will ensure
   * a path leads back to the relationship table.
   *
   * @param $table
   *   The unaliased name of the table to ensure.
   * @param $relationship
   *   The relationship to ensure the table links to. Each relationship will
   *   get a unique instance of the table being added. If not specified,
   *   will be the primary table.
489
   * @param Drupal\views\Plugin\views\join\JoinPluginBase $join
490
   *   A Join object (or derived object) to join the alias in.
merlinofchaos's avatar
merlinofchaos committed
491
492
493
494
495
   *
   * @return
   *   The alias used to refer to this specific table, or NULL if the table
   *   cannot be ensured.
   */
496
  public function ensureTable($table, $relationship = NULL, JoinPluginBase $join = NULL) {
merlinofchaos's avatar
merlinofchaos committed
497
498
    // ensure a relationship
    if (empty($relationship)) {
499
      $relationship = $this->view->storage->get('base_table');
merlinofchaos's avatar
merlinofchaos committed
500
501
502
503
504
505
    }

    // If the relationship is the primary table, this actually be a relationship
    // link back from an alias. We store all aliases along with the primary table
    // to detect this state, because eventually it'll hit a table we already
    // have and that's when we want to stop.
506
    if ($relationship == $this->view->storage->get('base_table') && !empty($this->tables[$relationship][$table])) {
merlinofchaos's avatar
merlinofchaos committed
507
508
509
510
511
512
513
514
515
516
517
518
519
      return $this->tables[$relationship][$table]['alias'];
    }

    if (!array_key_exists($relationship, $this->relationships)) {
      return FALSE;
    }

    if ($table == $this->relationships[$relationship]['base']) {
      return $relationship;
    }

    // If we do not have join info, fetch it.
    if (!isset($join)) {
520
      $join = $this->getJoinData($table, $this->relationships[$relationship]['base']);
merlinofchaos's avatar
merlinofchaos committed
521
522
523
524
525
526
527
528
529
530
    }

    // If it can't be fetched, this won't work.
    if (empty($join)) {
      return;
    }

    // Adjust this join for the relationship, which will ensure that the 'base'
    // table it links to is correct. Tables adjoined to a relationship
    // join to a link point, not the base table.
531
    $join = $this->adjustJoin($join, $relationship);
merlinofchaos's avatar
merlinofchaos committed
532

533
    if ($this->ensurePath($table, $relationship, $join)) {
merlinofchaos's avatar
merlinofchaos committed
534
535
536
537
538
539
540
      // Attempt to eliminate redundant joins.  If this table's
      // relationship and join exactly matches an existing table's
      // relationship and join, we do not have to join to it again;
      // just return the existing table's alias.  See
      // http://groups.drupal.org/node/11288 for details.
      //
      // This can be done safely here but not lower down in
541
      // queueTable(), because queueTable() is also used by
542
      // addTable() which requires the ability to intentionally add
merlinofchaos's avatar
merlinofchaos committed
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
      // the same table with the same join multiple times.  For
      // example, a view that filters on 3 taxonomy terms using AND
      // needs to join taxonomy_term_data 3 times with the same join.

      // scan through the table queue to see if a matching join and
      // relationship exists.  If so, use it instead of this join.

      // TODO: Scanning through $this->table_queue results in an
      // O(N^2) algorithm, and this code runs every time the view is
      // instantiated (Views 2 does not currently cache queries).
      // There are a couple possible "improvements" but we should do
      // some performance testing before picking one.
      foreach ($this->table_queue as $queued_table) {
        // In PHP 4 and 5, the == operation returns TRUE for two objects
        // if they are instances of the same class and have the same
        // attributes and values.
        if ($queued_table['relationship'] == $relationship && $queued_table['join'] == $join) {
          return $queued_table['alias'];
        }
      }

564
      return $this->queueTable($table, $relationship, $join);
merlinofchaos's avatar
merlinofchaos committed
565
566
567
568
569
570
571
572
573
574
    }
  }

  /**
   * Make sure that the specified table can be properly linked to the primary
   * table in the JOINs. This function uses recursion. If the tables
   * needed to complete the path back to the primary table are not in the
   * query they will be added, but additional copies will NOT be added
   * if the table is already there.
   */
575
  protected function ensurePath($table, $relationship = NULL, $join = NULL, $traced = array(), $add = array()) {
merlinofchaos's avatar
merlinofchaos committed
576
    if (!isset($relationship)) {
577
      $relationship = $this->view->storage->get('base_table');
merlinofchaos's avatar
merlinofchaos committed
578
579
580
581
582
583
584
585
    }

    if (!array_key_exists($relationship, $this->relationships)) {
      return FALSE;
    }

    // If we do not have join info, fetch it.
    if (!isset($join)) {
586
      $join = $this->getJoinData($table, $this->relationships[$relationship]['base']);
merlinofchaos's avatar
merlinofchaos committed
587
588
589
590
591
592
593
594
595
    }

    // If it can't be fetched, this won't work.
    if (empty($join)) {
      return FALSE;
    }

    // Does a table along this path exist?
    if (isset($this->tables[$relationship][$table]) ||
596
597
      ($join && $join->leftTable == $relationship) ||
      ($join && $join->leftTable == $this->relationships[$relationship]['table'])) {
merlinofchaos's avatar
merlinofchaos committed
598
599
600

      // Make sure that we're linking to the correct table for our relationship.
      foreach (array_reverse($add) as $table => $path_join) {
601
        $this->queueTable($table, $relationship, $this->adjustJoin($path_join, $relationship));
merlinofchaos's avatar
merlinofchaos committed
602
603
604
605
606
      }
      return TRUE;
    }

    // Have we been this way?
607
    if (isset($traced[$join->leftTable])) {
merlinofchaos's avatar
merlinofchaos committed
608
609
610
611
612
      // we looped. Broked.
      return FALSE;
    }

    // Do we have to add this table?
613
    $left_join = $this->getJoinData($join->leftTable, $this->relationships[$relationship]['base']);
614
615
    if (!isset($this->tables[$relationship][$join->leftTable])) {
      $add[$join->leftTable] = $left_join;
merlinofchaos's avatar
merlinofchaos committed
616
617
618
    }

    // Keep looking.
619
    $traced[$join->leftTable] = TRUE;
620
    return $this->ensurePath($join->leftTable, $relationship, $left_join, $traced, $add);
merlinofchaos's avatar
merlinofchaos committed
621
622
623
624
625
626
  }

  /**
   * Fix a join to adhere to the proper relationship; the left table can vary
   * based upon what relationship items are joined in on.
   */
627
  protected function adjustJoin($join, $relationship) {
merlinofchaos's avatar
merlinofchaos committed
628
629
630
631
632
633
634
635
636
    if (!empty($join->adjusted)) {
      return $join;
    }

    if (empty($relationship) || empty($this->relationships[$relationship])) {
      return $join;
    }

    // Adjusts the left table for our relationship.
637
    if ($relationship != $this->view->storage->get('base_table')) {
merlinofchaos's avatar
merlinofchaos committed
638
639
640
641
642
643
644
      // If we're linking to the primary table, the relationship to use will
      // be the prior relationship. Unless it's a direct link.

      // Safety! Don't modify an original here.
      $join = clone $join;

      // Do we need to try to ensure a path?
645
646
647
      if ($join->leftTable != $this->relationships[$relationship]['table'] &&
        $join->leftTable != $this->relationships[$relationship]['base'] &&
        !isset($this->tables[$relationship][$join->leftTable]['alias'])) {
648
        $this->ensureTable($join->leftTable, $relationship);
merlinofchaos's avatar
merlinofchaos committed
649
650
651
      }

      // First, if this is our link point/anchor table, just use the relationship
652
653
      if ($join->leftTable == $this->relationships[$relationship]['table']) {
        $join->leftTable = $relationship;
merlinofchaos's avatar
merlinofchaos committed
654
655
      }
      // then, try the base alias.
656
657
      elseif (isset($this->tables[$relationship][$join->leftTable]['alias'])) {
        $join->leftTable = $this->tables[$relationship][$join->leftTable]['alias'];
merlinofchaos's avatar
merlinofchaos committed
658
659
660
      }
      // But if we're already looking at an alias, use that instead.
      elseif (isset($this->table_queue[$relationship]['alias'])) {
661
        $join->leftTable = $this->table_queue[$relationship]['alias'];
merlinofchaos's avatar
merlinofchaos committed
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
      }
    }

    $join->adjusted = TRUE;
    return $join;
  }

  /**
   * Retrieve join data from the larger join data cache.
   *
   * @param $table
   *   The table to get the join information for.
   * @param $base_table
   *   The path we're following to get this join.
   *
677
   * @return Drupal\views\Plugin\views\join\JoinPluginBase
678
   *   A Join object or child object, if one exists.
merlinofchaos's avatar
merlinofchaos committed
679
   */
680
  public function getJoinData($table, $base_table) {
merlinofchaos's avatar
merlinofchaos committed
681
682
683
684
685
    // Check to see if we're linking to a known alias. If so, get the real
    // table's data instead.
    if (!empty($this->table_queue[$table])) {
      $table = $this->table_queue[$table]['table'];
    }
686
    return HandlerBase::getTableJoin($table, $base_table);
merlinofchaos's avatar
merlinofchaos committed
687
688
689
690
691
692
  }

  /**
   * Get the information associated with a table.
   *
   * If you need the alias of a table with a particular relationship, use
693
   * ensureTable().
merlinofchaos's avatar
merlinofchaos committed
694
   */
695
  public function getTableInfo($table) {
merlinofchaos's avatar
merlinofchaos committed
696
697
698
699
700
    if (!empty($this->table_queue[$table])) {
      return $this->table_queue[$table];
    }

    // In rare cases we might *only* have aliased versions of the table.
701
702
    if (!empty($this->tables[$this->view->storage->get('base_table')][$table])) {
      $alias = $this->tables[$this->view->storage->get('base_table')][$table]['alias'];
merlinofchaos's avatar
merlinofchaos committed
703
704
705
706
707
708
709
710
      if (!empty($this->table_queue[$alias])) {
        return $this->table_queue[$alias];
      }
    }
  }

  /**
   * Add a field to the query table, possibly with an alias. This will
711
   * automatically call ensureTable to make sure the required table
merlinofchaos's avatar
merlinofchaos committed
712
713
714
715
   * exists, *unless* $table is unset.
   *
   * @param $table
   *   The table this field is attached to. If NULL, it is assumed this will
716
   *   be a formula; otherwise, ensureTable is used to make sure the
merlinofchaos's avatar
merlinofchaos committed
717
718
719
720
721
722
723
724
725
726
727
728
729
730
   *   table exists.
   * @param $field
   *   The name of the field to add. This may be a real field or a formula.
   * @param $alias
   *   The alias to create. If not specified, the alias will be $table_$field
   *   unless $table is NULL. When adding formulae, it is recommended that an
   *   alias be used.
   * @param $params
   *   An array of parameters additional to the field that will control items
   *   such as aggregation functions and DISTINCT.
   *
   * @return $name
   *   The name that this field can be referred to as. Usually this is the alias.
   */
731
  public function addField($table, $field, $alias = '', $params = array()) {
merlinofchaos's avatar
merlinofchaos committed
732
    // We check for this specifically because it gets a special alias.
733
734
    if ($table == $this->view->storage->get('base_table') && $field == $this->view->storage->get('base_field') && empty($alias)) {
      $alias = $this->view->storage->get('base_field');
merlinofchaos's avatar
merlinofchaos committed
735
736
737
    }

    if ($table && empty($this->table_queue[$table])) {
738
      $this->ensureTable($table);
merlinofchaos's avatar
merlinofchaos committed
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
    }

    if (!$alias && $table) {
      $alias = $table . '_' . $field;
    }

    // Make sure an alias is assigned
    $alias = $alias ? $alias : $field;

    // PostgreSQL truncates aliases to 63 characters: http://drupal.org/node/571548

    // We limit the length of the original alias up to 60 characters
    // to get a unique alias later if its have duplicates
    $alias = strtolower(substr($alias, 0, 60));

    // Create a field info array.
    $field_info = array(
      'field' => $field,
      'table' => $table,
      'alias' => $alias,
    ) + $params;

    // Test to see if the field is actually the same or not. Due to
    // differing parameters changing the aggregation function, we need
    // to do some automatic alias collision detection:
    $base = $alias;
    $counter = 0;
    while (!empty($this->fields[$alias]) && $this->fields[$alias] != $field_info) {
      $field_info['alias'] = $alias = $base . '_' . ++$counter;
    }

    if (empty($this->fields[$alias])) {
      $this->fields[$alias] = $field_info;
    }

    // Keep track of all aliases used.
    $this->field_aliases[$table][$field] = $alias;

    return $alias;
  }

  /**
   * Remove all fields that may've been added; primarily used for summary
   * mode where we're changing the query because we didn't get data we needed.
   */
784
  public function clearFields() {
merlinofchaos's avatar
merlinofchaos committed
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
    $this->fields = array();
  }

  /**
   * Add a simple WHERE clause to the query. The caller is responsible for
   * ensuring that all fields are fully qualified (TABLE.FIELD) and that
   * the table already exists in the query.
   *
   * @param $group
   *   The WHERE group to add these to; groups are used to create AND/OR
   *   sections. Groups cannot be nested. Use 0 as the default group.
   *   If the group does not yet exist it will be created as an AND group.
   * @param $field
   *   The name of the field to check.
   * @param $value
   *   The value to test the field against. In most cases, this is a scalar. For more
   *   complex options, it is an array. The meaning of each element in the array is
   *   dependent on the $operator.
   * @param $operator
   *   The comparison operator, such as =, <, or >=. It also accepts more complex
   *   options such as IN, LIKE, or BETWEEN. Defaults to IN if $value is an array
   *   = otherwise. If $field is a string you have to use 'formula' here.
   *
808
809
810
   * The $field, $value and $operator arguments can also be passed in with a
   * single DatabaseCondition object, like this:
   * @code
811
   *   $this->query->addWhere(
812
813
814
815
816
817
818
819
820
   *     $this->options['group'],
   *     db_or()
   *       ->condition($field, $value, 'NOT IN')
   *       ->condition($field, $value, 'IS NULL')
   *   );
   * @endcode
   *
   * @see Drupal\Core\Database\Query\ConditionInterface::condition()
   * @see Drupal\Core\Database\Query\Condition
merlinofchaos's avatar
merlinofchaos committed
821
   */
822
  public function addWhere($group, $field, $value = NULL, $operator = NULL) {
merlinofchaos's avatar
merlinofchaos committed
823
824
825
826
827
828
829
830
    // Ensure all variants of 0 are actually 0. Thus '', 0 and NULL are all
    // the default group.
    if (empty($group)) {
      $group = 0;
    }

    // Check for a group.
    if (!isset($this->where[$group])) {
831
      $this->setWhereGroup('AND', $group);
merlinofchaos's avatar
merlinofchaos committed
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
    }

    $this->where[$group]['conditions'][] = array(
      'field' => $field,
      'value' => $value,
      'operator' => $operator,
    );
  }

  /**
   * Add a complex WHERE clause to the query.
   *
   * The caller is reponsible for ensuring that all fields are fully qualified
   * (TABLE.FIELD) and that the table already exists in the query.
   * Internally the dbtng method "where" is used.
   *
   * @param $group
   *   The WHERE group to add these to; groups are used to create AND/OR
   *   sections. Groups cannot be nested. Use 0 as the default group.
   *   If the group does not yet exist it will be created as an AND group.
   * @param $snippet
   *   The snippet to check. This can be either a column or
   *   a complex expression like "UPPER(table.field) = 'value'"
   * @param $args
   *   An associative array of arguments.
   *
   * @see QueryConditionInterface::where()
   */
860
  public function addWhereExpression($group, $snippet, $args = array()) {
merlinofchaos's avatar
merlinofchaos committed
861
862
863
864
865
866
867
868
    // Ensure all variants of 0 are actually 0. Thus '', 0 and NULL are all
    // the default group.
    if (empty($group)) {
      $group = 0;
    }

    // Check for a group.
    if (!isset($this->where[$group])) {
869
      $this->setWhereGroup('AND', $group);
merlinofchaos's avatar
merlinofchaos committed
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
    }

    $this->where[$group]['conditions'][] = array(
      'field' => $snippet,
      'value' => $args,
      'operator' => 'formula',
    );
  }

  /**
   * Add a complex HAVING clause to the query.
   * The caller is responsible for ensuring that all fields are fully qualified
   * (TABLE.FIELD) and that the table and an appropriate GROUP BY already exist in the query.
   * Internally the dbtng method "having" is used.
   *
   * @param $group
   *   The HAVING group to add these to; groups are used to create AND/OR
   *   sections. Groups cannot be nested. Use 0 as the default group.
   *   If the group does not yet exist it will be created as an AND group.
   * @param $snippet
   *   The snippet to check. This can be either a column or
   *   a complex expression like "COUNT(table.field) > 3"
   * @param $args
   *   An associative array of arguments.
   *
   * @see QueryConditionInterface::having()
   */
897
  public function addHavingExpression($group, $snippet, $args = array()) {
merlinofchaos's avatar
merlinofchaos committed
898
899
900
901
902
903
904
905
    // Ensure all variants of 0 are actually 0. Thus '', 0 and NULL are all
    // the default group.
    if (empty($group)) {
      $group = 0;
    }

    // Check for a group.
    if (!isset($this->having[$group])) {
906
      $this->setWhereGroup('AND', $group, 'having');
merlinofchaos's avatar
merlinofchaos committed
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
    }

    // Add the clause and the args.
    $this->having[$group]['conditions'][] = array(
      'field' => $snippet,
      'value' => $args,
      'operator' => 'formula',
    );
  }

  /**
   * Add an ORDER BY clause to the query.
   *
   * @param $table
   *   The table this field is part of. If a formula, enter NULL.
   *   If you want to orderby random use "rand" as table and nothing else.
   * @param $field
   *   The field or formula to sort on. If already a field, enter NULL
   *   and put in the alias.
   * @param $order
   *   Either ASC or DESC.
   * @param $alias
   *   The alias to add the field as. In SQL, all fields in the order by
   *   must also be in the SELECT portion. If an $alias isn't specified
   *   one will be generated for from the $field; however, if the
   *   $field is a formula, this alias will likely fail.
   * @param $params
934
   *   Any params that should be passed through to the addField.
merlinofchaos's avatar
merlinofchaos committed
935
   */
936
  public function addOrderBy($table, $field = NULL, $order = 'ASC', $alias = '', $params = array()) {
merlinofchaos's avatar
merlinofchaos committed
937
    // Only ensure the table if it's not the special random key.
938
    // @todo: Maybe it would make sense to just add an addOrderByRand or something similar.
merlinofchaos's avatar
merlinofchaos committed
939
    if ($table && $table != 'rand') {
940
      $this->ensureTable($table);
merlinofchaos's avatar
merlinofchaos committed
941
942
943
944
945
946
947
948
949
950
951
952
    }

    // Only fill out this aliasing if there is a table;
    // otherwise we assume it is a formula.
    if (!$alias && $table) {
      $as = $table . '_' . $field;
    }
    else {
      $as = $alias;
    }

    if ($field) {
953
      $as = $this->addField($table, $field, $as, $params);
merlinofchaos's avatar
merlinofchaos committed
954
955
956
957
958
959
960
961
962
963
964
965
966
    }

    $this->orderby[] = array(
      'field' => $as,
      'direction' => strtoupper($order)
    );
  }

  /**
   * Add a simple GROUP BY clause to the query. The caller is responsible
   * for ensuring that the fields are fully qualified and the table is properly
   * added.
   */
967
  public function addGroupBy($clause) {
merlinofchaos's avatar
merlinofchaos committed
968
969
970
971
972
973
974
975
976
    // Only add it if it's not already in there.
    if (!in_array($clause, $this->groupby)) {
      $this->groupby[] = $clause;
    }
  }

  /**
   * Returns the alias for the given field added to $table.
   *
977
978
   * @access protected
   *
979
   * @see \Drupal\views\Plugin\views\query\Sql::addField
merlinofchaos's avatar
merlinofchaos committed
980
   */
981
  protected function getFieldAlias($table_alias, $field) {
merlinofchaos's avatar
merlinofchaos committed
982
983
984
985
986
987
988
989
    return isset($this->field_aliases[$table_alias][$field]) ? $this->field_aliases[$table_alias][$field] : FALSE;
  }

  /**
   * Adds a query tag to the sql object.
   *
   * @see SelectQuery::addTag()
   */
990
  public function addTag($tag) {
merlinofchaos's avatar
merlinofchaos committed
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
    $this->tags[] = $tag;
  }

  /**
   * Generates a unique placeholder used in the db query.
   */
  function placeholder($base = 'views') {
    static $placeholders = array();
    if (!isset($placeholders[$base])) {
      $placeholders[$base] = 0;
      return ':' . $base;
    }
    else {
      return ':' . $base . ++$placeholders[$base];
    }
  }

  /**
   * Construct the "WHERE" or "HAVING" part of the query.
   *
   * As views has to wrap the conditions from arguments with AND, a special
   * group is wrapped around all conditions. This special group has the ID 0.
   * There is other code in filters which makes sure that the group IDs are
   * higher than zero.
   *
   * @param $where
   *   'where' or 'having'.
   */
1019
  protected function buildCondition($where = 'where') {
merlinofchaos's avatar
merlinofchaos committed
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
    $has_condition = FALSE;
    $has_arguments = FALSE;
    $has_filter = FALSE;

    $main_group = db_and();
    $filter_group = $this->group_operator == 'OR' ? db_or() : db_and();

    foreach ($this->$where as $group => $info) {

      if (!empty($info['conditions'])) {
        $sub_group = $info['type'] == 'OR' ? db_or() : db_and();
        foreach ($info['conditions'] as $key => $clause) {
          // DBTNG doesn't support to add the same subquery twice to the main
          // query and the count query, so clone the subquery to have two instances
          // of the same object. - http://drupal.org/node/1112854
          if (is_object($clause['value']) && $clause['value'] instanceof SelectQuery) {
            $clause['value'] = clone $clause['value'];
          }
          if ($clause['operator'] == 'formula') {
            $has_condition = TRUE;
            $sub_group->where($clause['field'], $clause['value']);
          }
          else {
            $has_condition = TRUE;
            $sub_group->condition($clause['field'], $clause['value'], $clause['operator']);
          }
        }

        // Add the item to the filter group.
        if ($group != 0) {
          $has_filter = TRUE;
          $filter_group->condition($sub_group);
        }
        else {
          $has_arguments = TRUE;
          $main_group->condition($sub_group);
        }
      }
    }

    if ($has_filter) {
      $main_group->condition($filter_group);
    }

    if (!$has_arguments && $has_condition) {
      return $filter_group;
    }
    if ($has_arguments && $has_condition) {
      return $main_group;
    }
  }

  /**
1073
1074
1075
1076
1077
1078
1079
1080
1081
   * Returns a list of non-aggregates to be added to the "group by" clause.
   *
   * Non-aggregates are fields that have no aggregation function (count, sum,
   * etc) applied. Since the SQL standard requires all fields to either have
   * an aggregation function applied, or to be in the GROUP BY clause, Views
   * gathers those fields and adds them to the GROUP BY clause.
   *
   * @return array
   *   An array of the fieldnames which are non-aggregates.
merlinofchaos's avatar
merlinofchaos committed
1082
   */
1083
  protected function getNonAggregates() {
merlinofchaos's avatar
merlinofchaos committed
1084
    $non_aggregates = array();
1085
    foreach ($this->fields as $field) {
merlinofchaos's avatar
merlinofchaos committed
1086
1087
1088
1089
1090
1091
1092
1093
      $string = '';
      if (!empty($field['table'])) {
        $string .= $field['table'] . '.';
      }
      $string .= $field['field'];
      $fieldname = (!empty($field['alias']) ? $field['alias'] : $string);

      if (!empty($field['count'])) {
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
        // Retained for compatibility.
        $field['function'] = 'count';
      }

      if (!empty($field['function'])) {
        $this->has_aggregate = TRUE;
      }
      // This is a formula, using no tables.
      elseif (empty($field['table'])) {
        $non_aggregates[] = $fieldname;
      }
      elseif (empty($field['aggregate'])) {
        $non_aggregates[] = $fieldname;
      }

      if ($this->get_count_optimized) {
        // We only want the first field in this case.
        break;
      }
    }

    return $non_aggregates;
  }

  /**
   * Adds fields to the query.
   *
   * @param Drupal\Core\Database\Query\SelectInterface $query
   *   The drupal query object.
   */
1124
  protected function compileFields($query) {
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
    foreach ($this->fields as $field) {
      $string = '';
      if (!empty($field['table'])) {
        $string .= $field['table'] . '.';
      }
      $string .= $field['field'];
      $fieldname = (!empty($field['alias']) ? $field['alias'] : $string);

      if (!empty($field['count'])) {
        // Retained for compatibility.
merlinofchaos's avatar
merlinofchaos committed
1135
1136
1137
1138
        $field['function'] = 'count';
      }

      if (!empty($field['function'])) {
1139
        $info = $this->getAggregationInfo();
1140
1141
        if (!empty($info[$field['function']]['method']) && is_callable(array($this, $info[$field['function']]['method']))) {
          $string = $this::$info[$field['function']]['method']($field['function'], $string);
merlinofchaos's avatar
merlinofchaos committed
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
          $placeholders = !empty($field['placeholders']) ? $field['placeholders'] : array();
          $query->addExpression($string, $fieldname, $placeholders);
        }

        $this->has_aggregate = TRUE;
      }
      // This is a formula, using no tables.
      elseif (empty($field['table'])) {
        $placeholders = !empty($field['placeholders']) ? $field['placeholders'] : array();
        $query->addExpression($string, $fieldname, $placeholders);
      }
      elseif ($this->distinct && !in_array($fieldname, $this->groupby)) {
1154
        $query->addField(!empty($field['table']) ? $field['table'] : $this->view->storage->get('base_table'), $field['field'], $fieldname);
merlinofchaos's avatar
merlinofchaos committed
1155
1156
      }
      elseif (empty($field['aggregate'])) {
1157
        $query->addField(!empty($field['table']) ? $field['table'] : $this->view->storage->get('base_table'), $field['field'], $fieldname);
merlinofchaos's avatar
merlinofchaos committed
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
      }

      if ($this->get_count_optimized) {
        // We only want the first field in this case.
        break;
      }
    }
  }

  /**
   * Generate a query and a countquery from all of the information supplied
   * to the object.
   *
   * @param $get_count
   *   Provide a countquery if this is true, otherwise provide a normal query.
   */
1174
  public function query($get_count = FALSE) {
merlinofchaos's avatar
merlinofchaos committed
1175
1176
    // Check query distinct value.
    if (empty($this->no_distinct) && $this->distinct && !empty($this->fields)) {
1177
      $base_field_alias = $this->addField($this->view->storage->get('base_table'), $this->view->storage->get('base_field'));
1178
      $this->addGroupBy($base_field_alias);
merlinofchaos's avatar
merlinofchaos committed
1179
1180
1181
1182
1183
1184
1185
1186
      $distinct = TRUE;
    }

    /**
     * An optimized count query includes just the base field instead of all the fields.
     * Determine of this query qualifies by checking for a groupby or distinct.
     */
    if ($get_count && !$this->groupby) {
1187
      foreach ($this->fields as $field) {
merlinofchaos's avatar
merlinofchaos committed
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
        if (!empty($field['distinct']) || !empty($field['function'])) {
          $this->get_count_optimized = FALSE;
          break;
        }
      }
    }
    else {
      $this->get_count_optimized = FALSE;
    }
    if (!isset($this->get_count_optimized)) {
      $this->get_count_optimized = TRUE;
    }

    $options = array();
    $target = 'default';
    $key = 'default';
    // Detect an external database and set the
    if (isset($this->view->base_database)) {
      $key = $this->view->base_database;
    }

    // Set the slave target if the slave option is set
    if (!empty($this->options['slave'])) {
      $target = 'slave';
    }

    // Go ahead and build the query.
    // db_select doesn't support to specify the key, so use getConnection directly.
    $query = Database::getConnection($target, $key)
1217
      ->select($this->view->storage->get('base_table'), $this->view->storage->get('base_table'), $options)
merlinofchaos's avatar
merlinofchaos committed
1218
      ->addTag('views')
1219
      ->addTag('views_' . $this->view->storage->id());
merlinofchaos's avatar
merlinofchaos committed
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235

    // Add the tags added to the view itself.
    foreach ($this->tags as $tag) {
      $query->addTag($tag);
    }

    if (!empty($distinct)) {
      $query->distinct();
    }

    $joins = $where = $having = $orderby = $groupby = '';
    $fields = $distinct = array();

    // Add all the tables to the query via joins. We assume all LEFT joins.
    foreach ($this->table_queue as $table) {
      if (is_object($table['join'])) {
1236
        $table['join']->buildJoin($query, $table, $this);
merlinofchaos's avatar
merlinofchaos committed
1237
1238
1239
      }
    }

1240
    // Assemble the groupby clause, if any.
merlinofchaos's avatar
merlinofchaos committed
1241
    $this->has_aggregate = FALSE;
1242
    $non_aggregates = $this->getNonAggregates();
merlinofchaos's avatar
merlinofchaos committed
1243
1244
1245
    if (count($this->having)) {
      $this->has_aggregate = TRUE;
    }
1246
    $groupby = array();
merlinofchaos's avatar
merlinofchaos committed
1247
1248
    if ($this->has_aggregate && (!empty($this->groupby) || !empty($non_aggregates))) {
      $groupby = array_unique(array_merge($this->groupby, $non_aggregates));
1249
1250
    }

1251
1252
    // Make sure each entity table has the base field added so that the
    // entities can be loaded.
1253
    $entity_tables = $this->getEntityTables();
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
    if ($entity_tables) {
      $params = array();
      if ($groupby) {
        // Handle grouping, by retrieving the minimum entity_id.
        $params = array(
          'function' => 'min',
        );
      }

      foreach ($entity_tables as $table_alias => $table) {
        $info = entity_get_info($table['entity_type']);
1265
        $base_field = empty($table['revision']) ? $info['entity_keys']['id'] : $info['entity_keys']['revision'];
1266
        $this->addField($table_alias, $base_field, '', $params);
1267
1268
1269
      }
    }

1270
    // Add all fields to the query.
1271
    $this->compileFields($query);
1272
1273
1274

    // Add groupby.
    if ($groupby) {
merlinofchaos's avatar
merlinofchaos committed
1275
1276
1277
      foreach ($groupby as $field) {
        $query->groupBy($field);
      }
1278
      if (!empty($this->having) && $condition = $this->buildCondition('having')) {
merlinofchaos's avatar
merlinofchaos committed
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
        $query->havingCondition($condition);
      }
    }

    if (!$this->get_count_optimized) {
      // we only add the orderby if we're not counting.
      if ($this->orderby) {
        foreach ($this->orderby as $order) {
          if ($order['field'] == 'rand_') {
            $query->orderRandom();
          }
          else {
            $query->orderBy($order['field'], $order['direction']);
          }
        }
      }
    }

1297
    if (!empty($this->where) && $condition = $this->buildCondition('where')) {
merlinofchaos's avatar
merlinofchaos committed
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
      $query->condition($condition);
    }

    // Add a query comment.
    if (!empty($this->options['query_comment'])) {
      $query->comment($this->options['query_comment']);
    }

    // Add the query tags.
    if (!empty($this->options['query_tags'])) {
      foreach ($this->options['query_tags'] as $tag) {
        $query->addTag($tag);
      }
    }

    // Add all query substitutions as metadata.
1314
    $query->addMetaData('views_substitutions', \Drupal::moduleHandler()->invokeAll('views_query_substitutions', array($this->view)));
merlinofchaos's avatar
merlinofchaos committed
1315
1316
1317
1318
1319
1320
1321

    return $query;
  }

  /**
   * Get the arguments attached to the WHERE and HAVING clauses of this query.
   */
1322
  public function getWhereArgs() {
merlinofchaos's avatar
merlinofchaos committed
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
    $args = array();
    foreach ($this->where as $group => $where) {
      $args = array_merge($args, $where['args']);
    }
    foreach ($this->having as $group => $having) {
      $args = array_merge($args, $having['args']);
    }
    return $args;
  }

  /**
   * Let modules modify the query just prior to finalizing it.
   */
1336
  function alter(ViewExecutable $view) {
1337
    \Drupal::moduleHandler()->invokeAll('views_query_alter', array($view, $this));
merlinofchaos's avatar
merlinofchaos committed
1338
1339
1340
1341
1342
  }

  /**
   * Builds the necessary info to execute the query.
   */
1343
  function build(ViewExecutable $view) {
merlinofchaos's avatar
merlinofchaos committed
1344
1345
    // Make the query distinct if the option was set.
    if (!empty($this->options['distinct'])) {
1346
      $this->setDistinct(TRUE);
merlinofchaos's avatar
merlinofchaos committed
1347
1348
1349
1350
1351
    }

    // Store the view in the object to be able to use it later.
    $this->view = $view;

1352
    $view->initPager();
merlinofchaos's avatar
merlinofchaos committed
1353
1354

    // Let the pager modify the query to add limits.
1355
    $view->pager->query();
merlinofchaos's avatar
merlinofchaos committed
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367

    $view->build_info['query'] = $this->query();
    $view->build_info['count_query'] = $this->query(TRUE);
  }

  /**
   * Executes the query and fills the associated view object with according
   * values.
   *
   * Values to set: $view->result, $view->total_rows, $view->execute_time,
   * $view->current_page.
   */
1368
  function execute(ViewExecutable $view) {
merlinofchaos's avatar
merlinofchaos committed
1369
1370
1371
1372
1373
1374
1375
1376
    $external = FALSE; // Whether this query will run against an external database.
    $query = $view->build_info['query'];
    $count_query = $view->build_info['count_query'];

    $query->addMetaData('view', $view);
    $count_query->addMetaData('view', $view);

    if (empty($this->options['disable_sql_rewrite'])) {
1377
      $base_table_data = Views::viewsData()->get($this->view->storage->get('base_table'));
merlinofchaos's avatar
merlinofchaos committed
1378
1379
1380
1381
1382
1383
1384
1385
1386
      if (isset($base_table_data['table']['base']['access query tag'])) {
        $access_tag = $base_table_data['table']['base']['access query tag'];
        $query->addTag($access_tag);
        $count_query->addTag($access_tag);
      }
    }

    $items = array();
    if ($query) {
1387
      $additional_arguments = \Drupal::moduleHandler()->invokeAll('views_query_substitutions', array($view));
merlinofchaos's avatar
merlinofchaos committed
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411

      // Count queries must be run through the preExecute() method.
      // If not, then hook_query_node_access_alter() may munge the count by
      // adding a distinct against an empty query string
      // (e.g. COUNT DISTINCT(1) ...) and no pager will return.
      // See pager.inc > PagerDefault::execute()
      // http://api.drupal.org/api/drupal/includes--pager.inc/function/PagerDefault::execute/7
      // See http://drupal.org/node/1046170.
      $count_query->preExecute();

      // Build the count query.
      $count_query = $count_query->countQuery();

      // Add additional arguments as a fake condition.
      // XXX: this doesn't work... because PDO mandates that all bound arguments
      // are used on the query. TODO: Find a better way to do this.
      if (!empty($additional_arguments)) {
        // $query->where('1 = 1', $additional_arguments);
        // $count_query->where('1 = 1', $additional_arguments);
      }

      $start = microtime(TRUE);

      try {
1412
        if ($view->pager->useCountQuery() || !empty($view->get_total_rows)) {
1413
          $view->pager->executeCountQuery($count_query);
merlinofchaos's avatar
merlinofchaos committed
1414
1415
1416
        }

        // Let the pager modify the query to add limits.
1417
        $view->pager->preExecute($query);
merlinofchaos's avatar
merlinofchaos committed
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432

        if (!empty($this->limit) || !empty($this->offset)) {
          // We can't have an offset without a limit, so provide a very large limit instead.
          $limit  = intval(!empty($this->limit) ? $this->limit : 999999);
          $offset = intval(!empty($this->offset) ? $this->offset : 0);
          $query->range($offset, $limit);
        }

        $result = $query->execute();

        $view->result = array();
        foreach ($result as $item) {
          $view->result[] = $item;
        }

1433
        $view->pager->postExecute($view->result);
1434
        if ($view->pager->useCountQuery() || !empty($view->get_total_rows)) {
1435
          $view->total_rows = $view->pager->getTotalItems();
merlinofchaos's avatar
merlinofchaos committed
1436
        }
1437
1438

        // Load all entities contained in the results.
1439
        $this->loadEntities($view->result);
merlinofchaos's avatar
merlinofchaos committed
1440
      }
1441
      catch (DatabaseExceptionWrapper $e) {
merlinofchaos's avatar
merlinofchaos committed
1442
1443
1444
1445
1446
        $view->result = array();
        if (!empty($view->live_preview)) {
          drupal_set_message($e->getMessage(), 'error');
        }
        else {
1447
          throw new DatabaseExceptionWrapper(format_string('Exception in @label[@view_name]: @message', array('@label' => $view->storage->label(), '@view_name' => $view->storage->id(), '@message' => $e->getMessage())));
merlinofchaos's avatar
merlinofchaos committed
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
        }
      }

    }
    else {
      $start = microtime(TRUE);
    }
    $view->execute_time = microtime(TRUE) - $start;
  }

1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
  /**
   * Returns an array of all tables from the query that map to an entity type.
   *
   * Includes the base table and all relationships, if eligible.
   * Available keys for each table:
   * - base: The actual base table (i.e. "user" for an author relationship).
   * - relationship_id: The id of the relationship, or "none".
   * - entity_type: The entity type matching the base table.
   * - revision: A boolean that specifies whether the table is a base table or
   *   a revision table of the entity type.
   *
   * @return array
   *   An array of table information, keyed by table alias.
   */
1472
  public function getEntityTables() {
1473
1474
    // Start with the base table.
    $entity_tables = array();
1475
    $views_data = Views::viewsData();
1476
    $base_table_data = $views_data->get($this->view->storage->get('base_table'));
1477
    if (isset($base_table_data['table']['entity type'])) {
1478
1479
      $entity_tables[$this->view->storage->get('base_table')] = array(
        'base' => $this->view->storage->get('base_table'),
1480
1481
1482
1483
1484
1485
1486
        'relationship_id' => 'none',
        'entity_type' => $base_table_data['table']['entity type'],
        'revision' => FALSE,
      );
    }
    // Include all relationships.
    foreach ($this->view->relationship as $relationship_id => $relationship) {
1487
      $table_data = $views_data->get($relationship->definition['base']);
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
      if (isset($table_data['table']['entity type'])) {
        $entity_tables[$relationship->alias] = array(
          'base' => $relationship->definition['base'],
          'relationship_id' => $relationship_id,
          'entity_type' => $table_data['table']['entity type'],
          'revision' => FALSE,
        );
      }
    }

    // Determine which of the tables are revision tables.
    foreach ($entity_tables as $table_alias => $table) {
      $info = entity_get_info($table['entity_type']);
      if (isset($info['revision table']) && $info['revision table'] == $table['base']) {
        $entity_tables[$table_alias]['revision'] = TRUE;
      }
    }

    return $entity_tables;
  }

  /**
   * Loads all entities contained in the passed-in $results.
   *.
   * If the entity belongs to the base table, then it gets stored in
   * $result->_entity. Otherwise, it gets stored in
   * $result->_relationship_entities[$relationship_id];
   */
1516
  function loadEntities(&$results) {
1517
    $entity_tables = $this->getEntityTables();
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
    // No entity tables found, nothing else to do here.
    if (empty($entity_tables)) {
      return;
    }

     // Initialize the entity placeholders in $results.
    foreach ($results as $index => $result) {
      $results[$index]->_entity = FALSE;
      $results[$index]->_relationship_entities = array();
    }

    // Assemble a list of entities to load.
    $ids_by_table = array();
    foreach ($entity_tables as $table_alias => $table) {
      $entity_type = $table['entity_type'];
      $info = entity_get_info($entity_type);
1534
      $id_key = empty($table['revision']) ? $info['entity_keys']['id'] : $info['entity_keys']['revision'];
1535
      $id_alias = $this->getFieldAlias($table_alias, $id_key);
1536
1537
1538

      foreach ($results as $index => $result) {
        // Store the entity id if it was found.
1539
        if (isset($result->{$id_alias}) && $result->{$id_alias} != '') {
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
          $ids_by_table[$table_alias][$index] = $result->$id_alias;
        }
      }
    }

    // Load all entities and assign them to the correct result row.
    foreach ($ids_by_table as $table_alias => $ids) {
      $table = $entity_tables[$table_alias];
      $entity_type = $table['entity_type'];
      $relationship_id = $table['relationship_id'];

      // Drupal core currently has no way to load multiple revisions. Sad.
      if ($table['revision']) {
        $entities = array();
        foreach ($ids as $index => $revision_id) {
          $entity = entity_revision_load($entity_type, $revision_id);
          if ($entity) {
            $entities[$revision_id] = $entity;
          }
        }
      }
      else {
        $entities = entity_load_multiple($entity_type, $ids);
      }

      foreach ($ids as $index => $id) {
        $entity = isset($entities[$id]) ? $entities[$id] : FALSE;

        if ($relationship_id == 'none') {
          $results[$index]->_entity = $entity;
        }
        else {
          $results[$index]->_relationship_entities[$relationship_id] = $entity;
        }
      }
    }
  }

1578
  public function addSignature(ViewExecutable $view) {
1579
    $view->query->addField(NULL, "'" . $view->storage->id() . ':' . $view->current_display . "'", 'view_name');
merlinofchaos's avatar
merlinofchaos committed
1580
1581
  }

1582
  public function getAggregationInfo() {
merlinofchaos's avatar
merlinofchaos committed
1583
1584
1585
1586
1587
1588
1589
1590
1591
    // @todo -- need a way to get database specific and customized aggregation
    // functions into here.
    return array(
      'group' => array(
        'title' => t('Group results together'),
        'is aggregate' => FALSE,
      ),
      'count' => array(
        'title' => t('Count'),
1592
        'method' => 'aggregationMethodSimple',
merlinofchaos's avatar
merlinofchaos committed
1593
        'handler' => array(
1594
          'argument' => 'groupby_numeric',
1595
          'field' => 'numeric',
dawehner's avatar
dawehner committed
1596
          'filter' => 'groupby_numeric',
1597
          'sort' => 'groupby_numeric',
merlinofchaos's avatar
merlinofchaos committed
1598
1599
1600
1601
        ),
      ),
      'count_distinct' => array(
        'title' => t('Count DISTINCT'),
1602
        'method' => 'aggregationMethodDistinct',
merlinofchaos's avatar
merlinofchaos committed
1603
        'handler' => array(
1604
          'argument' => 'groupby_numeric',
1605
          'field' => 'numeric',
dawehner's avatar
dawehner committed
1606
          'filter' => 'groupby_numeric',
1607